diff --git a/.gitignore b/.gitignore index 1890e8bd0e..08f570ad06 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,5 @@ SpringDataInjectionDemo/.mvn/wrapper/maven-wrapper.properties spring-call-getters-using-reflection/.mvn/wrapper/maven-wrapper.properties spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties +*.springBeans + diff --git a/README.md b/README.md index f0d3d29da7..25398d1d39 100644 --- a/README.md +++ b/README.md @@ -23,4 +23,4 @@ Any IDE can be used to work with the projects, but if you're using Eclipse, cons CI - Jenkins ================================ -This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials/)** +This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/github%20projects%20Jobs/job/tutorials/)** diff --git a/algorithms/README.md b/algorithms/README.md index dc12b528da..8cf4c35b68 100644 --- a/algorithms/README.md +++ b/algorithms/README.md @@ -8,3 +8,4 @@ - [Check If a Number Is Prime in Java](http://www.baeldung.com/java-prime-numbers) - [Example of Hill Climbing Algorithm](http://www.baeldung.com/java-hill-climbing-algorithm) - [Monte Carlo Tree Search for Tic-Tac-Toe Game](http://www.baeldung.com/java-monte-carlo-tree-search) +- [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms) diff --git a/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java b/algorithms/src/main/java/com/baeldung/algorithms/binarysearch/BinarySearch.java similarity index 93% rename from algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java rename to algorithms/src/main/java/com/baeldung/algorithms/binarysearch/BinarySearch.java index 86522950ef..5b2ac49d4e 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/binarysearch/BinarySearch.java @@ -1,3 +1,5 @@ +package com.baeldung.algorithms.binarysearch; + import java.util.Arrays; import java.util.Collections; import java.util.List; diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForce.java b/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForce.java new file mode 100644 index 0000000000..1df425ad2e --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForce.java @@ -0,0 +1,38 @@ +package com.baeldung.algorithms.linkedlist; + +public class CycleDetectionBruteForce { + + public static CycleDetectionResult detectCycle(Node head) { + if (head == null) { + return new CycleDetectionResult<>(false, null); + } + + Node it1 = head; + int nodesTraversedByOuter = 0; + while (it1 != null && it1.next != null) { + it1 = it1.next; + nodesTraversedByOuter++; + + int x = nodesTraversedByOuter; + Node it2 = head; + int noOfTimesCurrentNodeVisited = 0; + + while (x > 0) { + it2 = it2.next; + + if (it2 == it1) { + noOfTimesCurrentNodeVisited++; + } + + if (noOfTimesCurrentNodeVisited == 2) { + return new CycleDetectionResult<>(true, it1); + } + + x--; + } + } + + return new CycleDetectionResult<>(false, null); + } + +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIterators.java b/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIterators.java new file mode 100644 index 0000000000..ab088de44a --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIterators.java @@ -0,0 +1,25 @@ +package com.baeldung.algorithms.linkedlist; + +public class CycleDetectionByFastAndSlowIterators { + + public static CycleDetectionResult detectCycle(Node head) { + if (head == null) { + return new CycleDetectionResult<>(false, null); + } + + Node slow = head; + Node fast = head; + + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + + if (slow == fast) { + return new CycleDetectionResult<>(true, fast); + } + } + + return new CycleDetectionResult<>(false, null); + } + +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashing.java b/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashing.java new file mode 100644 index 0000000000..90d5ecd711 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashing.java @@ -0,0 +1,27 @@ +package com.baeldung.algorithms.linkedlist; + +import java.util.HashSet; +import java.util.Set; + +public class CycleDetectionByHashing { + + public static CycleDetectionResult detectCycle(Node head) { + if (head == null) { + return new CycleDetectionResult<>(false, null); + } + + Set> set = new HashSet<>(); + Node node = head; + + while (node != null) { + if (set.contains(node)) { + return new CycleDetectionResult<>(true, node); + } + set.add(node); + node = node.next; + } + + return new CycleDetectionResult<>(false, null); + } + +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionResult.java b/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionResult.java new file mode 100644 index 0000000000..e7556311b3 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionResult.java @@ -0,0 +1,12 @@ +package com.baeldung.algorithms.linkedlist; + +public class CycleDetectionResult { + boolean cycleExists; + Node node; + + public CycleDetectionResult(boolean cycleExists, Node node) { + super(); + this.cycleExists = cycleExists; + this.node = node; + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForce.java b/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForce.java new file mode 100644 index 0000000000..a2bfaee9a1 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForce.java @@ -0,0 +1,56 @@ +package com.baeldung.algorithms.linkedlist; + +public class CycleRemovalBruteForce { + + public static boolean detectAndRemoveCycle(Node head) { + CycleDetectionResult result = CycleDetectionByFastAndSlowIterators.detectCycle(head); + + if (result.cycleExists) { + removeCycle(result.node, head); + } + + return result.cycleExists; + } + + /** + * @param loopNodeParam - reference to the node where Flyods cycle + * finding algorithm ends, i.e. the fast and the slow iterators + * meet. + * @param head - reference to the head of the list + */ + private static void removeCycle(Node loopNodeParam, Node head) { + Node it = head; + + while (it != null) { + if (isNodeReachableFromLoopNode(it, loopNodeParam)) { + Node loopStart = it; + findEndNodeAndBreakCycle(loopStart); + break; + } + it = it.next; + } + } + + private static boolean isNodeReachableFromLoopNode(Node it, Node loopNodeParam) { + Node loopNode = loopNodeParam; + + do { + if (it == loopNode) { + return true; + } + loopNode = loopNode.next; + } while (loopNode.next != loopNodeParam); + + return false; + } + + private static void findEndNodeAndBreakCycle(Node loopStartParam) { + Node loopStart = loopStartParam; + + while (loopStart.next != loopStartParam) { + loopStart = loopStart.next; + } + + loopStart.next = null; + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodes.java b/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodes.java new file mode 100644 index 0000000000..d8db37fc4c --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodes.java @@ -0,0 +1,44 @@ +package com.baeldung.algorithms.linkedlist; + +public class CycleRemovalByCountingLoopNodes { + + public static boolean detectAndRemoveCycle(Node head) { + CycleDetectionResult result = CycleDetectionByFastAndSlowIterators.detectCycle(head); + + if (result.cycleExists) { + removeCycle(result.node, head); + } + + return result.cycleExists; + } + + private static void removeCycle(Node loopNodeParam, Node head) { + int cycleLength = calculateCycleLength(loopNodeParam); + Node cycleLengthAdvancedIterator = head; + Node it = head; + + for (int i = 0; i < cycleLength; i++) { + cycleLengthAdvancedIterator = cycleLengthAdvancedIterator.next; + } + + while (it.next != cycleLengthAdvancedIterator.next) { + it = it.next; + cycleLengthAdvancedIterator = cycleLengthAdvancedIterator.next; + } + + cycleLengthAdvancedIterator.next = null; + } + + private static int calculateCycleLength(Node loopNodeParam) { + Node loopNode = loopNodeParam; + int length = 1; + + while (loopNode.next != loopNodeParam) { + length++; + loopNode = loopNode.next; + } + + return length; + } + +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodes.java b/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodes.java new file mode 100644 index 0000000000..b979f7f677 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodes.java @@ -0,0 +1,27 @@ +package com.baeldung.algorithms.linkedlist; + +public class CycleRemovalWithoutCountingLoopNodes { + + public static boolean detectAndRemoveCycle(Node head) { + CycleDetectionResult result = CycleDetectionByFastAndSlowIterators.detectCycle(head); + + if (result.cycleExists) { + removeCycle(result.node, head); + } + + return result.cycleExists; + } + + private static void removeCycle(Node meetingPointParam, Node head) { + Node loopNode = meetingPointParam; + Node it = head; + + while (loopNode.next != it.next) { + it = it.next; + loopNode = loopNode.next; + } + + loopNode.next = null; + } + +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/Node.java b/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/Node.java new file mode 100644 index 0000000000..4add22c77d --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/Node.java @@ -0,0 +1,38 @@ +package com.baeldung.algorithms.linkedlist; + +public class Node { + T data; + Node next; + + public static Node createNewNode(T data, Node next) { + Node node = new Node(); + node.data = data; + node.next = next; + return node; + } + + public static void traverseList(Node root) { + if (root == null) { + return; + } + + Node node = root; + while (node != null) { + System.out.println(node.data); + node = node.next; + } + } + + public static Node getTail(Node root) { + if (root == null) { + return null; + } + + Node node = root; + while (node.next != null) { + node = node.next; + } + return node; + } + +} \ No newline at end of file diff --git a/algorithms/src/main/java/com/baeldung/algorithms/string/search/StringSearchAlgorithms.java b/algorithms/src/main/java/com/baeldung/algorithms/string/search/StringSearchAlgorithms.java new file mode 100755 index 0000000000..45ac53e039 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/string/search/StringSearchAlgorithms.java @@ -0,0 +1,194 @@ +package com.baeldung.algorithms.string.search; + +import java.math.BigInteger; +import java.util.Random; + +public class StringSearchAlgorithms { + public static long getBiggerPrime(int m) { + BigInteger prime = BigInteger.probablePrime(getNumberOfBits(m) + 1, new Random()); + return prime.longValue(); + } + + public static long getLowerPrime(long number) { + BigInteger prime = BigInteger.probablePrime(getNumberOfBits(number) - 1, new Random()); + return prime.longValue(); + } + + private static int getNumberOfBits(final int number) { + return Integer.SIZE - Integer.numberOfLeadingZeros(number); + } + + private static int getNumberOfBits(final long number) { + return Long.SIZE - Long.numberOfLeadingZeros(number); + } + + public static int simpleTextSearch(char[] pattern, char[] text) { + int patternSize = pattern.length; + int textSize = text.length; + + int i = 0; + + while ((i + patternSize) <= textSize) { + int j = 0; + while (text[i + j] == pattern[j]) { + j += 1; + if (j >= patternSize) + return i; + } + i += 1; + } + + return -1; + } + + public static int RabinKarpMethod(char[] pattern, char[] text) { + int patternSize = pattern.length; // m + int textSize = text.length; // n + + long prime = getBiggerPrime(patternSize); + + long r = 1; + for (int i = 0; i < patternSize - 1; i++) { + r *= 2; + r = r % prime; + } + + long[] t = new long[textSize]; + t[0] = 0; + + long pfinger = 0; + + for (int j = 0; j < patternSize; j++) { + t[0] = (2 * t[0] + text[j]) % prime; + pfinger = (2 * pfinger + pattern[j]) % prime; + } + + int i = 0; + boolean passed = false; + + int diff = textSize - patternSize; + for (i = 0; i <= diff; i++) { + if (t[i] == pfinger) { + passed = true; + for (int k = 0; k < patternSize; k++) { + if (text[i + k] != pattern[k]) { + passed = false; + break; + } + } + + if (passed) { + return i; + } + } + + if (i < diff) { + long value = 2 * (t[i] - r * text[i]) + text[i + patternSize]; + t[i + 1] = ((value % prime) + prime) % prime; + } + } + return -1; + + } + + public static int KnuthMorrisPrattSearch(char[] pattern, char[] text) { + int patternSize = pattern.length; // m + int textSize = text.length; // n + + int i = 0, j = 0; + + int[] shift = KnuthMorrisPrattShift(pattern); + + while ((i + patternSize) <= textSize) { + while (text[i + j] == pattern[j]) { + j += 1; + if (j >= patternSize) + return i; + } + + if (j > 0) { + i += shift[j - 1]; + j = Math.max(j - shift[j - 1], 0); + } else { + i++; + j = 0; + } + } + return -1; + } + + public static int[] KnuthMorrisPrattShift(char[] pattern) { + int patternSize = pattern.length; + + int[] shift = new int[patternSize]; + shift[0] = 1; + + int i = 1, j = 0; + + while ((i + j) < patternSize) { + if (pattern[i + j] == pattern[j]) { + shift[i + j] = i; + j++; + } else { + if (j == 0) + shift[i] = i + 1; + + if (j > 0) { + i = i + shift[j - 1]; + j = Math.max(j - shift[j - 1], 0); + } else { + i = i + 1; + j = 0; + } + } + } + return shift; + } + + public static int BoyerMooreHorspoolSimpleSearch(char[] pattern, char[] text) { + int patternSize = pattern.length; + int textSize = text.length; + + int i = 0, j = 0; + + while ((i + patternSize) <= textSize) { + j = patternSize - 1; + while (text[i + j] == pattern[j]) { + j--; + if (j < 0) + return i; + } + i++; + } + return -1; + } + + public static int BoyerMooreHorspoolSearch(char[] pattern, char[] text) { + + int shift[] = new int[256]; + + for (int k = 0; k < 256; k++) { + shift[k] = pattern.length; + } + + for (int k = 0; k < pattern.length - 1; k++) { + shift[pattern[k]] = pattern.length - 1 - k; + } + + int i = 0, j = 0; + + while ((i + pattern.length) <= text.length) { + j = pattern.length - 1; + + while (text[i + j] == pattern[j]) { + j -= 1; + if (j < 0) + return i; + } + + i = i + shift[text[i + pattern.length - 1]]; + + } + return -1; + } +} diff --git a/algorithms/src/test/java/algorithms/StringSearchAlgorithmsTest.java b/algorithms/src/test/java/algorithms/StringSearchAlgorithmsTest.java new file mode 100755 index 0000000000..e260cd7e5b --- /dev/null +++ b/algorithms/src/test/java/algorithms/StringSearchAlgorithmsTest.java @@ -0,0 +1,25 @@ +package algorithms; + + +import org.junit.Assert; +import org.junit.Test; + +import com.baeldung.algorithms.string.search.StringSearchAlgorithms; + +public class StringSearchAlgorithmsTest { + + + @Test + public void testStringSearchAlgorithms(){ + String text = "This is some nice text."; + String pattern = "some"; + + int realPosition = text.indexOf(pattern); + Assert.assertTrue(realPosition == StringSearchAlgorithms.simpleTextSearch(pattern.toCharArray(), text.toCharArray())); + Assert.assertTrue(realPosition == StringSearchAlgorithms.RabinKarpMethod(pattern.toCharArray(), text.toCharArray())); + Assert.assertTrue(realPosition == StringSearchAlgorithms.KnuthMorrisPrattSearch(pattern.toCharArray(), text.toCharArray())); + Assert.assertTrue(realPosition == StringSearchAlgorithms.BoyerMooreHorspoolSimpleSearch(pattern.toCharArray(), text.toCharArray())); + Assert.assertTrue(realPosition == StringSearchAlgorithms.BoyerMooreHorspoolSearch(pattern.toCharArray(), text.toCharArray())); + } + +} diff --git a/algorithms/src/test/java/algorithms/BinarySearchTest.java b/algorithms/src/test/java/algorithms/binarysearch/BinarySearchTest.java similarity index 92% rename from algorithms/src/test/java/algorithms/BinarySearchTest.java rename to algorithms/src/test/java/algorithms/binarysearch/BinarySearchTest.java index 3611ec8e49..959f47a275 100644 --- a/algorithms/src/test/java/algorithms/BinarySearchTest.java +++ b/algorithms/src/test/java/algorithms/binarysearch/BinarySearchTest.java @@ -1,9 +1,11 @@ +package algorithms.binarysearch; + import java.util.Arrays; import java.util.List; import org.junit.Assert; import org.junit.Test; - +import com.baeldung.algorithms.binarysearch.BinarySearch; public class BinarySearchTest { diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceTest.java new file mode 100644 index 0000000000..7f9b8acdbd --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceTest.java @@ -0,0 +1,23 @@ +package com.baeldung.algorithms.linkedlist; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(value = Parameterized.class) +public class CycleDetectionBruteForceTest extends CycleDetectionTestBase { + boolean cycleExists; + Node head; + + public CycleDetectionBruteForceTest(Node head, boolean cycleExists) { + super(); + this.cycleExists = cycleExists; + this.head = head; + } + + @Test + public void givenList_detectLoop() { + Assert.assertEquals(cycleExists, CycleDetectionBruteForce.detectCycle(head).cycleExists); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsTest.java new file mode 100644 index 0000000000..17d339bc33 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsTest.java @@ -0,0 +1,23 @@ +package com.baeldung.algorithms.linkedlist; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(value = Parameterized.class) +public class CycleDetectionByFastAndSlowIteratorsTest extends CycleDetectionTestBase { + boolean cycleExists; + Node head; + + public CycleDetectionByFastAndSlowIteratorsTest(Node head, boolean cycleExists) { + super(); + this.cycleExists = cycleExists; + this.head = head; + } + + @Test + public void givenList_detectLoop() { + Assert.assertEquals(cycleExists, CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingTest.java new file mode 100644 index 0000000000..73a2cc7861 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingTest.java @@ -0,0 +1,23 @@ +package com.baeldung.algorithms.linkedlist; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(value = Parameterized.class) +public class CycleDetectionByHashingTest extends CycleDetectionTestBase { + boolean cycleExists; + Node head; + + public CycleDetectionByHashingTest(Node head, boolean cycleExists) { + super(); + this.cycleExists = cycleExists; + this.head = head; + } + + @Test + public void givenList_detectLoop() { + Assert.assertEquals(cycleExists, CycleDetectionByHashing.detectCycle(head).cycleExists); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionTestBase.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionTestBase.java new file mode 100644 index 0000000000..51906de8e5 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionTestBase.java @@ -0,0 +1,62 @@ +package com.baeldung.algorithms.linkedlist; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.runners.Parameterized.Parameters; + +public class CycleDetectionTestBase { + + @Parameters + public static Collection getLists() { + return Arrays.asList(new Object[][] { + { createList(), false }, + { createListWithLoop(), true }, + { createListWithFullCycle(), true }, + { createListWithSingleNodeInCycle(), true } + }); + } + + public static Node createList() { + Node root = Node.createNewNode(10, null); + + for (int i = 9; i >= 1; --i) { + Node current = Node.createNewNode(i, root); + root = current; + } + + return root; + } + + public static Node createListWithLoop() { + Node node = createList(); + createLoop(node); + return node; + } + + public static Node createListWithFullCycle() { + Node head = createList(); + Node tail = Node.getTail(head); + tail.next = head; + return head; + } + + public static Node createListWithSingleNodeInCycle() { + Node head = createList(); + Node tail = Node.getTail(head); + tail.next = tail; + return head; + } + + public static void createLoop(Node root) { + Node tail = Node.getTail(root); + + Node middle = root; + for (int i = 1; i <= 4; i++) { + middle = middle.next; + } + + tail.next = middle; + } + +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceTest.java new file mode 100644 index 0000000000..6484c9988e --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceTest.java @@ -0,0 +1,24 @@ +package com.baeldung.algorithms.linkedlist; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(value = Parameterized.class) +public class CycleRemovalBruteForceTest extends CycleDetectionTestBase { + boolean cycleExists; + Node head; + + public CycleRemovalBruteForceTest(Node head, boolean cycleExists) { + super(); + this.cycleExists = cycleExists; + this.head = head; + } + + @Test + public void givenList_ifLoopExists_thenDetectAndRemoveLoop() { + Assert.assertEquals(cycleExists, CycleRemovalBruteForce.detectAndRemoveCycle(head)); + Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesTest.java new file mode 100644 index 0000000000..7bfd89c502 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesTest.java @@ -0,0 +1,24 @@ +package com.baeldung.algorithms.linkedlist; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(value = Parameterized.class) +public class CycleRemovalByCountingLoopNodesTest extends CycleDetectionTestBase { + boolean cycleExists; + Node head; + + public CycleRemovalByCountingLoopNodesTest(Node head, boolean cycleExists) { + super(); + this.cycleExists = cycleExists; + this.head = head; + } + + @Test + public void givenList_ifLoopExists_thenDetectAndRemoveLoop() { + Assert.assertEquals(cycleExists, CycleRemovalByCountingLoopNodes.detectAndRemoveCycle(head)); + Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesTest.java new file mode 100644 index 0000000000..c77efb3e3e --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesTest.java @@ -0,0 +1,24 @@ +package com.baeldung.algorithms.linkedlist; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(value = Parameterized.class) +public class CycleRemovalWithoutCountingLoopNodesTest extends CycleDetectionTestBase { + boolean cycleExists; + Node head; + + public CycleRemovalWithoutCountingLoopNodesTest(Node head, boolean cycleExists) { + super(); + this.cycleExists = cycleExists; + this.head = head; + } + + @Test + public void givenList_ifLoopExists_thenDetectAndRemoveLoop() { + Assert.assertEquals(cycleExists, CycleRemovalWithoutCountingLoopNodes.detectAndRemoveCycle(head)); + Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); + } +} \ No newline at end of file diff --git a/apache-shiro/README.md b/apache-shiro/README.md index e69de29bb2..bc3480b266 100644 --- a/apache-shiro/README.md +++ b/apache-shiro/README.md @@ -0,0 +1,2 @@ +### Relevant articles +- [Introduction to Apache Shiro](http://www.baeldung.com/apache-shiro) diff --git a/bootique/README.md b/bootique/README.md new file mode 100644 index 0000000000..2ef898fcf7 --- /dev/null +++ b/bootique/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to Bootique](http://www.baeldung.com/bootique) diff --git a/core-java-8/src/test/java/com/baeldung/stream/SupplierStreamTest.java b/core-java-8/src/test/java/com/baeldung/stream/SupplierStreamTest.java new file mode 100644 index 0000000000..d78c9fca35 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/stream/SupplierStreamTest.java @@ -0,0 +1,35 @@ +package com.baeldung.stream; + +import static org.junit.Assert.fail; + +import java.util.Optional; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import org.junit.Test; + +public class SupplierStreamTest { + + @Test(expected = IllegalStateException.class) + public void givenStream_whenStreamUsedTwice_thenThrowException() { + Stream stringStream = Stream.of("A", "B", "C", "D"); + Optional result1 = stringStream.findAny(); + System.out.println(result1.get()); + Optional result2 = stringStream.findFirst(); + System.out.println(result2.get()); + } + + @Test + public void givenStream_whenUsingSupplier_thenNoExceptionIsThrown() { + try { + Supplier> streamSupplier = () -> Stream.of("A", "B", "C", "D"); + Optional result1 = streamSupplier.get().findAny(); + System.out.println(result1.get()); + Optional result2 = streamSupplier.get().findFirst(); + System.out.println(result2.get()); + } catch (IllegalStateException e) { + fail(); + } + } + +} \ No newline at end of file diff --git a/core-java-9/README.md b/core-java-9/README.md index 22d6903f06..f0b2e3f206 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -8,7 +8,7 @@ - [Java 9 Stream API Improvements](http://www.baeldung.com/java-9-stream-api) - [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods) - [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors) -- [Java 9 CompletableFuture API Improvements](http://www.baeldung.com/java9-completablefuture-api-improvements/) +- [Java 9 CompletableFuture API Improvements](http://www.baeldung.com/java-9-completablefuture) - [Spring Security – Redirect to the Previous URL After Login](http://www.baeldung.com/spring-security-redirect-login) - [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api) - [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api) @@ -16,3 +16,4 @@ - [Java 9 Optional API Additions](http://www.baeldung.com/java-9-optional) - [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams) - [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates) +- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new) diff --git a/core-java-9/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java b/core-java-9/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java new file mode 100644 index 0000000000..cb24511f72 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java @@ -0,0 +1,24 @@ +package com.baeldung.java9.compactstring; + +import java.util.List; +import static java.util.stream.Collectors.toList; +import java.util.stream.IntStream; + +public class CompactStringDemo { + + public static void main(String[] args) { + long startTime = System.currentTimeMillis(); + List strings = IntStream.rangeClosed(1, 10_000_000) + .mapToObj(Integer::toString).collect(toList()); + long totalTime = System.currentTimeMillis() - startTime; + System.out.println("Generated " + strings.size() + " strings in " + + totalTime + " ms."); + + startTime = System.currentTimeMillis(); + String appended = (String) strings.stream().limit(100_000) + .reduce("", (left, right) -> left.toString() + right.toString()); + totalTime = System.currentTimeMillis() - startTime; + System.out.println("Created string of length " + appended.length() + + " in " + totalTime + " ms."); + } +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/callable/FactorialTask.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/callable/FactorialTask.java new file mode 100644 index 0000000000..8663609d2d --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/callable/FactorialTask.java @@ -0,0 +1,30 @@ +package com.baeldung.concurrent.callable; + + +import java.util.concurrent.Callable; + +public class FactorialTask implements Callable { + int number; + + public FactorialTask(int number) { + this.number = number; + } + + public Integer call() throws InvalidParamaterException { + int fact=1; + if(number < 0) + throw new InvalidParamaterException("Number must be positive"); + + for(int count=number;count>1;count--){ + fact=fact * count; + } + + return fact; + } + + private class InvalidParamaterException extends Exception { + public InvalidParamaterException(String message) { + super(message); + } + } +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/runnable/EventLoggingTask.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/runnable/EventLoggingTask.java new file mode 100644 index 0000000000..d65f79202e --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/runnable/EventLoggingTask.java @@ -0,0 +1,17 @@ +package com.baeldung.concurrent.runnable; + + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class EventLoggingTask implements Runnable{ + private Logger logger = LoggerFactory.getLogger(EventLoggingTask.class); + + @Override + public void run() { + + String messge="Message read from the event queue"; + logger.info("Message read from event queue is "+messge); + + } +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/runnable/TaskRunner.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/runnable/TaskRunner.java new file mode 100644 index 0000000000..8fd98e77b8 --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/runnable/TaskRunner.java @@ -0,0 +1,25 @@ +package com.baeldung.concurrent.runnable; + + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +public class TaskRunner { + + private static ExecutorService executorService; + + public static void main(String[] args) { + executeTask(); + } + + private static void executeTask() { + executorService= Executors.newSingleThreadExecutor(); + + EventLoggingTask task = new EventLoggingTask(); + + Future future = executorService.submit(task); + + executorService.shutdown(); + } +} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/callable/FactorialTaskManualTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/callable/FactorialTaskManualTest.java new file mode 100644 index 0000000000..c55e04af94 --- /dev/null +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/callable/FactorialTaskManualTest.java @@ -0,0 +1,48 @@ +package com.baeldung.concurrent.callable; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import static junit.framework.Assert.assertEquals; + +public class FactorialTaskManualTest { + + private ExecutorService executorService; + + @Before + public void setup(){ + executorService = Executors.newSingleThreadExecutor(); + } + + @Test + public void whenTaskSubmitted_ThenFutureResultObtained() throws ExecutionException, InterruptedException { + FactorialTask task = new FactorialTask(5); + Future future= executorService.submit(task); + assertEquals(120,future.get().intValue()); + } + + @Test(expected = ExecutionException.class) + public void whenException_ThenCallableThrowsIt() throws ExecutionException, InterruptedException { + FactorialTask task = new FactorialTask(-5); + Future future= executorService.submit(task); + Integer result=future.get().intValue(); + } + + @Test + public void whenException_ThenCallableDoesntThrowsItIfGetIsNotCalled(){ + FactorialTask task = new FactorialTask(-5); + Future future= executorService.submit(task); + assertEquals(false,future.isDone()); + } + + @After + public void cleanup(){ + executorService.shutdown(); + } +} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java index 1f8e8d681a..9c56fa64be 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java @@ -18,7 +18,7 @@ public class BaeldungSychronizedBlockTest { IntStream.range(0, 1000) .forEach(count -> service.submit(synchronizedBlocks::performSynchronisedTask)); - service.awaitTermination(100, TimeUnit.MILLISECONDS); + service.awaitTermination(500, TimeUnit.MILLISECONDS); assertEquals(1000, synchronizedBlocks.getCount()); } @@ -29,7 +29,7 @@ public class BaeldungSychronizedBlockTest { IntStream.range(0, 1000) .forEach(count -> service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask)); - service.awaitTermination(100, TimeUnit.MILLISECONDS); + service.awaitTermination(500, TimeUnit.MILLISECONDS); assertEquals(1000, BaeldungSynchronizedBlocks.getStaticCount()); } diff --git a/core-java/README.md b/core-java/README.md index 57457e90fe..0f0e4cc858 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -99,4 +99,10 @@ - [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror) - [Guide to UUID in Java](http://www.baeldung.com/java-uuid) - [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char) +- [Guide to hashCode() in Java](http://www.baeldung.com/java-hashcode) +- [Collect a Java Stream to an Immutable Collection](http://www.baeldung.com/java-stream-immutable-collection) +- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri) +- [Broadcasting and Multicasting in Java](http://www.baeldung.com/java-broadcast-multicast) +- [Converting a List to String in Java](http://www.baeldung.com/java-list-to-string) +- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string) - [Period and Duration in Java](http://www.baeldung.com/java-period-duration) diff --git a/core-java/pom.xml b/core-java/pom.xml index 586486027a..bb3958f36c 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -80,7 +80,7 @@ - + log4j log4j 1.2.17 @@ -187,15 +187,35 @@ ${fscontext.version} - joda-time - joda-time - ${joda-time.version} + com.codepoetics + protonpack + ${protonpack.version} - com.darwinsys - hirondelle-date4j - ${hirondelle-date4j.version} + one.util + streamex + ${streamex.version} + + io.vavr + vavr + ${vavr.version} + + + org.openjdk.jmh + jmh-core + 1.19 + + + org.openjdk.jmh + jmh-generator-annprocess + 1.19 + + + org.springframework + spring-web + 4.3.4.RELEASE + @@ -224,6 +244,7 @@ maven-surefire-plugin + **/*LiveTest.java **/*IntegrationTest.java **/*LongRunningUnitTest.java **/*ManualTest.java @@ -357,6 +378,8 @@ + + @@ -391,12 +414,37 @@ + + org.codehaus.mojo + exec-maven-plugin + + + + run-benchmarks + + none + + exec + + + test + java + + -classpath + + org.openjdk.jmh.Main + .* + + + + + - + 2.8.5 @@ -418,9 +466,10 @@ 1.8.7 1.16.12 4.6-b01 - 2.9.9 - 1.5.1 - + 1.13 + 0.6.5 + 0.9.0 + 1.3 4.12 @@ -428,9 +477,8 @@ 3.6.1 1.7.0 - 3.6.0 2.19.1 - + \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java index 0d69d0e7ec..79f618d038 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java @@ -5,9 +5,16 @@ import static com.baeldung.designpatterns.util.LogerUtil.LOG; public class AdapterPatternDriver { public static void main(String args[]) { - LuxuryCarsSpeedAdapter luxuryCars = new LuxuryCarsSpeedAdapterImpl(); - LOG.info("Bugatti Veyron Super Sport's top speed is " + luxuryCars.bugattiVeyronInKMPH() + " Kmph."); - LOG.info("McLaren F1 top speed is " + luxuryCars.mcLarenInKMPH() + " Kmph."); - LOG.info("Aston Martin One-77 top speed is " + luxuryCars.astonMartinInKMPH() + " Kmph."); + Movable bugattiVeyron = new BugattiVeyron(); + MovableAdapter bugattiVeyronAdapter = new MovableAdapterImpl(bugattiVeyron); + LOG.info("Bugatti Veyron Super Sport's top speed is " + bugattiVeyronAdapter.getSpeed() + " Kmph."); + + Movable mcLaren = new McLaren(); + MovableAdapter mcLarenAdapter = new MovableAdapterImpl(mcLaren); + LOG.info("McLaren F1 top speed is " + mcLarenAdapter.getSpeed() + " Kmph."); + + Movable astonMartin = new AstonMartin(); + MovableAdapter astonMartinAdapter = new MovableAdapterImpl(astonMartin); + LOG.info("McLaren F1 top speed is " + astonMartinAdapter.getSpeed() + " Kmph."); } } diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/AstonMartin.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/AstonMartin.java new file mode 100644 index 0000000000..7dd83079a2 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/AstonMartin.java @@ -0,0 +1,8 @@ +package com.baeldung.designpatterns.adapter; + +public class AstonMartin implements Movable { + @Override + public double getSpeed() { + return 220; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/BugattiVeyron.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/BugattiVeyron.java new file mode 100644 index 0000000000..a249d64b6f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/BugattiVeyron.java @@ -0,0 +1,8 @@ +package com.baeldung.designpatterns.adapter; + +public class BugattiVeyron implements Movable { + @Override + public double getSpeed() { + return 268; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java deleted file mode 100644 index 0b97b8228c..0000000000 --- a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.designpatterns.adapter; - -public class LuxuryCarsSpeed { - public double bugattiVeyronInMPH() { - return 268; - } - - public double mcLarenInMPH() { - return 241; - } - - public double astonMartinInMPH() { - return 220; - } -} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java deleted file mode 100644 index d9255f0910..0000000000 --- a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.designpatterns.adapter; - -public interface LuxuryCarsSpeedAdapter { - public double bugattiVeyronInKMPH(); - - public double mcLarenInKMPH(); - - public double astonMartinInKMPH(); -} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java deleted file mode 100644 index 2767b78e38..0000000000 --- a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.designpatterns.adapter; - -public class LuxuryCarsSpeedAdapterImpl extends LuxuryCarsSpeed implements LuxuryCarsSpeedAdapter { - - @Override - public double bugattiVeyronInKMPH() { - double mph = super.bugattiVeyronInMPH(); - return convertMPHtoKMPH(mph); - } - - @Override - public double mcLarenInKMPH() { - double mph = super.mcLarenInMPH(); - return convertMPHtoKMPH(mph); - } - - @Override - public double astonMartinInKMPH() { - double mph = super.astonMartinInMPH(); - return convertMPHtoKMPH(mph); - } - - private double convertMPHtoKMPH(double mph) { - return mph * 1.60934; - } -} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/McLaren.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/McLaren.java new file mode 100644 index 0000000000..c807df67db --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/McLaren.java @@ -0,0 +1,8 @@ +package com.baeldung.designpatterns.adapter; + +public class McLaren implements Movable { + @Override + public double getSpeed() { + return 241; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/Movable.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/Movable.java new file mode 100644 index 0000000000..ec94e90af0 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/Movable.java @@ -0,0 +1,6 @@ +package com.baeldung.designpatterns.adapter; + +public interface Movable { + // returns speed in MPH + double getSpeed(); +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/MovableAdapter.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/MovableAdapter.java new file mode 100644 index 0000000000..b9c7484446 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/MovableAdapter.java @@ -0,0 +1,6 @@ +package com.baeldung.designpatterns.adapter; + +public interface MovableAdapter { + // returns speed in KMPH + double getSpeed(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/MovableAdapterImpl.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/MovableAdapterImpl.java new file mode 100644 index 0000000000..eb74641389 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/MovableAdapterImpl.java @@ -0,0 +1,19 @@ +package com.baeldung.designpatterns.adapter; + +public class MovableAdapterImpl implements MovableAdapter { + private Movable luxuryCars; + + public MovableAdapterImpl(Movable luxuryCars) { + this.luxuryCars = luxuryCars; + } + + @Override + public double getSpeed() { + double mph = luxuryCars.getSpeed(); + return convertMPHtoKMPH(mph); + } + + private double convertMPHtoKMPH(double mph) { + return mph * 1.60934; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java index ed3f75b4a1..da5d29617f 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java @@ -1,12 +1,8 @@ package com.baeldung.designpatterns.bridge; -import static com.baeldung.designpatterns.util.LogerUtil.LOG; - public class Blue implements Color { - @Override - public void fillColor() { - LOG.info("Color : Blue"); + public String fill() { + return "Color is Blue"; } - } diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/BridgePatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/BridgePatternDriver.java index 921deadcac..e6a7fb41c1 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/bridge/BridgePatternDriver.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/BridgePatternDriver.java @@ -5,10 +5,10 @@ public class BridgePatternDriver { public static void main(String[] args) { //a square with red color Shape square = new Square(new Red()); - square.drawShape(); + System.out.println(square.draw()); //a triangle with blue color Shape triangle = new Triangle(new Blue()); - triangle.drawShape(); + System.out.println(triangle.draw()); } } diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Color.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Color.java index 91d2b01609..05618e6d6e 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Color.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Color.java @@ -1,5 +1,5 @@ package com.baeldung.designpatterns.bridge; public interface Color { - public void fillColor(); + String fill(); } diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Red.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Red.java index 8c22a94f00..bc83199591 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Red.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Red.java @@ -1,12 +1,10 @@ package com.baeldung.designpatterns.bridge; -import static com.baeldung.designpatterns.util.LogerUtil.LOG; - public class Red implements Color { @Override - public void fillColor() { - LOG.info("Color : Red"); + public String fill() { + return "Color is Red"; } } diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Shape.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Shape.java index c4daf7a821..75cd43dbc8 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Shape.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Shape.java @@ -7,5 +7,5 @@ public abstract class Shape { this.color = color; } - abstract public void drawShape(); + abstract public String draw(); } diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Square.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Square.java index 6b377197eb..7397f4bd47 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Square.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Square.java @@ -1,7 +1,5 @@ package com.baeldung.designpatterns.bridge; -import static com.baeldung.designpatterns.util.LogerUtil.LOG; - public class Square extends Shape { public Square(Color color) { @@ -9,8 +7,7 @@ public class Square extends Shape { } @Override - public void drawShape() { - LOG.info("Square drawn. "); - color.fillColor(); + public String draw() { + return "Square drawn. " + color.fill(); } } diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Triangle.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Triangle.java index 900e78cf2b..46db66ee42 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Triangle.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Triangle.java @@ -1,7 +1,5 @@ package com.baeldung.designpatterns.bridge; -import static com.baeldung.designpatterns.util.LogerUtil.LOG; - public class Triangle extends Shape { public Triangle(Color color) { @@ -9,8 +7,7 @@ public class Triangle extends Shape { } @Override - public void drawShape() { - LOG.info("Triangle drawn. "); - color.fillColor(); + public String draw() { + return "Triangle drawn. "+ color.fill(); } } diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTree.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTree.java index 80a0865567..e5dca41dd8 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTree.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTree.java @@ -1,5 +1,5 @@ package com.baeldung.designpatterns.decorator; public interface ChristmasTree { - public String decorate(); -} + String decorate(); +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObject.java b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObject.java index 96a6bfb878..256b31bc84 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObject.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObject.java @@ -1,5 +1,5 @@ package com.baeldung.designpatterns.proxy; public interface ExpensiveObject { - public void process(); + void process(); } diff --git a/core-java/src/main/java/com/baeldung/numberofdigits/Benchmarking.java b/core-java/src/main/java/com/baeldung/numberofdigits/Benchmarking.java old mode 100644 new mode 100755 index fbd9af2c30..737654ccf5 --- a/core-java/src/main/java/com/baeldung/numberofdigits/Benchmarking.java +++ b/core-java/src/main/java/com/baeldung/numberofdigits/Benchmarking.java @@ -1,131 +1,67 @@ package com.baeldung.numberofdigits; -import static com.baeldung.designpatterns.util.LogerUtil.LOG;; +import java.io.IOException; +import java.util.concurrent.TimeUnit; -public class Benchmarking {; - - private static final int LOWER_BOUND = 1; - private static final int UPPER_BOUND = 999999999; - - - public static void main(String[] args) { - LOG.info("Testing all methods..."); - - long length = test_stringBasedSolution(); - LOG.info("String Based Solution : " + length); - - length = test_logarithmicApproach(); - LOG.info("Logarithmic Approach : " + length); - - length = test_repeatedMultiplication(); - LOG.info("Repeated Multiplication : " + length); - - length = test_shiftOperators(); - LOG.info("Shift Operators : " + length); - - length = test_dividingWithPowersOf2(); - LOG.info("Dividing with Powers of 2 : " + length); - - length = test_divideAndConquer(); - LOG.info("Divide And Conquer : " + length); +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.runner.RunnerException; +public class Benchmarking { + public static void main(String[] args) throws RunnerException, IOException { + org.openjdk.jmh.Main.main(args); } - private static long test_stringBasedSolution() { - - long startTime, stopTime, elapsedTime; - startTime = System.currentTimeMillis(); - - int total = 0; - for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) { - total += NumberOfDigits.stringBasedSolution(i); - } - - stopTime = System.currentTimeMillis(); - elapsedTime = stopTime - startTime; - - return elapsedTime; - } - - private static long test_logarithmicApproach() { - - long startTime, stopTime, elapsedTime; - startTime = System.currentTimeMillis(); - - int total = 0; - for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) { - total += NumberOfDigits.logarithmicApproach(i); - } - - stopTime = System.currentTimeMillis(); - elapsedTime = stopTime - startTime; - - return elapsedTime; - } - - private static long test_repeatedMultiplication() { - - long startTime, stopTime, elapsedTime; - startTime = System.currentTimeMillis(); - - int total = 0; - for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) { - total += NumberOfDigits.repeatedMultiplication(i); - } - - stopTime = System.currentTimeMillis(); - elapsedTime = stopTime - startTime; - - return elapsedTime; - } - - private static long test_shiftOperators() { - - long startTime, stopTime, elapsedTime; - startTime = System.currentTimeMillis(); - - int total = 0; - for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) { - total += NumberOfDigits.shiftOperators(i); - } - - stopTime = System.currentTimeMillis(); - elapsedTime = stopTime - startTime; - - return elapsedTime; - } - - private static long test_dividingWithPowersOf2() { - - long startTime, stopTime, elapsedTime; - startTime = System.currentTimeMillis(); - - int total = 0; - for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) { - total += NumberOfDigits.dividingWithPowersOf2(i); - } - - stopTime = System.currentTimeMillis(); - elapsedTime = stopTime - startTime; - - return elapsedTime; - } - - private static long test_divideAndConquer() { - - long startTime, stopTime, elapsedTime; - startTime = System.currentTimeMillis(); - - int total = 0; - for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) { - total += NumberOfDigits.divideAndConquer(i); - } - - stopTime = System.currentTimeMillis(); - elapsedTime = stopTime - startTime; - - return elapsedTime; + @State(Scope.Thread) + public static class ExecutionPlan { + public int number = Integer.MAX_VALUE; + public int length = 0; + public NumberOfDigits numberOfDigits= new NumberOfDigits(); } + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.NANOSECONDS) + public void stringBasedSolution(ExecutionPlan plan) { + plan.length = plan.numberOfDigits.stringBasedSolution(plan.number); + } + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.NANOSECONDS) + public void logarithmicApproach(ExecutionPlan plan) { + plan.length = plan.numberOfDigits.logarithmicApproach(plan.number); + } + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.NANOSECONDS) + public void repeatedMultiplication(ExecutionPlan plan) { + plan.length = plan.numberOfDigits.repeatedMultiplication(plan.number); + } + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.NANOSECONDS) + public void shiftOperators(ExecutionPlan plan) { + plan.length = plan.numberOfDigits.shiftOperators(plan.number); + } + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.NANOSECONDS) + public void dividingWithPowersOf2(ExecutionPlan plan) { + plan.length = plan.numberOfDigits.dividingWithPowersOf2(plan.number); + } + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.NANOSECONDS) + public void divideAndConquer(ExecutionPlan plan) { + plan.length = plan.numberOfDigits.divideAndConquer(plan.number); + } } diff --git a/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigits.java b/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigits.java old mode 100644 new mode 100755 index f455430750..1abf74d405 --- a/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigits.java +++ b/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigits.java @@ -1,17 +1,17 @@ package com.baeldung.numberofdigits; public class NumberOfDigits { - public static int stringBasedSolution(int number) { + public int stringBasedSolution(int number) { int length = String.valueOf(number).length(); return length; } - public static int logarithmicApproach(int number) { + public int logarithmicApproach(int number) { int length = (int) Math.log10(number) + 1; return length; } - public static int repeatedMultiplication(int number) { + public int repeatedMultiplication(int number) { int length = 0; long temp = 1; while(temp <= number) { @@ -21,7 +21,7 @@ public class NumberOfDigits { return length; } - public static int shiftOperators(int number) { + public int shiftOperators(int number) { int length = 0; long temp = 1; while(temp <= number) { @@ -31,7 +31,7 @@ public class NumberOfDigits { return length; } - public static int dividingWithPowersOf2(int number) { + public int dividingWithPowersOf2(int number) { int length = 1; if (number >= 100000000) { length += 8; @@ -51,7 +51,7 @@ public class NumberOfDigits { return length; } - public static int divideAndConquer(int number) { + public int divideAndConquer(int number) { if (number < 100000){ // 5 digits or less if (number < 100){ diff --git a/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigitsDriver.java b/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigitsDriver.java old mode 100644 new mode 100755 index 4d76a5d677..32d3051327 --- a/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigitsDriver.java +++ b/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigitsDriver.java @@ -1,27 +1,33 @@ -package com.baeldung.numberofdigits; - -import static com.baeldung.designpatterns.util.LogerUtil.LOG; - -public class NumberOfDigitsDriver { - public static void main(String[] args) { - LOG.info("Testing all methods..."); - - long length = NumberOfDigits.stringBasedSolution(602); - LOG.info("String Based Solution : " + length); - - length = NumberOfDigits.logarithmicApproach(602); - LOG.info("Logarithmic Approach : " + length); - - length = NumberOfDigits.repeatedMultiplication(602); - LOG.info("Repeated Multiplication : " + length); - - length = NumberOfDigits.shiftOperators(602); - LOG.info("Shift Operators : " + length); - - length = NumberOfDigits.dividingWithPowersOf2(602); - LOG.info("Dividing with Powers of 2 : " + length); - - length = NumberOfDigits.divideAndConquer(602); - LOG.info("Divide And Conquer : " + length); - } -} +package com.baeldung.numberofdigits; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class NumberOfDigitsDriver { + private static NumberOfDigits numberOfDigits; + + static { + numberOfDigits = new NumberOfDigits(); + } + + public static void main(String[] args) { + LOG.info("Testing all methods..."); + + long length = numberOfDigits.stringBasedSolution(602); + LOG.info("String Based Solution : " + length); + + length = numberOfDigits.logarithmicApproach(602); + LOG.info("Logarithmic Approach : " + length); + + length = numberOfDigits.repeatedMultiplication(602); + LOG.info("Repeated Multiplication : " + length); + + length = numberOfDigits.shiftOperators(602); + LOG.info("Shift Operators : " + length); + + length = numberOfDigits.dividingWithPowersOf2(602); + LOG.info("Dividing with Powers of 2 : " + length); + + length = numberOfDigits.divideAndConquer(602); + LOG.info("Divide And Conquer : " + length); + } +} diff --git a/core-java/src/main/java/com/baeldung/sneakythrows/SneakyRunnable.java b/core-java/src/main/java/com/baeldung/sneakythrows/SneakyRunnable.java new file mode 100644 index 0000000000..88a8696053 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/sneakythrows/SneakyRunnable.java @@ -0,0 +1,23 @@ +package com.baeldung.sneakythrows; + +import lombok.SneakyThrows; + +public class SneakyRunnable implements Runnable { + + @SneakyThrows + public void run() { + try { + throw new InterruptedException(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + public static void main(String[] args) { + try { + new SneakyRunnable().run(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/sneakythrows/SneakyThrows.java b/core-java/src/main/java/com/baeldung/sneakythrows/SneakyThrows.java new file mode 100644 index 0000000000..847aaa7249 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/sneakythrows/SneakyThrows.java @@ -0,0 +1,25 @@ +package com.baeldung.sneakythrows; + +import java.io.IOException; + +public class SneakyThrows { + + + public static void sneakyThrow(Throwable e) throws E { + throw (E) e; + } + + public static void throwsSneakyIOException() { + sneakyThrow(new IOException("sneaky")); + } + + + public static void main(String[] args) { + try { + throwsSneakyIOException(); + } catch (Exception ex) { + ex.printStackTrace(); + } + + } +} diff --git a/core-java/src/main/java/com/baeldung/stream/StreamIndices.java b/core-java/src/main/java/com/baeldung/stream/StreamIndices.java new file mode 100644 index 0000000000..34768a725a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/stream/StreamIndices.java @@ -0,0 +1,62 @@ +package com.baeldung.stream; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import com.codepoetics.protonpack.Indexed; +import com.codepoetics.protonpack.StreamUtils; + +import io.vavr.collection.Stream; +import one.util.streamex.EntryStream; + +public class StreamIndices { + + public static List getEvenIndexedStrings(String[] names) { + List evenIndexedNames = IntStream.range(0, names.length) + .filter(i -> i % 2 == 0) + .mapToObj(i -> names[i]) + .collect(Collectors.toList()); + return evenIndexedNames; + } + + public List getEvenIndexedStringsVersionTwo(List names) { + List evenIndexedNames = EntryStream.of(names) + .filterKeyValue((index, name) -> index % 2 == 0) + .values() + .toList(); + return evenIndexedNames; + } + + public static List> getEvenIndexedStrings(List names) { + List> list = StreamUtils.zipWithIndex(names.stream()) + .filter(i -> i.getIndex() % 2 == 0) + .collect(Collectors.toList()); + return list; + } + + public static List> getOddIndexedStrings(List names) { + List> list = StreamUtils.zipWithIndex(names.stream()) + .filter(i -> i.getIndex() % 2 == 1) + .collect(Collectors.toList()); + return list; + } + + public static List getOddIndexedStrings(String[] names) { + List oddIndexedNames = IntStream.range(0, names.length) + .filter(i -> i % 2 == 1) + .mapToObj(i -> names[i]) + .collect(Collectors.toList()); + return oddIndexedNames; + } + + public static List getOddIndexedStringsVersionTwo(String[] names) { + List oddIndexedNames = Stream.of(names) + .zipWithIndex() + .filter(tuple -> tuple._2 % 2 == 1) + .map(tuple -> tuple._1) + .toJavaList(); + return oddIndexedNames; + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/string/StringBufferStringBuilder.java b/core-java/src/main/java/com/baeldung/string/StringBufferStringBuilder.java new file mode 100644 index 0000000000..74f489d57f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/string/StringBufferStringBuilder.java @@ -0,0 +1,46 @@ +package com.baeldung.string; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.RunnerException; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +public class StringBufferStringBuilder { + + public static void main(String[] args) throws RunnerException { + + Options opt = new OptionsBuilder() + .include(StringBufferStringBuilder.class.getSimpleName()) + .build(); + + new Runner(opt).run(); + } + + @State(Scope.Benchmark) + public static class MyState { + int iterations = 1000; + String initial = "abc"; + String suffix = "def"; + } + + @Benchmark + public StringBuffer benchmarkStringBuffer(MyState state) { + StringBuffer stringBuffer = new StringBuffer(state.initial); + for (int i = 0; i < state.iterations; i++) { + stringBuffer.append(state.suffix); + } + return stringBuffer; + } + + @Benchmark + public StringBuilder benchmarkStringBuilder(MyState state) { + StringBuilder stringBuilder = new StringBuilder(state.initial); + for (int i = 0; i < state.iterations; i++) { + stringBuilder.append(state.suffix); + } + return stringBuilder; + } +} \ No newline at end of file diff --git a/couchbase-sdk/src/main/resources/application.properties b/core-java/src/main/resources/META-INF/BenchmarkList old mode 100644 new mode 100755 similarity index 100% rename from couchbase-sdk/src/main/resources/application.properties rename to core-java/src/main/resources/META-INF/BenchmarkList diff --git a/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java index fb483a8a68..8cad1290d9 100644 --- a/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java @@ -1,20 +1,30 @@ package com.baeldung.designpatterns; - -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; -import com.baeldung.designpatterns.adapter.LuxuryCarsSpeedAdapter; -import com.baeldung.designpatterns.adapter.LuxuryCarsSpeedAdapterImpl; +import com.baeldung.designpatterns.adapter.AstonMartin; +import com.baeldung.designpatterns.adapter.BugattiVeyron; +import com.baeldung.designpatterns.adapter.McLaren; +import com.baeldung.designpatterns.adapter.Movable; +import com.baeldung.designpatterns.adapter.MovableAdapter; +import com.baeldung.designpatterns.adapter.MovableAdapterImpl; public class AdapterPatternIntegrationTest { @Test - public void givenLuxuryCarsAdapter_WhenConvertingMPHToKMPH_thenSuccessfullyConverted() { - LuxuryCarsSpeedAdapter luxuryCars = new LuxuryCarsSpeedAdapterImpl(); - assertEquals(luxuryCars.bugattiVeyronInKMPH(), 431.30312, 0.00001); - assertEquals(luxuryCars.mcLarenInKMPH(), 387.85094, 0.00001); - assertEquals(luxuryCars.astonMartinInKMPH(), 354.0548, 0.00001); + public void givenMovableAdapter_WhenConvertingMPHToKMPH_thenSuccessfullyConverted() { + Movable bugattiVeyron = new BugattiVeyron(); + MovableAdapter bugattiVeyronAdapter = new MovableAdapterImpl(bugattiVeyron); + assertEquals(bugattiVeyronAdapter.getSpeed(), 431.30312, 0.00001); + + Movable mcLaren = new McLaren(); + MovableAdapter mcLarenAdapter = new MovableAdapterImpl(mcLaren); + assertEquals(mcLarenAdapter.getSpeed(), 387.85094, 0.00001); + + Movable astonMartin = new AstonMartin(); + MovableAdapter astonMartinAdapter = new MovableAdapterImpl(astonMartin); + assertEquals(astonMartinAdapter.getSpeed(), 354.0548, 0.00001); } } diff --git a/core-java/src/test/java/com/baeldung/designpatterns/BridgePatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/BridgePatternIntegrationTest.java index 56a7a704f2..ed7eb0c453 100644 --- a/core-java/src/test/java/com/baeldung/designpatterns/BridgePatternIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/designpatterns/BridgePatternIntegrationTest.java @@ -1,14 +1,7 @@ package com.baeldung.designpatterns; -import static com.baeldung.designpatterns.util.LogerUtil.LOG; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.junit.Assert.*; -import java.util.List; - -import org.apache.log4j.spi.LoggingEvent; -import org.junit.After; -import org.junit.Before; import org.junit.Test; import com.baeldung.designpatterns.bridge.Blue; @@ -18,35 +11,16 @@ import com.baeldung.designpatterns.bridge.Square; import com.baeldung.designpatterns.bridge.Triangle; public class BridgePatternIntegrationTest { - public static TestAppenderDP appender; - - @Before - public void setUp() { - appender = new TestAppenderDP(); - LOG.addAppender(appender); - } - + @Test public void whenBridgePatternInvoked_thenConfigSuccess() { //a square with red color Shape square = new Square(new Red()); - square.drawShape(); + assertEquals(square.draw(), "Square drawn. Color is Red"); //a triangle with blue color Shape triangle = new Triangle(new Blue()); - triangle.drawShape(); - - final List log = appender.getLog(); - - assertThat((String) log.get(0).getMessage(), is("Square drawn. ")); - assertThat((String) log.get(1).getMessage(), is("Color : Red")); - assertThat((String) log.get(2).getMessage(), is("Triangle drawn. ")); - assertThat((String) log.get(3).getMessage(), is("Color : Blue")); - } - - @After - public void tearDown() { - LOG.removeAppender(appender); + assertEquals(triangle.draw(), "Triangle drawn. Color is Blue"); } } diff --git a/core-java/src/test/java/com/baeldung/designpatterns/DecoratorPatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/DecoratorPatternIntegrationTest.java index b3b3f988f1..de0ca8a135 100644 --- a/core-java/src/test/java/com/baeldung/designpatterns/DecoratorPatternIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/designpatterns/DecoratorPatternIntegrationTest.java @@ -10,19 +10,16 @@ import com.baeldung.designpatterns.decorator.ChristmasTreeImpl; import com.baeldung.designpatterns.decorator.Garland; public class DecoratorPatternIntegrationTest { - private ChristmasTree tree; - @Test public void givenDecoratorPattern_WhenDecoratorsInjectedAtRuntime_thenConfigSuccess() { - //christmas tree with just one Garland - tree = new Garland(new ChristmasTreeImpl()); - assertEquals(tree.decorate(), "Christmas tree with Garland"); - - //christmas tree with two Garlands and one Bubble lights - tree = new BubbleLights(new Garland( - new Garland(new ChristmasTreeImpl())) - ); - assertEquals(tree.decorate(), "Christmas tree with Garland with Garland with Bubble Lights"); + ChristmasTree tree1 = new Garland(new ChristmasTreeImpl()); + assertEquals(tree1.decorate(), + "Christmas tree with Garland"); + + ChristmasTree tree2 = new BubbleLights( + new Garland(new Garland(new ChristmasTreeImpl()))); + assertEquals(tree2.decorate(), + "Christmas tree with Garland with Garland with Bubble Lights"); } } diff --git a/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java b/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java index da615eef6f..c27af983d3 100644 --- a/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java +++ b/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java @@ -1,20 +1,23 @@ package com.baeldung.encoderdecoder; +import static java.util.stream.Collectors.joining; +import static org.hamcrest.CoreMatchers.is; + +import java.io.UnsupportedEncodingException; +import java.net.URL; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - -import java.io.UnsupportedEncodingException; -import java.net.*; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import static java.util.stream.Collectors.joining; -import static org.hamcrest.CoreMatchers.*; +import org.springframework.web.util.UriUtils; public class EncoderDecoderUnitTest { @@ -76,19 +79,20 @@ public class EncoderDecoderUnitTest { private String encodePath(String path) { try { - path = new URI(null, null, path, null).getPath(); - } catch (URISyntaxException e) { + path = UriUtils.encodePath(path, "UTF-8"); + } catch (UnsupportedEncodingException e) { LOGGER.error("Error encoding parameter {}", e.getMessage(), e); } return path; } @Test - public void givenPath_thenEncodeDecodePath() throws URISyntaxException { - URI uri = new URI(null, null, "/Path 1/Path+2", null); - - Assert.assertEquals("/Path 1/Path+2", uri.getPath()); - Assert.assertEquals("/Path%201/Path+2", uri.getRawPath()); + public void givenPathSegment_thenEncodeDecode() throws UnsupportedEncodingException { + String pathSegment = "/Path 1/Path+2"; + String encodedPathSegment = encodePath(pathSegment); + String decodedPathSegment = UriUtils.decode(encodedPathSegment, "UTF-8"); + Assert.assertEquals("/Path%201/Path+2", encodedPathSegment); + Assert.assertEquals("/Path 1/Path+2", decodedPathSegment); } @Test diff --git a/core-java/src/test/java/com/baeldung/java/nio/selector/NioEchoIntegrationTest.java b/core-java/src/test/java/com/baeldung/java/nio/selector/NioEchoLiveTest.java similarity index 89% rename from core-java/src/test/java/com/baeldung/java/nio/selector/NioEchoIntegrationTest.java rename to core-java/src/test/java/com/baeldung/java/nio/selector/NioEchoLiveTest.java index fc64799578..0e1afa87a5 100644 --- a/core-java/src/test/java/com/baeldung/java/nio/selector/NioEchoIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/java/nio/selector/NioEchoLiveTest.java @@ -8,10 +8,10 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -public class NioEchoIntegrationTest { +public class NioEchoLiveTest { - Process server; - EchoClient client; + private Process server; + private EchoClient client; @Before public void setup() throws IOException, InterruptedException { diff --git a/core-java/src/test/java/com/baeldung/jdbc/JdbcIntegrationTest.java b/core-java/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/jdbc/JdbcIntegrationTest.java rename to core-java/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java index 926fdb3833..da0c6bffe5 100644 --- a/core-java/src/test/java/com/baeldung/jdbc/JdbcIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java @@ -21,9 +21,9 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -public class JdbcIntegrationTest { +public class JdbcLiveTest { - private static final Logger LOG = Logger.getLogger(JdbcIntegrationTest.class); + private static final Logger LOG = Logger.getLogger(JdbcLiveTest.class); private Connection con; diff --git a/core-java/src/test/java/com/baeldung/maths/RoundTest.java b/core-java/src/test/java/com/baeldung/maths/RoundTest.java index 9e3c049c96..5ce9523e21 100644 --- a/core-java/src/test/java/com/baeldung/maths/RoundTest.java +++ b/core-java/src/test/java/com/baeldung/maths/RoundTest.java @@ -15,56 +15,56 @@ public class RoundTest { private double expected = 2.03d; @Test - public void givenDecimalNumber_whenRoundToNDecimalPlaces_thenGetExpectedResult() { + public void givenDecimalNumber_whenRoundToNDecimalPlaces_thenGetExpectedResult() { Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta); Assert.assertEquals(expected, Round.roundAvoid(value, places), delta); Assert.assertEquals(expected, Precision.round(value, places), delta); Assert.assertEquals(expected, DoubleRounder.round(value, places), delta); - + places = 3; expected = 2.035d; - + Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta); Assert.assertEquals(expected, Round.roundAvoid(value, places), delta); Assert.assertEquals(expected, Precision.round(value, places), delta); Assert.assertEquals(expected, DoubleRounder.round(value, places), delta); - + value = 1000.0d; places = 17; expected = 1000.0d; - + Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta); Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 92.23372036854776 ! Assert.assertEquals(expected, Precision.round(value, places), delta); Assert.assertEquals(expected, DoubleRounder.round(value, places), delta); - + value = 256.025d; places = 2; expected = 256.03d; - + Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 256.02 ! Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 256.02 ! Assert.assertEquals(expected, Precision.round(value, places), delta); Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 256.02 ! - - value = 260.775d; + + value = 260.775d; places = 2; expected = 260.78d; - + Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 260.77 ! Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 260.77 ! Assert.assertEquals(expected, Precision.round(value, places), delta); Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 260.77 ! - + value = 90080070060.1d; places = 9; expected = 90080070060.1d; - + Assert.assertEquals(expected, Round.round(value, places), delta); Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta); Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 9.223372036854776E9 ! diff --git a/core-java/src/test/java/com/baeldung/networking/udp/UDPIntegrationTest.java b/core-java/src/test/java/com/baeldung/networking/udp/UDPLiveTest.java similarity index 96% rename from core-java/src/test/java/com/baeldung/networking/udp/UDPIntegrationTest.java rename to core-java/src/test/java/com/baeldung/networking/udp/UDPLiveTest.java index 968c01d24e..7337be6e3d 100644 --- a/core-java/src/test/java/com/baeldung/networking/udp/UDPIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/networking/udp/UDPLiveTest.java @@ -9,7 +9,7 @@ import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -public class UDPIntegrationTest { +public class UDPLiveTest { private EchoClient client; @Before diff --git a/core-java/src/test/java/com/baeldung/networking/udp/broadcast/BroadcastIntegrationTest.java b/core-java/src/test/java/com/baeldung/networking/udp/broadcast/BroadcastLiveTest.java similarity index 96% rename from core-java/src/test/java/com/baeldung/networking/udp/broadcast/BroadcastIntegrationTest.java rename to core-java/src/test/java/com/baeldung/networking/udp/broadcast/BroadcastLiveTest.java index c4f1e1f42c..51e5bfc669 100644 --- a/core-java/src/test/java/com/baeldung/networking/udp/broadcast/BroadcastIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/networking/udp/broadcast/BroadcastLiveTest.java @@ -7,7 +7,7 @@ import java.io.IOException; import static org.junit.Assert.assertEquals; -public class BroadcastIntegrationTest { +public class BroadcastLiveTest { private BroadcastingClient client; @Test diff --git a/core-java/src/test/java/com/baeldung/networking/udp/multicast/MulticastIntegrationTest.java b/core-java/src/test/java/com/baeldung/networking/udp/multicast/MulticastLiveTest.java similarity index 96% rename from core-java/src/test/java/com/baeldung/networking/udp/multicast/MulticastIntegrationTest.java rename to core-java/src/test/java/com/baeldung/networking/udp/multicast/MulticastLiveTest.java index 404f6c4e85..83d0482f44 100644 --- a/core-java/src/test/java/com/baeldung/networking/udp/multicast/MulticastIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/networking/udp/multicast/MulticastLiveTest.java @@ -7,7 +7,7 @@ import java.io.IOException; import static org.junit.Assert.assertEquals; -public class MulticastIntegrationTest { +public class MulticastLiveTest { private MulticastingClient client; @Test diff --git a/core-java/src/test/java/com/baeldung/numberofdigits/NumberOfDigitsIntegrationTest.java b/core-java/src/test/java/com/baeldung/numberofdigits/NumberOfDigitsIntegrationTest.java index 01b874622e..b348fe01ef 100644 --- a/core-java/src/test/java/com/baeldung/numberofdigits/NumberOfDigitsIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/numberofdigits/NumberOfDigitsIntegrationTest.java @@ -9,7 +9,13 @@ import org.junit.runner.RunWith; @RunWith(Theories.class) public class NumberOfDigitsIntegrationTest { - + + private static NumberOfDigits numberOfDigits; + + static { + numberOfDigits = new NumberOfDigits(); + } + @DataPoints public static int[][] lowestIntegers() { @@ -64,37 +70,37 @@ public class NumberOfDigitsIntegrationTest { @Theory public void givenDataPoints_whenStringBasedSolutionInvoked_thenAllPointsMatch(final int[] entry) { Assume.assumeTrue(entry[0] > 0 && entry[1] > 0); - Assert.assertEquals(entry[0], NumberOfDigits.stringBasedSolution(entry[1])); + Assert.assertEquals(entry[0], numberOfDigits.stringBasedSolution(entry[1])); } @Theory public void givenDataPoints_whenLogarithmicApproachInvoked_thenAllPointsMatch(final int[] entry) { Assume.assumeTrue(entry[0] > 0 && entry[1] > 0); - Assert.assertEquals(entry[0], NumberOfDigits.logarithmicApproach(entry[1])); + Assert.assertEquals(entry[0], numberOfDigits.logarithmicApproach(entry[1])); } @Theory public void givenDataPoints_whenRepeatedMultiplicationInvoked_thenAllPointsMatch(final int[] entry) { Assume.assumeTrue(entry[0] > 0 && entry[1] > 0); - Assert.assertEquals(entry[0], NumberOfDigits.repeatedMultiplication(entry[1])); + Assert.assertEquals(entry[0], numberOfDigits.repeatedMultiplication(entry[1])); } @Theory public void givenDataPoints_whenShiftOperatorsInvoked_thenAllPointsMatch(final int[] entry) { Assume.assumeTrue(entry[0] > 0 && entry[1] > 0); - Assert.assertEquals(entry[0], NumberOfDigits.shiftOperators(entry[1])); + Assert.assertEquals(entry[0], numberOfDigits.shiftOperators(entry[1])); } @Theory public void givenDataPoints_whenDividingWithPowersOf2Invoked_thenAllPointsMatch(final int[] entry) { Assume.assumeTrue(entry[0] > 0 && entry[1] > 0); - Assert.assertEquals(entry[0], NumberOfDigits.dividingWithPowersOf2(entry[1])); + Assert.assertEquals(entry[0], numberOfDigits.dividingWithPowersOf2(entry[1])); } @Theory public void givenDataPoints_whenDivideAndConquerInvoked_thenAllPointsMatch(final int[] entry) { Assume.assumeTrue(entry[0] > 0 && entry[1] > 0); - Assert.assertEquals(entry[0], NumberOfDigits.divideAndConquer(entry[1])); + Assert.assertEquals(entry[0], numberOfDigits.divideAndConquer(entry[1])); } } \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/printscreen/ScreenshotIntegrationTest.java b/core-java/src/test/java/com/baeldung/printscreen/ScreenshotLiveTest.java similarity index 92% rename from core-java/src/test/java/com/baeldung/printscreen/ScreenshotIntegrationTest.java rename to core-java/src/test/java/com/baeldung/printscreen/ScreenshotLiveTest.java index 13609b6977..672ba9668d 100644 --- a/core-java/src/test/java/com/baeldung/printscreen/ScreenshotIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/printscreen/ScreenshotLiveTest.java @@ -7,7 +7,7 @@ import java.io.File; import static org.junit.Assert.assertTrue; -public class ScreenshotIntegrationTest { +public class ScreenshotLiveTest { private Screenshot screenshot = new Screenshot("Screenshot.jpg"); private File file = new File("Screenshot.jpg"); diff --git a/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableTest.java b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableTest.java new file mode 100644 index 0000000000..cd31f545b9 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableTest.java @@ -0,0 +1,17 @@ +package com.baeldung.sneakythrows; + +import org.junit.Test; + +import static junit.framework.TestCase.assertEquals; + +public class SneakyRunnableTest { + + @Test + public void whenCallSneakyRunnableMethod_thenThrowException() { + try { + new SneakyRunnable().run(); + } catch (Exception e) { + assertEquals(InterruptedException.class, e.getStackTrace()); + } + } +} diff --git a/core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsTest.java b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsTest.java new file mode 100644 index 0000000000..e033ca062d --- /dev/null +++ b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsTest.java @@ -0,0 +1,18 @@ +package com.baeldung.sneakythrows; + +import org.junit.Test; + +import static junit.framework.TestCase.assertEquals; + +public class SneakyThrowsTest { + + @Test + public void whenCallSneakyMethod_thenThrowSneakyException() { + try { + SneakyThrows.throwsSneakyIOException(); + } catch (Exception ex) { + assertEquals("sneaky", ex.getMessage().toString()); + } + } + +} diff --git a/core-java/src/test/java/com/baeldung/stream/StreamIndicesTest.java b/core-java/src/test/java/com/baeldung/stream/StreamIndicesTest.java new file mode 100644 index 0000000000..a02ef4031e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stream/StreamIndicesTest.java @@ -0,0 +1,70 @@ +package com.baeldung.stream; + +import com.codepoetics.protonpack.Indexed; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class StreamIndicesTest { + + @Test + public void whenCalled_thenReturnListOfEvenIndexedStrings() { + String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"}; + List expectedResult = Arrays.asList("Afrim", "Besim", "Durim"); + List actualResult = StreamIndices.getEvenIndexedStrings(names); + + assertEquals(expectedResult, actualResult); + } + + @Test + public void whenCalled_thenReturnListOfEvenIndexedStringsVersionTwo() { + String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"}; + List expectedResult = Arrays.asList("Afrim", "Besim", "Durim"); + List actualResult = StreamIndices.getEvenIndexedStrings(names); + + assertEquals(expectedResult, actualResult); + } + + @Test + public void whenCalled_thenReturnListOfOddStrings() { + String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"}; + List expectedResult = Arrays.asList("Bashkim", "Lulzim", "Shpetim"); + List actualResult = StreamIndices.getOddIndexedStrings(names); + + assertEquals(expectedResult, actualResult); + } + + @Test + public void givenList_whenCalled_thenReturnListOfEvenIndexedStrings() { + List names = Arrays.asList("Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"); + List> expectedResult = Arrays + .asList(Indexed.index(0, "Afrim"), Indexed.index(2, "Besim"), Indexed + .index(4, "Durim")); + List> actualResult = StreamIndices.getEvenIndexedStrings(names); + + assertEquals(expectedResult, actualResult); + } + + @Test + public void givenList_whenCalled_thenReturnListOfOddIndexedStrings() { + List names = Arrays.asList("Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"); + List> expectedResult = Arrays + .asList(Indexed.index(1, "Bashkim"), Indexed.index(3, "Lulzim"), Indexed + .index(5, "Shpetim")); + List> actualResult = StreamIndices.getOddIndexedStrings(names); + + assertEquals(expectedResult, actualResult); + } + + @Test + public void whenCalled_thenReturnListOfOddStringsVersionTwo() { + String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"}; + List expectedResult = Arrays.asList("Bashkim", "Lulzim", "Shpetim"); + List actualResult = StreamIndices.getOddIndexedStringsVersionTwo(names); + + assertEquals(expectedResult, actualResult); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/org/baeldung/java/diamond/Car.java b/core-java/src/test/java/org/baeldung/java/diamond/Car.java new file mode 100644 index 0000000000..9f923e0f3b --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/diamond/Car.java @@ -0,0 +1,5 @@ +package org.baeldung.java.diamond; + +public class Car implements Vehicle { + +} diff --git a/core-java/src/test/java/org/baeldung/java/diamond/DiamondOperatorUnitTest.java b/core-java/src/test/java/org/baeldung/java/diamond/DiamondOperatorUnitTest.java new file mode 100644 index 0000000000..f6c7f7162f --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/diamond/DiamondOperatorUnitTest.java @@ -0,0 +1,13 @@ +package org.baeldung.java.diamond; + +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +public class DiamondOperatorUnitTest { + @Test + public void whenCreateCarUsingDiamondOperator_thenSuccess() { + Car myCar = new Car<>(); + assertNotNull(myCar); + } +} diff --git a/core-java/src/test/java/org/baeldung/java/diamond/Diesel.java b/core-java/src/test/java/org/baeldung/java/diamond/Diesel.java new file mode 100644 index 0000000000..dc4256cdae --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/diamond/Diesel.java @@ -0,0 +1,10 @@ +package org.baeldung.java.diamond; + +public class Diesel implements Engine { + + @Override + public void start() { + System.out.println("Started Diesel..."); + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/diamond/Engine.java b/core-java/src/test/java/org/baeldung/java/diamond/Engine.java new file mode 100644 index 0000000000..c18a8f64b5 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/diamond/Engine.java @@ -0,0 +1,6 @@ +package org.baeldung.java.diamond; + +public interface Engine { + + void start(); +} diff --git a/core-java/src/test/java/org/baeldung/java/diamond/Vehicle.java b/core-java/src/test/java/org/baeldung/java/diamond/Vehicle.java new file mode 100644 index 0000000000..f61cf59620 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/diamond/Vehicle.java @@ -0,0 +1,5 @@ +package org.baeldung.java.diamond; + +public interface Vehicle { + +} diff --git a/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesTest.java b/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesTest.java new file mode 100644 index 0000000000..2b36786abf --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesTest.java @@ -0,0 +1,17 @@ +package org.baeldung.java.rawtypes; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +public class RawTypesTest { + @Test + public void shouldCreateListUsingRawTypes() { + @SuppressWarnings("rawtypes") + List myList = new ArrayList(); + myList.add(new Object()); + myList.add("2"); + myList.add(new Integer(1)); + } +} diff --git a/couchbase/.gitignore b/couchbase/.gitignore new file mode 100644 index 0000000000..f6867e01bd --- /dev/null +++ b/couchbase/.gitignore @@ -0,0 +1,6 @@ +# Created by .ignore support plugin (hsz.mobi) + +# IntelliJ project files +.idea +*.iml +/target/ diff --git a/couchbase-sdk/README.md b/couchbase/README.md similarity index 100% rename from couchbase-sdk/README.md rename to couchbase/README.md diff --git a/couchbase-sdk/mvnw b/couchbase/mvnw old mode 100755 new mode 100644 similarity index 100% rename from couchbase-sdk/mvnw rename to couchbase/mvnw diff --git a/couchbase-sdk/mvnw.cmd b/couchbase/mvnw.cmd similarity index 100% rename from couchbase-sdk/mvnw.cmd rename to couchbase/mvnw.cmd diff --git a/couchbase-sdk/pom.xml b/couchbase/pom.xml similarity index 88% rename from couchbase-sdk/pom.xml rename to couchbase/pom.xml index fd9e1b08f6..c79ce853d0 100644 --- a/couchbase-sdk/pom.xml +++ b/couchbase/pom.xml @@ -6,7 +6,7 @@ couchbase-sdk 0.1-SNAPSHOT jar - couchbase-sdk + couchbase Couchbase SDK Tutorials @@ -23,6 +23,12 @@ ${couchbase.client.version} + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + org.springframework @@ -67,9 +73,10 @@ 1.8 UTF-8 - 2.4.0 + 2.5.0 4.3.5.RELEASE 3.5 + 2.9.1 diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java b/couchbase/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java rename to couchbase/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/Person.java b/couchbase/src/main/java/com/baeldung/couchbase/async/person/Person.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/Person.java rename to couchbase/src/main/java/com/baeldung/couchbase/async/person/Person.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java b/couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java rename to couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java b/couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java rename to couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java b/couchbase/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java rename to couchbase/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java rename to couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java rename to couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/BucketService.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/BucketService.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/BucketService.java rename to couchbase/src/main/java/com/baeldung/couchbase/async/service/BucketService.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java rename to couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java rename to couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/CrudService.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/CrudService.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/CrudService.java rename to couchbase/src/main/java/com/baeldung/couchbase/async/service/CrudService.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java rename to couchbase/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java rename to couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java b/couchbase/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java rename to couchbase/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/mapreduce/CouchbaseKeyGenerator.java b/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/CouchbaseKeyGenerator.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/mapreduce/CouchbaseKeyGenerator.java rename to couchbase/src/main/java/com/baeldung/couchbase/mapreduce/CouchbaseKeyGenerator.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/mapreduce/DuplicateKeyException.java b/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/DuplicateKeyException.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/mapreduce/DuplicateKeyException.java rename to couchbase/src/main/java/com/baeldung/couchbase/mapreduce/DuplicateKeyException.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/mapreduce/RandomUUIDGenerator.java b/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/RandomUUIDGenerator.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/mapreduce/RandomUUIDGenerator.java rename to couchbase/src/main/java/com/baeldung/couchbase/mapreduce/RandomUUIDGenerator.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/mapreduce/StudentGrade.java b/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGrade.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/mapreduce/StudentGrade.java rename to couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGrade.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeKeyGenerator.java b/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeKeyGenerator.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeKeyGenerator.java rename to couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeKeyGenerator.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeQueryBuilder.java b/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeQueryBuilder.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeQueryBuilder.java rename to couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeQueryBuilder.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeService.java b/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeService.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeService.java rename to couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/n1ql/BucketFactory.java b/couchbase/src/main/java/com/baeldung/couchbase/n1ql/BucketFactory.java new file mode 100644 index 0000000000..98fbe17e60 --- /dev/null +++ b/couchbase/src/main/java/com/baeldung/couchbase/n1ql/BucketFactory.java @@ -0,0 +1,26 @@ +package com.baeldung.couchbase.n1ql; + +import com.couchbase.client.java.Bucket; +import com.couchbase.client.java.Cluster; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class BucketFactory { + + @Autowired + private Cluster cluster; + + private Bucket travelSampleBucket; + private Bucket testBucket; + + public Bucket getTravelSampleBucket() { + return (travelSampleBucket != null) ? + travelSampleBucket : cluster.openBucket("travel-sample"); + } + + public Bucket getTestBucket() { + return (testBucket != null) ? + testBucket : cluster.openBucket("test"); + } +} diff --git a/couchbase/src/main/java/com/baeldung/couchbase/n1ql/CodeSnippets.java b/couchbase/src/main/java/com/baeldung/couchbase/n1ql/CodeSnippets.java new file mode 100644 index 0000000000..45067911cb --- /dev/null +++ b/couchbase/src/main/java/com/baeldung/couchbase/n1ql/CodeSnippets.java @@ -0,0 +1,34 @@ +package com.baeldung.couchbase.n1ql; + +import com.couchbase.client.java.query.N1qlQueryResult; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; +import java.util.List; +import java.util.Objects; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.stream.Collectors; + +public class CodeSnippets { + + private static ObjectMapper objectMapper = new ObjectMapper(); + + private static final Logger logger = Logger.getLogger(CodeSnippets.class.getName()); + + public static List extractJsonResult(N1qlQueryResult result) { + return result.allRows().stream() + .map(row -> { + try { + return objectMapper.readTree(row.value().toString()); + }catch (IOException e) { + logger.log(Level.WARNING, e.getLocalizedMessage()); + return null; + } + }) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + +} diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/Person.java b/couchbase/src/main/java/com/baeldung/couchbase/spring/person/Person.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/Person.java rename to couchbase/src/main/java/com/baeldung/couchbase/spring/person/Person.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java b/couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java rename to couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java b/couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java rename to couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java b/couchbase/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java rename to couchbase/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java b/couchbase/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java rename to couchbase/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java b/couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java rename to couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java b/couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java rename to couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java b/couchbase/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java rename to couchbase/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java b/couchbase/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java rename to couchbase/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java b/couchbase/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java similarity index 100% rename from couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java rename to couchbase/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java diff --git a/couchbase/src/main/resources/application.properties b/couchbase/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/couchbase-sdk/src/main/resources/logback.xml b/couchbase/src/main/resources/logback.xml similarity index 100% rename from couchbase-sdk/src/main/resources/logback.xml rename to couchbase/src/main/resources/logback.xml diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java similarity index 100% rename from couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java b/couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java similarity index 100% rename from couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java rename to couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java similarity index 100% rename from couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java similarity index 100% rename from couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java similarity index 100% rename from couchbase-sdk/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/n1ql/IntegrationTestConfig.java b/couchbase/src/test/java/com/baeldung/couchbase/n1ql/IntegrationTestConfig.java new file mode 100644 index 0000000000..ef7e31b224 --- /dev/null +++ b/couchbase/src/test/java/com/baeldung/couchbase/n1ql/IntegrationTestConfig.java @@ -0,0 +1,26 @@ +package com.baeldung.couchbase.n1ql; + +import com.couchbase.client.java.Cluster; +import com.couchbase.client.java.CouchbaseCluster; +import com.couchbase.client.java.env.CouchbaseEnvironment; +import com.couchbase.client.java.env.DefaultCouchbaseEnvironment; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +import java.util.concurrent.TimeUnit; + +@Configuration +@ComponentScan(basePackages = { "com.baeldung.couchbase.n1ql" }) +public class IntegrationTestConfig { + + @Bean + public Cluster cluster() { + CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder() + .connectTimeout(60000) + .build(); + return CouchbaseCluster.create(env, "127.0.0.1"); + } + + +} diff --git a/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java new file mode 100644 index 0000000000..8112d7d222 --- /dev/null +++ b/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java @@ -0,0 +1,248 @@ +package com.baeldung.couchbase.n1ql; + +import com.couchbase.client.java.Bucket; +import com.couchbase.client.java.Cluster; +import com.couchbase.client.java.document.JsonDocument; +import com.couchbase.client.java.document.json.JsonArray; +import com.couchbase.client.java.document.json.JsonObject; +import com.couchbase.client.java.query.N1qlQuery; +import com.couchbase.client.java.query.N1qlQueryResult; +import com.couchbase.client.java.query.N1qlQueryRow; +import com.couchbase.client.java.query.Statement; +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import rx.Observable; + +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import static com.baeldung.couchbase.n1ql.CodeSnippets.extractJsonResult; +import static com.couchbase.client.java.query.Select.select; +import static com.couchbase.client.java.query.dsl.Expression.*; +import static org.junit.Assert.assertNotNull; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { IntegrationTestConfig.class }) +public class N1QLIntegrationTest { + + + @Autowired + private Cluster cluster; + + @Autowired + private BucketFactory bucketFactory; + + @Test + public void givenAutowiredCluster_whenNotNull_thenNotNull() { + assertNotNull(cluster); + } + + @Test + public void givenBucketFactory_whenGetTestBucket_thenNotNull() { + assertNotNull(bucketFactory.getTestBucket()); + } + + @Test + public void givenBucketFactory_whenGetTravelSampleBucket_thenNotNull() { + assertNotNull(bucketFactory.getTravelSampleBucket()); + } + + @Test + public void givenDocument_whenInsert_thenResult() { + Bucket bucket = bucketFactory.getTestBucket(); + JsonObject personObj = JsonObject.create() + .put("name", "John") + .put("email", "john@doe.com") + .put("interests", JsonArray.from("Java", "Nigerian Jollof")); + + String id = UUID.randomUUID().toString(); + JsonDocument doc = JsonDocument.create(id, personObj); + bucket.insert(doc); + assertNotNull(bucket.get(id)); + } + + @Test + public void whenBasicSelectQuery_thenGetQueryResult() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + N1qlQueryResult result + = bucket.query(N1qlQuery.simple("SELECT * FROM test")); + + result.forEach(System.out::println); + + System.out.println("result count: " + result.info().resultCount()); + System.out.println("error count: " + result.info().errorCount()); + } + + @Test + public void givenSelectStatement_whenQuery_thenResult() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + String query = "SELECT name FROM `travel-sample` " + + "WHERE type = 'airport' LIMIT 100"; + N1qlQueryResult result1 = bucket.query(N1qlQuery.simple(query)); + + System.out.println("Result Count " + result1.info().resultCount()); + + N1qlQueryRow row = result1.allRows().get(0); + JsonObject rowJson = row.value(); + System.out.println("Name in First Row " + rowJson.get("name")); + + } + + @Test + public void givenSelectStatement2_whenQuery_thenResult() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + JsonObject pVal = JsonObject.create().put("type", "airport"); + String query = "SELECT * FROM `travel-sample` " + + "WHERE type = $type LIMIT 100"; + N1qlQueryResult r2 = bucket.query(N1qlQuery.parameterized(query, pVal)); + + System.out.println(r2.allRows()); + + List list = extractJsonResult(r2); + System.out.println( + list.get(0).get("travel-sample").get("airportname").asText()); + } + + @Test + public void givenSelectDSL_whenQuery_thenResult() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + Statement statement = select("*") + .from(i("travel-sample")) + .where(x("type").eq(s("airport"))) + .limit(100); + N1qlQueryResult r3 = bucket.query(N1qlQuery.simple(statement)); + + List list2 = extractJsonResult(r3); + System.out.println("First Airport Name: " + list2.get(0).get("travel-sample").get("airportname").asText()); + + } + + @Test + public void givenSelectStatementWithOperators_whenQuery_thenResult() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + String query2 = "SELECT t.city, " + + "t.airportname || \" (\" || t.faa || \")\" AS portname_faa " + + "FROM `travel-sample` t " + + "WHERE t.type=\"airport\"" + + "AND t.country LIKE '%States'" + + "AND t.geo.lat >= 70 " + + "LIMIT 2"; + N1qlQueryResult r4 = bucket.query(N1qlQuery.simple(query2)); + List list3 = extractJsonResult(r4); + System.out.println("First Doc : " + list3.get(0)); + } + + @Test + public void givenSelectStatementWithDSL2_whenQuery_thenResult() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + Statement st2 = select( + x("t.city, t.airportname") + .concat(s(" (")).concat(x("t.faa")).concat(s(")")).as("portname_faa")) + .from(i("travel-sample").as("t")) + .where( x("t.type").eq(s("airport")) + .and(x("t.country").like(s("%States"))) + .and(x("t.geo.lat").gte(70))) + .limit(2); + N1qlQueryResult r5 = bucket.query(N1qlQuery.simple(st2)); + List list5 = extractJsonResult(r5); + System.out.println("First Doc : " + list5.get(0)); + System.out.println("Query from Statement2: " + st2.toString()); + } + + @Test + public void givenInsertStatement_whenQuery_thenUpdate() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + String query = "INSERT INTO `travel-sample` (KEY, VALUE) " + + " VALUES(" + + "\"cust1293\", " + + "{\"id\":\"1293\",\"name\":\"Sample Airline\", \"type\":\"airline\"})" + + " RETURNING META().id as docid, *"; + N1qlQueryResult r1 = bucket.query(N1qlQuery.simple(query)); + r1.forEach(System.out::println); + } + + @Test + public void givenDocument_whenInsert_thenResults() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + JsonObject ob = JsonObject.create() + .put("id", "1293") + .put("name", "Sample Airline") + .put("type", "airline"); + bucket.insert(JsonDocument.create("cust1295", ob)); + } + + @Test + public void givenDocuments_whenBatchInsert_thenResult() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + + List documents = IntStream.rangeClosed(0,10) + .mapToObj( i -> { + JsonObject content = JsonObject.create() + .put("id", i) + .put("type", "airline") + .put("name", "Sample Airline " + i); + return JsonDocument.create("cust_" + i, content); + }) + .collect(Collectors.toList()); + + List r5 = Observable + .from(documents) + .flatMap(doc -> bucket.async().insert(doc)) + .toList() + .last() + .toBlocking() + .single(); + + r5.forEach(System.out::println); + } + + @Test + public void givenUpdateStatement_whenQuery_thenUpdate() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + String query2 = "UPDATE `travel-sample` USE KEYS \"cust_1\" " + + "SET name=\"Sample Airline Updated\" RETURNING name"; + N1qlQueryResult result = bucket.query(N1qlQuery.simple(query2)); + result.forEach(System.out::println); + } + + @Test + public void givenDocument_whenUpsert_thenUpdate() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + JsonObject o2 = JsonObject.create() + .put("name", "Sample Airline Updated"); + bucket.upsert(JsonDocument.create("cust_1", o2)); + } + + @Test + public void givenUnestUpdateStatement_whenQuery_thenResult() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + String query3 = "UPDATE `travel-sample` USE KEYS \"cust_2\" " + + "UNSET name RETURNING *"; + N1qlQueryResult result1 = bucket.query(N1qlQuery.simple(query3)); + result1.forEach(System.out::println); + } + + @Test + public void givenDeleteStatement_whenQuery_thenDelete() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + String query4 = "DELETE FROM `travel-sample` USE KEYS \"cust_50\""; + N1qlQueryResult result4 = bucket.query(N1qlQuery.simple(query4)); + } + + @Test + public void givenDeleteStatement2_whenQuery_thenDelete() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + String query5 = "DELETE FROM `travel-sample` WHERE id = 0 RETURNING *"; + N1qlQueryResult result5 = bucket.query(N1qlQuery.simple(query5)); + } + + +} diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java similarity index 100% rename from couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java b/couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java similarity index 100% rename from couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java rename to couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java similarity index 100% rename from couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java similarity index 100% rename from couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java diff --git a/couchbase-sdk/src/test/resources/logback.xml b/couchbase/src/test/resources/logback.xml similarity index 100% rename from couchbase-sdk/src/test/resources/logback.xml rename to couchbase/src/test/resources/logback.xml diff --git a/ejb/ejbclient/src/main/java/com/baeldung/ejbclient/application/TextApplication.java b/ejb/ejb-client/src/main/java/com/baeldung/ejb/wildfly/TextApplication.java similarity index 92% rename from ejb/ejbclient/src/main/java/com/baeldung/ejbclient/application/TextApplication.java rename to ejb/ejb-client/src/main/java/com/baeldung/ejb/wildfly/TextApplication.java index b65c21100d..3b63761c73 100644 --- a/ejb/ejbclient/src/main/java/com/baeldung/ejbclient/application/TextApplication.java +++ b/ejb/ejb-client/src/main/java/com/baeldung/ejb/wildfly/TextApplication.java @@ -1,7 +1,5 @@ -package com.baeldung.ejbclient.application; +package com.baeldung.ejb.wildfly; -import com.baeldung.ejbmodule.TextProcessorBean; -import com.baeldung.ejbmodule.TextProcessorRemote; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; diff --git a/ejb/ejbclient/src/test/java/com/baeldung/ejbclient/application/TextApplicationTest.java b/ejb/ejb-client/src/test/java/com/baeldung/ejb/wildfly/TextApplicationTest.java similarity index 94% rename from ejb/ejbclient/src/test/java/com/baeldung/ejbclient/application/TextApplicationTest.java rename to ejb/ejb-client/src/test/java/com/baeldung/ejb/wildfly/TextApplicationTest.java index 947c72d0b0..c0446eaea6 100644 --- a/ejb/ejbclient/src/test/java/com/baeldung/ejbclient/application/TextApplicationTest.java +++ b/ejb/ejb-client/src/test/java/com/baeldung/ejb/wildfly/TextApplicationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.ejbclient.application; +package com.baeldung.ejb.wildfly; import org.junit.AfterClass; import org.junit.BeforeClass; diff --git a/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorBean.java b/ejb/ejb-remote/src/main/java/com/baeldung/ejb/wildfly/TextProcessorBean.java similarity index 85% rename from ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorBean.java rename to ejb/ejb-remote/src/main/java/com/baeldung/ejb/wildfly/TextProcessorBean.java index dc0db5fc53..4f0c013b0f 100644 --- a/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorBean.java +++ b/ejb/ejb-remote/src/main/java/com/baeldung/ejb/wildfly/TextProcessorBean.java @@ -1,4 +1,4 @@ -package com.baeldung.ejbmodule; +package com.baeldung.ejb.wildfly; import javax.ejb.Stateless; diff --git a/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorRemote.java b/ejb/ejb-remote/src/main/java/com/baeldung/ejb/wildfly/TextProcessorRemote.java similarity index 76% rename from ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorRemote.java rename to ejb/ejb-remote/src/main/java/com/baeldung/ejb/wildfly/TextProcessorRemote.java index 680d8f4e10..b51af8528d 100644 --- a/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorRemote.java +++ b/ejb/ejb-remote/src/main/java/com/baeldung/ejb/wildfly/TextProcessorRemote.java @@ -1,4 +1,4 @@ -package com.baeldung.ejbmodule; +package com.baeldung.ejb.wildfly; import javax.ejb.Remote; diff --git a/ejb/ejbclient/src/main/resources/jboss-ejb-client.properties b/ejb/ejbclient/src/main/resources/jboss-ejb-client.properties deleted file mode 100644 index 67533b7825..0000000000 --- a/ejb/ejbclient/src/main/resources/jboss-ejb-client.properties +++ /dev/null @@ -1,8 +0,0 @@ -endpoint.name=client-endpoint -remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false -remote.connections=default -remote.connection.default.host=127.0.0.1 -remote.connection.default.port=8080 -remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false -remote.connection.default.username=myusername -remote.connection.default.password=mypassword \ No newline at end of file diff --git a/ejb/ejbmodule/src/test/java/com/baeldung/ejbmodule/TextProcessorBeanTest.java b/ejb/ejbmodule/src/test/java/com/baeldung/ejbmodule/TextProcessorBeanTest.java deleted file mode 100644 index d8693420d4..0000000000 --- a/ejb/ejbmodule/src/test/java/com/baeldung/ejbmodule/TextProcessorBeanTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.ejbmodule; - -import org.junit.Test; -import static org.junit.Assert.assertEquals; - -public class TextProcessorBeanTest { - @Test - public void givenInputString_whenComparedToStringParsedByBean_thenSuccessful() { - TextProcessorBean textProcessor = new TextProcessorBean(); - assertEquals("TEST", textProcessor.processText("test")); - } -} \ No newline at end of file diff --git a/ejb/pom.xml b/ejb/pom.xml index b8aa32fab1..78e40a7b7c 100755 --- a/ejb/pom.xml +++ b/ejb/pom.xml @@ -81,6 +81,5 @@ ejb-remote ejb-client ejb-session-beans - ejb-session-beans-client \ No newline at end of file diff --git a/ethereumj/.gitgnore b/ethereumj/.gitgnore new file mode 100644 index 0000000000..9cff80e071 --- /dev/null +++ b/ethereumj/.gitgnore @@ -0,0 +1,6 @@ +.idea +target +database +logs +target +*.iml \ No newline at end of file diff --git a/ethereumj/README.md b/ethereumj/README.md new file mode 100644 index 0000000000..54da91b4f7 --- /dev/null +++ b/ethereumj/README.md @@ -0,0 +1,4 @@ +## EthereumJ + +### Relevant Articles: +- [Introduction to EthereumJ](http://www.baeldung.com/intro-to-ethereumj) \ No newline at end of file diff --git a/ethereumj/pom.xml b/ethereumj/pom.xml new file mode 100644 index 0000000000..c9f5924d7a --- /dev/null +++ b/ethereumj/pom.xml @@ -0,0 +1,110 @@ + + + 4.0.0 + com.baeldung.ethereumj + ethereumj + war + 1.0.0 + ethereumj + + + UTF-8 + 1.8 + 8.5.4 + + + + org.springframework.boot + spring-boot-starter-parent + 1.5.6.RELEASE + + + + + Ethereum + Ethereum + https://dl.bintray.com/ethereum/maven/ + + + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + + org.springframework.boot + spring-boot-starter-test + 1.5.6.RELEASE + test + + + + + org.ethereum + ethereumj-core + 1.5.0-RELEASE + + + + + javax.servlet + jstl + + + com.fasterxml.jackson.core + jackson-databind + 2.5.0 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + ethereumj + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + */EthControllerTestOne.java + + + + + + + + + + \ No newline at end of file diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/ApplicationMain.java b/ethereumj/src/main/java/com/baeldung/ethereumj/ApplicationMain.java new file mode 100644 index 0000000000..4735548bd1 --- /dev/null +++ b/ethereumj/src/main/java/com/baeldung/ethereumj/ApplicationMain.java @@ -0,0 +1,16 @@ +package com.baeldung.ethereumj; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.web.support.SpringBootServletInitializer; + +@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) +@SpringBootApplication +public class ApplicationMain extends SpringBootServletInitializer { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } +} \ No newline at end of file diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/Constants.java b/ethereumj/src/main/java/com/baeldung/ethereumj/Constants.java new file mode 100644 index 0000000000..919958be35 --- /dev/null +++ b/ethereumj/src/main/java/com/baeldung/ethereumj/Constants.java @@ -0,0 +1,9 @@ +package com.baeldung.ethereumj; + +public class Constants { + + public static final String ENDPOINT_ONE = "/api/get/bestblock/"; + public static final String ENDPOINT_TWO = "/api/get/difficulty/"; + public static final String RESPONSE_TYPE ="application/json/"; + +} diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/beans/EthBean.java b/ethereumj/src/main/java/com/baeldung/ethereumj/beans/EthBean.java new file mode 100644 index 0000000000..7680473c6e --- /dev/null +++ b/ethereumj/src/main/java/com/baeldung/ethereumj/beans/EthBean.java @@ -0,0 +1,25 @@ +package com.baeldung.ethereumj.beans; + +import com.baeldung.ethereumj.listeners.EthListener; +import org.ethereum.core.Block; +import org.ethereum.facade.Ethereum; +import org.ethereum.facade.EthereumFactory; + +import java.math.BigInteger; + +public class EthBean { + private Ethereum ethereum; + + public void start() { + this.ethereum = EthereumFactory.createEthereum(); + this.ethereum.addListener(new EthListener(ethereum)); + } + + public Block getBestBlock() { + return this.ethereum.getBlockchain().getBestBlock(); + } + + public BigInteger getTotalDifficulty() { + return this.ethereum.getBlockchain().getTotalDifficulty(); + } +} \ No newline at end of file diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/config/EthConfig.java b/ethereumj/src/main/java/com/baeldung/ethereumj/config/EthConfig.java new file mode 100644 index 0000000000..8180cc3ce2 --- /dev/null +++ b/ethereumj/src/main/java/com/baeldung/ethereumj/config/EthConfig.java @@ -0,0 +1,18 @@ +package com.baeldung.ethereumj.config; + +import com.baeldung.ethereumj.beans.EthBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.concurrent.Executors; + +@Configuration +public class EthConfig { + + @Bean + EthBean ethBeanConfig() throws Exception { + EthBean eBean = new EthBean(); + Executors.newSingleThreadExecutor().submit(eBean::start); + return eBean; + } +} \ No newline at end of file diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/controllers/EthController.java b/ethereumj/src/main/java/com/baeldung/ethereumj/controllers/EthController.java new file mode 100644 index 0000000000..8240d60e30 --- /dev/null +++ b/ethereumj/src/main/java/com/baeldung/ethereumj/controllers/EthController.java @@ -0,0 +1,44 @@ +package com.baeldung.ethereumj.controllers; + +import com.baeldung.ethereumj.Constants; +import com.baeldung.ethereumj.beans.EthBean; +import com.baeldung.ethereumj.transfer.EthResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.PostConstruct; +import javax.servlet.ServletContext; + +@RestController +public class EthController { + + @Autowired + EthBean ethBean; + @Autowired + private ServletContext servletContext; + private Logger l = LoggerFactory.getLogger(EthController.class); + + @RequestMapping(Constants.ENDPOINT_ONE) + public EthResponse getBestBlock() { + l.debug("Request received - fetching best block."); + EthResponse r = new EthResponse(); + r.setResponse(ethBean.getBestBlock().toString()); + return r; + } + + @RequestMapping(Constants.ENDPOINT_TWO) + public EthResponse getTotalDifficulty() { + l.debug("Request received - calculating total difficulty."); + EthResponse r = new EthResponse(); + r.setResponse(ethBean.getTotalDifficulty().toString()); + return r; + } + + @PostConstruct + public void showIt() { + l.debug(servletContext.getContextPath()); + } +} diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/listeners/EthListener.java b/ethereumj/src/main/java/com/baeldung/ethereumj/listeners/EthListener.java new file mode 100644 index 0000000000..c3a5143fdb --- /dev/null +++ b/ethereumj/src/main/java/com/baeldung/ethereumj/listeners/EthListener.java @@ -0,0 +1,71 @@ +package com.baeldung.ethereumj.listeners; + +import org.ethereum.core.Block; +import org.ethereum.core.TransactionReceipt; +import org.ethereum.facade.Ethereum; +import org.ethereum.listener.EthereumListenerAdapter; +import org.ethereum.util.BIUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.math.BigInteger; +import java.util.List; + +public class EthListener extends EthereumListenerAdapter { + + private Logger l = LoggerFactory.getLogger(EthListener.class); + private Ethereum ethereum; + private boolean syncDone = false; + private static final int thou = 1000; + + private void out(String t) { + l.info(t); + } + + private String calcNetHashRate(Block block) { + String response = "Net hash rate not available"; + if (block.getNumber() > thou) { + long timeDelta = 0; + for (int i = 0; i < thou; ++i) { + Block parent = ethereum + .getBlockchain() + .getBlockByHash(block.getParentHash()); + timeDelta += Math.abs(block.getTimestamp() - parent.getTimestamp()); + } + response = String.valueOf(block + .getDifficultyBI() + .divide(BIUtil.toBI(timeDelta / thou)) + .divide(new BigInteger("1000000000")) + .doubleValue()) + " GH/s"; + } + return response; + } + + public EthListener(Ethereum ethereum) { + this.ethereum = ethereum; + } + + @Override + public void onBlock(Block block, List receipts) { + if (syncDone) { + out("Net hash rate: " + calcNetHashRate(block)); + out("Block difficulty: " + block.getDifficultyBI().toString()); + out("Block transactions: " + block.getTransactionsList().toString()); + out("Best block (last block): " + ethereum + .getBlockchain() + .getBestBlock().toString()); + out("Total difficulty: " + ethereum + .getBlockchain() + .getTotalDifficulty().toString()); + } + } + + @Override + public void onSyncDone(SyncState state) { + out("onSyncDone " + state); + if (!syncDone) { + out(" ** SYNC DONE ** "); + syncDone = true; + } + } +} \ No newline at end of file diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/transfer/EthResponse.java b/ethereumj/src/main/java/com/baeldung/ethereumj/transfer/EthResponse.java new file mode 100644 index 0000000000..e8cfb3113b --- /dev/null +++ b/ethereumj/src/main/java/com/baeldung/ethereumj/transfer/EthResponse.java @@ -0,0 +1,14 @@ +package com.baeldung.ethereumj.transfer; + +public class EthResponse { + + private String response; + + public String getResponse() { + return response; + } + + public void setResponse(String response) { + this.response = response; + } +} diff --git a/ethereumj/src/main/resources/application.properties b/ethereumj/src/main/resources/application.properties new file mode 100644 index 0000000000..033e543fe8 --- /dev/null +++ b/ethereumj/src/main/resources/application.properties @@ -0,0 +1,2 @@ +server.servlet-path=/ +server.port=8080 \ No newline at end of file diff --git a/ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerTestOne.java b/ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerTestOne.java new file mode 100644 index 0000000000..9298c34ec2 --- /dev/null +++ b/ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerTestOne.java @@ -0,0 +1,72 @@ +package com.baeldung.ethereumj.controllers; + +import com.baeldung.ethereumj.ApplicationMain; +import com.baeldung.ethereumj.Constants; +import com.baeldung.ethereumj.transfer.EthResponse; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.*; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.client.RestTemplate; + +import static junit.framework.TestCase.assertTrue; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ApplicationMain.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +@TestPropertySource(properties = "server.port=8080") +public class EthControllerTestOne { + + @LocalServerPort + int port; + + private RestTemplate restTemplate = new RestTemplate(); + + private String url(String uri) { + String s = "http://localhost:" + port + uri; + System.out.println(s); + return s; + } + + @Before + public void setup() { + restTemplate = new RestTemplate(); + } + + @Test() + public void bestBlockTest() throws Exception { + + Thread.sleep(20000); + + EthResponse a = restTemplate.getForObject(url(Constants.ENDPOINT_ONE), EthResponse.class); + assertNotNull(a); + + ResponseEntity b = restTemplate.exchange( + url(Constants.ENDPOINT_ONE), + HttpMethod.GET, new HttpEntity(null, new HttpHeaders()), EthResponse.class); + + assertTrue("Status 200?", b.getStatusCode().equals(HttpStatus.OK)); + System.out.println("Status 200?: " + b.getStatusCode().equals(HttpStatus.OK)); + assertTrue("Dynamic data returned?", b.hasBody()); + System.out.println("Dynamic data returned?: " + b.hasBody()); + } + + @Test() + public void difficultyTest() throws Exception { + + Thread.sleep(20000); + + ResponseEntity a = restTemplate.exchange( + url(Constants.ENDPOINT_TWO), + HttpMethod.GET, new HttpEntity(null, new HttpHeaders()), EthResponse.class); + + assertTrue("Status 200?", a.getStatusCode().equals(HttpStatus.OK)); + System.out.println("Status 200?: " + a.getStatusCode().equals(HttpStatus.OK)); + assertTrue("Dynamic data returned?", a.hasBody()); + System.out.println("Dynamic data returned?: " + a.hasBody()); + } +} diff --git a/geotools/pom.xml b/geotools/pom.xml new file mode 100644 index 0000000000..37b4a2338a --- /dev/null +++ b/geotools/pom.xml @@ -0,0 +1,74 @@ + + 4.0.0 + + com.baeldung + geotools + 0.0.1-SNAPSHOT + jar + + geotools + http://maven.apache.org + + + + junit + junit + 4.12 + test + + + org.geotools + gt-shapefile + ${geotools-shapefile.version} + + + org.geotools + gt-epsg-hsql + ${geotools.version} + + + org.geotools + gt-swing + ${geotools-swing.version} + + + + + maven2-repository.dev.java.net + Java.net repository + http://download.java.net/maven/2 + + + osgeo + Open Source Geospatial Foundation Repository + http://download.osgeo.org/webdav/geotools/ + + + + true + + opengeo + OpenGeo Maven Repository + http://repo.opengeo.org + + + + + + true + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + 15.2 + 15.2 + 15.2 + + diff --git a/libraries/src/main/java/com/baeldung/geotools/ShapeFile.java b/geotools/src/main/java/com/baeldung/geotools/ShapeFile.java similarity index 71% rename from libraries/src/main/java/com/baeldung/geotools/ShapeFile.java rename to geotools/src/main/java/com/baeldung/geotools/ShapeFile.java index 77c67abc84..de789918cd 100644 --- a/libraries/src/main/java/com/baeldung/geotools/ShapeFile.java +++ b/geotools/src/main/java/com/baeldung/geotools/ShapeFile.java @@ -1,12 +1,8 @@ package com.baeldung.geotools; -import java.io.File; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.vividsolutions.jts.geom.Coordinate; +import com.vividsolutions.jts.geom.GeometryFactory; +import com.vividsolutions.jts.geom.Point; import org.geotools.data.DataUtilities; import org.geotools.data.DefaultTransaction; import org.geotools.data.Transaction; @@ -23,9 +19,13 @@ import org.geotools.swing.data.JFileDataStoreChooser; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; -import com.vividsolutions.jts.geom.Coordinate; -import com.vividsolutions.jts.geom.GeometryFactory; -import com.vividsolutions.jts.geom.Point; +import java.io.File; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; public class ShapeFile { @@ -41,22 +41,117 @@ public class ShapeFile { SimpleFeatureType CITY = createFeatureType(); - SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY); - - addLocations(featureBuilder, collection); + addLocations(CITY, collection); File shapeFile = getNewShapeFile(); ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); Map params = new HashMap(); + + ShapefileDataStore dataStore = setDataStoreParams(dataStoreFactory, params, shapeFile, CITY); + + writeToFile(dataStore, collection); + } + + static SimpleFeatureType createFeatureType() { + + SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder(); + builder.setName("Location"); + builder.setCRS(DefaultGeographicCRS.WGS84); + + builder.add("Location", Point.class); + builder.length(15) + .add("Name", String.class); + + return builder.buildFeatureType(); + } + + static void addLocations(SimpleFeatureType CITY, DefaultFeatureCollection collection) { + + Map> locations = new HashMap<>(); + + double lat = 13.752222; + double lng = 100.493889; + addToLocationMap("Bangkok", lat, lng, locations); + + lat = 53.083333; + lng = -0.15; + addToLocationMap("New York", lat, lng, locations); + + lat = -33.925278; + lng = 18.423889; + addToLocationMap("Cape Town", lat, lng, locations); + + lat = -33.859972; + lng = 151.211111; + addToLocationMap("Sydney", lat, lng, locations); + + lat = 45.420833; + lng = -75.69; + addToLocationMap("Ottawa", lat, lng, locations); + + lat = 30.07708; + lng = 31.285909; + addToLocationMap("Cairo", lat, lng, locations); + + GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); + + locations.entrySet().stream() + .map(toFeature(CITY, geometryFactory)) + .forEach(collection::add); + } + + private static Function>, SimpleFeature> toFeature(SimpleFeatureType CITY, GeometryFactory geometryFactory) { + return location -> { + Point point = geometryFactory.createPoint( + new Coordinate(location.getValue() + .get(0), location.getValue().get(1))); + + SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY); + featureBuilder.add(point); + featureBuilder.add(location.getKey()); + return featureBuilder.buildFeature(null); + }; + } + + private static void addToLocationMap(String name, double lat, double lng, Map> locations) { + List coordinates = new ArrayList<>(); + + coordinates.add(lat); + coordinates.add(lng); + locations.put(name, coordinates); + } + + private static File getNewShapeFile() { + String filePath = new File(".").getAbsolutePath() + FILE_NAME; + + JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp"); + chooser.setDialogTitle("Save shapefile"); + chooser.setSelectedFile(new File(filePath)); + + int returnVal = chooser.showSaveDialog(null); + + if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) { + System.exit(0); + } + + return chooser.getSelectedFile(); + } + + private static ShapefileDataStore setDataStoreParams(ShapefileDataStoreFactory dataStoreFactory, Map params, File shapeFile, SimpleFeatureType CITY) throws Exception { params.put("url", shapeFile.toURI() - .toURL()); + .toURL()); params.put("create spatial index", Boolean.TRUE); ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); dataStore.createSchema(CITY); + return dataStore; + } + + private static void writeToFile(ShapefileDataStore dataStore, DefaultFeatureCollection collection) throws Exception { + // If you decide to use the TYPE type and create a Data Store with it, // You will need to uncomment this line to set the Coordinate Reference System // newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84); @@ -73,11 +168,9 @@ public class ShapeFile { try { featureStore.addFeatures(collection); transaction.commit(); - } catch (Exception problem) { problem.printStackTrace(); transaction.rollback(); - } finally { transaction.close(); } @@ -86,102 +179,5 @@ public class ShapeFile { System.out.println(typeName + " does not support read/write access"); System.exit(1); } - } - - public static SimpleFeatureType createFeatureType() { - - SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder(); - builder.setName("Location"); - builder.setCRS(DefaultGeographicCRS.WGS84); - - builder.add("Location", Point.class); - builder.length(15) - .add("Name", String.class); - - SimpleFeatureType CITY = builder.buildFeatureType(); - - return CITY; - } - - public static void addLocations(SimpleFeatureBuilder featureBuilder, DefaultFeatureCollection collection) { - - Map> locations = new HashMap<>(); - - double lat = 13.752222; - double lng = 100.493889; - String name = "Bangkok"; - addToLocationMap(name, lat, lng, locations); - - lat = 53.083333; - lng = -0.15; - name = "New York"; - addToLocationMap(name, lat, lng, locations); - - lat = -33.925278; - lng = 18.423889; - name = "Cape Town"; - addToLocationMap(name, lat, lng, locations); - - lat = -33.859972; - lng = 151.211111; - name = "Sydney"; - addToLocationMap(name, lat, lng, locations); - - lat = 45.420833; - lng = -75.69; - name = "Ottawa"; - addToLocationMap(name, lat, lng, locations); - - lat = 30.07708; - lng = 31.285909; - name = "Cairo"; - addToLocationMap(name, lat, lng, locations); - - GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); - - for (Map.Entry> location : locations.entrySet()) { - Point point = geometryFactory.createPoint(new Coordinate(location.getValue() - .get(0), - location.getValue() - .get(1))); - featureBuilder.add(point); - featureBuilder.add(name); - SimpleFeature feature = featureBuilder.buildFeature(null); - collection.add(feature); - } - - } - - private static void addToLocationMap(String name, double lat, double lng, Map> locations) { - List coordinates = new ArrayList<>(); - - coordinates.add(lat); - coordinates.add(lng); - locations.put(name, coordinates); - } - - private static File getNewShapeFile() { - String filePath = new File(".").getAbsolutePath() + FILE_NAME; - - - JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp"); - chooser.setDialogTitle("Save shapefile"); - chooser.setSelectedFile(new File(filePath)); - - int returnVal = chooser.showSaveDialog(null); - - if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) { - System.exit(0); - } - - File shapeFile = chooser.getSelectedFile(); - if (shapeFile.equals(filePath)) { - System.out.println("Error: cannot replace " + filePath); - System.exit(0); - } - - return shapeFile; - } - } diff --git a/libraries/src/test/java/com/baeldung/geotools/GeoToolsUnitTestTest.java b/geotools/src/test/java/com/baeldung/geotools/GeoToolsUnitTest.java similarity index 75% rename from libraries/src/test/java/com/baeldung/geotools/GeoToolsUnitTestTest.java rename to geotools/src/test/java/com/baeldung/geotools/GeoToolsUnitTest.java index 44cd47edc3..053932b2a7 100644 --- a/libraries/src/test/java/com/baeldung/geotools/GeoToolsUnitTestTest.java +++ b/geotools/src/test/java/com/baeldung/geotools/GeoToolsUnitTest.java @@ -7,21 +7,16 @@ import org.geotools.feature.simple.SimpleFeatureBuilder; import org.junit.Test; import org.opengis.feature.simple.SimpleFeatureType; -public class GeoToolsUnitTestTest { +public class GeoToolsUnitTest { @Test public void givenFeatureType_whenAddLocations_returnFeatureCollection() { - DefaultFeatureCollection collection = new DefaultFeatureCollection(); SimpleFeatureType CITY = ShapeFile.createFeatureType(); - SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY); - - ShapeFile.addLocations(featureBuilder, collection); + ShapeFile.addLocations(CITY, collection); assertNotNull(collection); - } - } diff --git a/graphql/graphql-java/payload-examples/createUser.json b/graphql/graphql-java/payload-examples/createUser.json new file mode 100644 index 0000000000..3ade405b16 --- /dev/null +++ b/graphql/graphql-java/payload-examples/createUser.json @@ -0,0 +1,8 @@ +{ + "query": "mutation($name: String! $email: String! $age: String! ){ createUser ( name: $name email: $email age: $age) { id name email age } }", + "parameters": { + "name": "John", + "email": "john@email.com", + "age": 34 + } +} \ No newline at end of file diff --git a/graphql/graphql-java/payload-examples/deleteUser.json b/graphql/graphql-java/payload-examples/deleteUser.json new file mode 100644 index 0000000000..204496f19b --- /dev/null +++ b/graphql/graphql-java/payload-examples/deleteUser.json @@ -0,0 +1,6 @@ +{ + "query": "mutation($name: String! ){ deleteUser ( id: $id) { id name email age} }", + "parameters": { + "id": 2 + } +} \ No newline at end of file diff --git a/graphql/graphql-java/payload-examples/listUsers.json b/graphql/graphql-java/payload-examples/listUsers.json new file mode 100644 index 0000000000..dde887bb07 --- /dev/null +++ b/graphql/graphql-java/payload-examples/listUsers.json @@ -0,0 +1,4 @@ +{ + "query": "{ listUsers{ id name email age}}", + "parameters": {} +} \ No newline at end of file diff --git a/graphql/graphql-java/payload-examples/retrieveUser.json b/graphql/graphql-java/payload-examples/retrieveUser.json new file mode 100644 index 0000000000..27b5f422eb --- /dev/null +++ b/graphql/graphql-java/payload-examples/retrieveUser.json @@ -0,0 +1,6 @@ +{ + "query": "query($id: String!){ retrieveUser ( id: $id) { id name email} }", + "parameters": { + "id": 1 + } +} \ No newline at end of file diff --git a/graphql/graphql-java/payload-examples/searchName.json b/graphql/graphql-java/payload-examples/searchName.json new file mode 100644 index 0000000000..df8f080b86 --- /dev/null +++ b/graphql/graphql-java/payload-examples/searchName.json @@ -0,0 +1,6 @@ +{ + "query": "query($id: String!){ searchName ( id: $id) { id name email} }", + "parameters": { + "id": 2 + } +} \ No newline at end of file diff --git a/graphql/graphql-java/payload-examples/updateUser.json b/graphql/graphql-java/payload-examples/updateUser.json new file mode 100644 index 0000000000..aa68151111 --- /dev/null +++ b/graphql/graphql-java/payload-examples/updateUser.json @@ -0,0 +1,9 @@ +{ + "query": "mutation($id: String! $name: String! $email: String! $age: String! ){ updateUser ( id: $id name: $name email: $email age: $age) { id name email age} }", + "parameters": { + "id": 1, + "name":"John updated", + "email": "johnupdate@email.com", + "age": 50 + } +} \ No newline at end of file diff --git a/graphql/graphql-java/pom.xml b/graphql/graphql-java/pom.xml new file mode 100644 index 0000000000..c031ddc694 --- /dev/null +++ b/graphql/graphql-java/pom.xml @@ -0,0 +1,29 @@ + + 4.0.0 + + com.baeldung.graphql + graphql-java + 1.0 + + graphql-java + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + com.graphql-java + graphql-java-annotations + 3.0.3 + + + io.ratpack + ratpack-core + 1.4.6 + + + \ No newline at end of file diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/Application.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/Application.java new file mode 100644 index 0000000000..6e9b2a5c80 --- /dev/null +++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/Application.java @@ -0,0 +1,17 @@ +package com.baeldung.graphql; + +import ratpack.server.RatpackServer; + +import com.baeldung.graphql.handler.UserHandler; + +public class Application { + public static void main(String[] args) throws Exception { + new Application(); + } + + private Application() throws Exception { + final RatpackServer server = RatpackServer.of(s -> s.handlers(chain -> chain.post("users", new UserHandler()))); + server.start(); + } + +} diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/entity/User.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/entity/User.java new file mode 100644 index 0000000000..a4a776cfff --- /dev/null +++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/entity/User.java @@ -0,0 +1,78 @@ +package com.baeldung.graphql.entity; + +import java.util.List; + +import com.baeldung.graphql.handler.UserHandler; +import com.baeldung.graphql.utils.SchemaUtils; + +import graphql.annotations.GraphQLField; +import graphql.annotations.GraphQLName; + +@GraphQLName(SchemaUtils.USER) +public class User { + + @GraphQLField + private Long id; + @GraphQLField + private String name; + @GraphQLField + private String email; + @GraphQLField + private Integer age; + + public User(String name, String email, Integer age) { + this.id = genId(); + this.name = name; + this.email = email; + this.age = age; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getEmail() { + return email; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public static Long genId() { + Long id = 1L; + try { + List users = new UserHandler().getUsers(); + for (User user : users) + id = (user.getId() > id ? user.getId() : id) + 1; + + } catch (Exception e) { + e.printStackTrace(); + } + return id; + } + + public String toString() { + return "[id=" + id + ", name=" + name + ", email="+email+ ", age="+ age +"]"; + } +} \ No newline at end of file diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/handler/UserHandler.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/handler/UserHandler.java new file mode 100644 index 0000000000..a6d474a70d --- /dev/null +++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/handler/UserHandler.java @@ -0,0 +1,56 @@ +package com.baeldung.graphql.handler; + +import graphql.ExecutionResult; +import graphql.GraphQL; +import graphql.schema.DataFetchingEnvironment; +import ratpack.handling.Context; +import ratpack.handling.Handler; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; + +import com.baeldung.graphql.entity.User; +import com.baeldung.graphql.schema.UserSchema; +import com.baeldung.graphql.utils.SchemaUtils; + +import static ratpack.jackson.Jackson.json; + +public class UserHandler implements Handler { + private static final Logger LOGGER = Logger.getLogger(UserHandler.class.getSimpleName()); + private GraphQL graphql; + private static List users = new ArrayList<>(); + + public UserHandler() throws Exception { + graphql = new GraphQL(new UserSchema().getSchema()); + } + + @Override + public void handle(Context context) throws Exception { + context.parse(Map.class) + .then(payload -> { + Map parameters = (Map) payload.get("parameters"); + ExecutionResult executionResult = graphql.execute(payload.get(SchemaUtils.QUERY) + .toString(), null, this, parameters); + Map result = new LinkedHashMap<>(); + if (executionResult.getErrors() + .isEmpty()) { + result.put(SchemaUtils.DATA, executionResult.getData()); + } else { + result.put(SchemaUtils.ERRORS, executionResult.getErrors()); + LOGGER.warning("Errors: " + executionResult.getErrors()); + } + context.render(json(result)); + }); + } + + public static List getUsers() { + return users; + } + + public static List getUsers(DataFetchingEnvironment env) { + return ((UserHandler) env.getSource()).getUsers(); + } +} diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/mutation/UserMutation.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/mutation/UserMutation.java new file mode 100644 index 0000000000..3c6f53a382 --- /dev/null +++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/mutation/UserMutation.java @@ -0,0 +1,57 @@ +package com.baeldung.graphql.mutation; + +import graphql.annotations.GraphQLField; +import graphql.annotations.GraphQLName; +import graphql.schema.DataFetchingEnvironment; + +import javax.validation.constraints.NotNull; + +import com.baeldung.graphql.entity.User; +import com.baeldung.graphql.utils.SchemaUtils; + +import java.util.List; +import java.util.Optional; + +import static com.baeldung.graphql.handler.UserHandler.getUsers; + +@GraphQLName(SchemaUtils.MUTATION) +public class UserMutation { + @GraphQLField + public static User createUser(final DataFetchingEnvironment env, @NotNull @GraphQLName(SchemaUtils.NAME) final String name, @NotNull @GraphQLName(SchemaUtils.EMAIL) final String email, @NotNull @GraphQLName(SchemaUtils.AGE) final String age) { + List users = getUsers(env); + final User user = new User(name, email, Integer.valueOf(age)); + users.add(user); + return user; + } + + @GraphQLField + public static User updateUser(final DataFetchingEnvironment env, @NotNull @GraphQLName(SchemaUtils.ID) final String id, @NotNull @GraphQLName(SchemaUtils.NAME) final String name, @NotNull @GraphQLName(SchemaUtils.EMAIL) final String email, + @NotNull @GraphQLName(SchemaUtils.AGE) final String age) { + final Optional user = getUsers(env).stream() + .filter(c -> c.getId() == Long.parseLong(id)) + .findFirst(); + if (!user.isPresent()) { + return null; + } + user.get() + .setName(name); + user.get() + .setEmail(email); + user.get() + .setAge(Integer.valueOf(age)); + return user.get(); + } + + @GraphQLField + public static User deleteUser(final DataFetchingEnvironment env, @NotNull @GraphQLName(SchemaUtils.ID) final String id) { + final List users = getUsers(env); + final Optional user = users.stream() + .filter(c -> c.getId() == Long.parseLong(id)) + .findFirst(); + if (!user.isPresent()) { + return null; + } + users.removeIf(c -> c.getId() == Long.parseLong(id)); + return user.get(); + } +} diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/query/UserQuery.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/query/UserQuery.java new file mode 100644 index 0000000000..6f1521c5cf --- /dev/null +++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/query/UserQuery.java @@ -0,0 +1,42 @@ +package com.baeldung.graphql.query; + +import graphql.annotations.GraphQLField; +import graphql.annotations.GraphQLName; +import graphql.schema.DataFetchingEnvironment; + +import javax.validation.constraints.NotNull; + +import com.baeldung.graphql.entity.User; +import com.baeldung.graphql.utils.SchemaUtils; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static com.baeldung.graphql.handler.UserHandler.getUsers; + +@GraphQLName(SchemaUtils.QUERY) +public class UserQuery { + + @GraphQLField + public static User retrieveUser(final DataFetchingEnvironment env, @NotNull @GraphQLName(SchemaUtils.ID) final String id) { + final Optional any = getUsers(env).stream() + .filter(c -> c.getId() == Long.parseLong(id)) + .findFirst(); + return any.orElse(null); + } + + @GraphQLField + public static List searchName(final DataFetchingEnvironment env, @NotNull @GraphQLName(SchemaUtils.NAME) final String name) { + return getUsers(env).stream() + .filter(c -> c.getName() + .contains(name)) + .collect(Collectors.toList()); + } + + @GraphQLField + public static List listUsers(final DataFetchingEnvironment env) { + return getUsers(env); + } + +} \ No newline at end of file diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/schema/UserSchema.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/schema/UserSchema.java new file mode 100644 index 0000000000..ebb3569aac --- /dev/null +++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/schema/UserSchema.java @@ -0,0 +1,24 @@ +package com.baeldung.graphql.schema; + +import graphql.annotations.GraphQLAnnotations; +import graphql.schema.GraphQLSchema; + +import static graphql.schema.GraphQLSchema.newSchema; + +import com.baeldung.graphql.mutation.UserMutation; +import com.baeldung.graphql.query.UserQuery; + +public class UserSchema { + + private final GraphQLSchema schema; + + public UserSchema() throws IllegalAccessException, NoSuchMethodException, InstantiationException { + schema = newSchema().query(GraphQLAnnotations.object(UserQuery.class)) + .mutation(GraphQLAnnotations.object(UserMutation.class)) + .build(); + } + + public GraphQLSchema getSchema() { + return schema; + } +} diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/utils/SchemaUtils.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/utils/SchemaUtils.java new file mode 100644 index 0000000000..680d7e3ea9 --- /dev/null +++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/utils/SchemaUtils.java @@ -0,0 +1,14 @@ +package com.baeldung.graphql.utils; + +public class SchemaUtils { + public static final String USER = "user"; + public static final String ID = "id"; + public static final String NAME = "name"; + public static final String EMAIL = "email"; + public static final String AGE = "age"; + + public static final String MUTATION = "mutation"; + public static final String QUERY = "query"; + public static final String ERRORS = "errors"; + public static final String DATA = "data"; +} diff --git a/grpc/README.md b/grpc/README.md new file mode 100644 index 0000000000..5a60ca2e7e --- /dev/null +++ b/grpc/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to gRPC](http://www.baeldung.com/grpc-introduction) diff --git a/guest/core-java-9/pom.xml b/guest/core-java-9/pom.xml new file mode 100644 index 0000000000..d588df4abc --- /dev/null +++ b/guest/core-java-9/pom.xml @@ -0,0 +1,27 @@ + + 4.0.0 + com.stackify + core-java-9 + 0.0.1-SNAPSHOT + + + + junit + junit + 4.12 + + + + + + + maven-compiler-plugin + 3.6.2 + + 1.9 + 1.9 + + + + + \ No newline at end of file diff --git a/guest/core-java-9/src/main/java/com/stackify/optional/User.java b/guest/core-java-9/src/main/java/com/stackify/optional/User.java new file mode 100644 index 0000000000..903e75f6f6 --- /dev/null +++ b/guest/core-java-9/src/main/java/com/stackify/optional/User.java @@ -0,0 +1,28 @@ +package com.stackify.optional; + +public class User { + private String email; + private String password; + + public User(String email, String password) { + super(); + this.email = email; + this.password = password; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/guest/core-java-9/src/test/java/com/stackify/optional/OptionalTest.java b/guest/core-java-9/src/test/java/com/stackify/optional/OptionalTest.java new file mode 100644 index 0000000000..4c3503b811 --- /dev/null +++ b/guest/core-java-9/src/test/java/com/stackify/optional/OptionalTest.java @@ -0,0 +1,41 @@ +package com.stackify.optional; + +import org.junit.Test; +import java.util.Optional; +import java.util.List; + +import static org.junit.Assert.*; +import java.util.stream.Collectors; + +public class OptionalTest { + + private User user; + + @Test + public void whenEmptyOptional_thenGetValueFromOr() { + User result = Optional.ofNullable(user) + .or( () -> Optional.of(new User("default","1234"))).get(); + + assertEquals(result.getEmail(), "default"); + } + + @Test + public void whenIfPresentOrElse_thenOk() { + Optional.ofNullable(user) + .ifPresentOrElse( u -> System.out.println("User is:" + u.getEmail()), () -> System.out.println("User not found")); + } + + @Test + public void whenGetStream_thenOk() { + User user = new User("john@gmail.com", "1234"); + List emails = Optional.ofNullable(user) + .stream() + .filter(u -> u.getEmail() != null && u.getEmail().contains("@")) + .map( u -> u.getEmail()) + .collect(Collectors.toList()); + + assertTrue(emails.size() == 1); + assertEquals(emails.get(0), user.getEmail()); + } + +} diff --git a/guest/core-java/pom.xml b/guest/core-java/pom.xml new file mode 100644 index 0000000000..548d5c663b --- /dev/null +++ b/guest/core-java/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + com.stackify + core-java + 0.0.1-SNAPSHOT + + + + junit + junit + 4.12 + + + org.apache.logging.log4j + log4j-core + ${log4j2.version} + + + + + + + maven-compiler-plugin + 3.5 + + 1.8 + 1.8 + + + + + + 2.8.2 + + \ No newline at end of file diff --git a/guest/core-java/src/main/java/com/stackify/optional/Address.java b/guest/core-java/src/main/java/com/stackify/optional/Address.java new file mode 100644 index 0000000000..f54c999920 --- /dev/null +++ b/guest/core-java/src/main/java/com/stackify/optional/Address.java @@ -0,0 +1,40 @@ +package com.stackify.optional; + +public class Address { + private String addressLine; + private String city; + private Country country; + + public Address(String addressLine, String city, Country country) { + super(); + this.addressLine = addressLine; + this.city = city; + this.country = country; + } + + public String getAddressLine() { + return addressLine; + } + + public void setAddressLine(String addressLine) { + this.addressLine = addressLine; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public Country getCountry() { + return country; + } + + public void setCountry(Country country) { + this.country = country; + } + + +} diff --git a/guest/core-java/src/main/java/com/stackify/optional/Country.java b/guest/core-java/src/main/java/com/stackify/optional/Country.java new file mode 100644 index 0000000000..bf97ef7b6d --- /dev/null +++ b/guest/core-java/src/main/java/com/stackify/optional/Country.java @@ -0,0 +1,29 @@ +package com.stackify.optional; + +public class Country { + private String name; + private String isocode; + + public Country(String name, String isocode) { + super(); + this.name = name; + this.isocode = isocode; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getIsocode() { + return isocode; + } + + public void setIsocode(String isocode) { + this.isocode = isocode; + } + +} diff --git a/guest/core-java/src/main/java/com/stackify/optional/User.java b/guest/core-java/src/main/java/com/stackify/optional/User.java new file mode 100644 index 0000000000..910f2605dd --- /dev/null +++ b/guest/core-java/src/main/java/com/stackify/optional/User.java @@ -0,0 +1,51 @@ +package com.stackify.optional; + +import java.util.Optional; + +public class User { + private String email; + private String password; + + private Address address; + + private String position; + + public User(String email, String password) { + super(); + this.email = email; + this.password = password; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public Optional getPosition() { + return Optional.ofNullable(position); + } + + public void setPosition(String position) { + this.position = position; + } + +} diff --git a/guest/core-java/src/main/java/com/stackify/optional/chaining/Address.java b/guest/core-java/src/main/java/com/stackify/optional/chaining/Address.java new file mode 100644 index 0000000000..1e10c67c39 --- /dev/null +++ b/guest/core-java/src/main/java/com/stackify/optional/chaining/Address.java @@ -0,0 +1,38 @@ +package com.stackify.optional.chaining; + +import java.util.Optional; + +public class Address { + private String addressLine; + private String city; + private Country country; + + public Address(String addressLine, String city) { + this.addressLine = addressLine; + this.city = city; + } + + public String getAddressLine() { + return addressLine; + } + + public void setAddressLine(String addressLine) { + this.addressLine = addressLine; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public Optional getCountry() { + return Optional.ofNullable(country); + } + + public void setCountry(Country country) { + this.country = country; + } +} diff --git a/guest/core-java/src/main/java/com/stackify/optional/chaining/Country.java b/guest/core-java/src/main/java/com/stackify/optional/chaining/Country.java new file mode 100644 index 0000000000..89e85a9b43 --- /dev/null +++ b/guest/core-java/src/main/java/com/stackify/optional/chaining/Country.java @@ -0,0 +1,28 @@ +package com.stackify.optional.chaining; + +public class Country { + private String name; + private String isocode; + + public Country(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getIsocode() { + return isocode; + } + + public void setIsocode(String isocode) { + this.isocode = isocode; + } + + +} \ No newline at end of file diff --git a/guest/core-java/src/main/java/com/stackify/optional/chaining/User.java b/guest/core-java/src/main/java/com/stackify/optional/chaining/User.java new file mode 100644 index 0000000000..07eb398abe --- /dev/null +++ b/guest/core-java/src/main/java/com/stackify/optional/chaining/User.java @@ -0,0 +1,50 @@ +package com.stackify.optional.chaining; + +import java.util.Optional; + +public class User { + private String email; + private String password; + + private Address address; + + private String position; + + public User(String email, String password) { + this.email = email; + this.password = password; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Optional
getAddress() { + return Optional.ofNullable(address); + } + + public void setAddress(Address address) { + this.address = address; + } + + public Optional getPosition() { + return Optional.ofNullable(position); + } + + public void setPosition(String position) { + this.position = position; + } + +} diff --git a/guest/core-java/src/main/resources/log4j2.xml b/guest/core-java/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..a67aae6aa6 --- /dev/null +++ b/guest/core-java/src/main/resources/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/guest/core-java/src/test/java/com/stackify/optional/OptionalTest.java b/guest/core-java/src/test/java/com/stackify/optional/OptionalTest.java new file mode 100644 index 0000000000..c6e6ddb15d --- /dev/null +++ b/guest/core-java/src/test/java/com/stackify/optional/OptionalTest.java @@ -0,0 +1,166 @@ +package com.stackify.optional; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Optional; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.Test; + +public class OptionalTest { + + private User user; + + private Logger logger = LogManager.getLogger(OptionalTest.class); + + @Test(expected = NullPointerException.class) + public void testNull() { + String isocode = user.getAddress().getCountry().getIsocode().toUpperCase(); + } + + @Test + public void test() { + + if (user != null) { + Address address = user.getAddress(); + if (address != null) { + Country country = address.getCountry(); + if (country != null) { + String isocode = country.getIsocode(); + if (isocode != null) { + isocode = isocode.toUpperCase(); + } + } + } + } + + } + + @Test(expected = NoSuchElementException.class) + public void whenCreateEmptyOptional_thenNull() { + Optional emptyOpt = Optional.empty(); + emptyOpt.get(); + } + + @Test(expected = NullPointerException.class) + public void whenCreateOfEmptyOptional_thenNullPointerException() { + Optional opt = Optional.of(user); + } + + @Test + public void whenCreateOfNullableOptional_thenOk() { + String name = "John"; + Optional opt = Optional.ofNullable(name); + assertEquals("John", opt.get()); + } + + @Test + public void whenCheckIsPresent_thenOk() { + user = new User("john@gmail.com", "1234"); + Optional opt = Optional.ofNullable(user); + assertTrue(opt.isPresent()); + + assertEquals(user.getEmail(), opt.get().getEmail()); + } + + @Test + public void whenCheckIfPresent_thenOk() { + user = new User("john@gmail.com", "1234"); + Optional opt = Optional.ofNullable(user); + assertTrue(opt.isPresent()); + + opt.ifPresent(u -> assertEquals(user.getEmail(), u.getEmail())); + } + + @Test + public void whenEmptyValue_thenReturnDefault() { + User user = null; + User user2 = new User("anna@gmail.com", "1234"); + User result = Optional.ofNullable(user).orElse(user2); + + assertEquals("anna@gmail.com", result.getEmail()); + } + + @Test + public void whenValueNotNull_thenIgnoreDefault() { + User user = new User("john@gmail.com", "1234"); + User user2 = new User("anna@gmail.com", "1234"); + User result = Optional.ofNullable(user).orElse(user2); + + assertEquals("john@gmail.com", result.getEmail()); + } + + @Test + public void whenSetDefaultOrElseGet_thenOk() { + User user = null; + User user2 = new User("anna@gmail.com", "1234"); + User result = Optional.ofNullable(user).orElseGet(() -> user2); + + assertEquals("anna@gmail.com", result.getEmail()); + } + + @Test + public void givenPresentValue_whenCompare_thenOk() { + User user = new User("john@gmail.com", "1234"); + logger.info("Using orElse"); + User result = Optional.ofNullable(user).orElse(createNewUser()); + logger.info("Using orElseGet"); + User result2 = Optional.ofNullable(user).orElseGet(() -> createNewUser()); + } + + private User createNewUser() { + logger.info("Creating New User"); + return new User("extra@gmail.com", "1234"); + } + + @Test + public void givenEmptyValue_whenCompare_thenOk() { + User user = null; + logger.info("Using orElse"); + User result = Optional.ofNullable(user).orElse(createNewUser()); + logger.info("Using orElseGet"); + User result2 = Optional.ofNullable(user).orElseGet(() -> createNewUser()); + } + + @Test(expected = IllegalArgumentException.class) + public void whenThrowException_thenOk() { + User result = Optional.ofNullable(user).orElseThrow(() -> new IllegalArgumentException()); + } + + @Test + public void whenMap_thenOk() { + user = new User("anna@gmail.com", "1234"); + String email = Optional.ofNullable(user).map(u -> u.getEmail()).orElse("default@gmail.com"); + assertEquals(email, user.getEmail()); + + } + + @Test + public void whenFlatMap_thenOk() { + user = new User("anna@gmail.com", "1234"); + user.setPosition("Developer"); + String position = Optional.ofNullable(user).flatMap(u -> u.getPosition()).orElse("default"); + assertEquals(position, user.getPosition().get()); + + } + + @Test + public void whenFilter_thenOk() { + user = new User("anna@gmail.com", "1234"); + Optional result = Optional.ofNullable(user).filter(u -> u.getEmail() != null && u.getEmail().contains("@")); + + assertTrue(result.isPresent()); + } + + @Test + public void whenStream_thenOk() { + List users = new ArrayList<>(); + User user = users.stream().findFirst().orElse(new User("default", "1234")); + assertEquals(user.getEmail(), "default"); + } + +} diff --git a/guest/core-java/src/test/java/com/stackify/optional/chaining/OptionalChainingTest.java b/guest/core-java/src/test/java/com/stackify/optional/chaining/OptionalChainingTest.java new file mode 100644 index 0000000000..660497c367 --- /dev/null +++ b/guest/core-java/src/test/java/com/stackify/optional/chaining/OptionalChainingTest.java @@ -0,0 +1,36 @@ +package com.stackify.optional.chaining; + +import static org.junit.Assert.*; + +import java.util.Optional; + +import org.junit.Test; + +public class OptionalChainingTest { + + @Test + public void whenChaining_thenOk() { + User user = new User("anna@gmail.com", "1234"); + + String result = Optional.ofNullable(user) + .flatMap(u -> u.getAddress()) + .flatMap(a -> a.getCountry()) + .map(c -> c.getIsocode()) + .orElse("default"); + + assertEquals(result, "default"); + } + + @Test + public void whenChainingWithMethodReferences_thenOk() { + User user = new User("anna@gmail.com", "1234"); + + String result = Optional.ofNullable(user) + .flatMap(User::getAddress) + .flatMap(Address::getCountry) + .map(Country::getIsocode) + .orElse("default"); + + assertEquals(result, "default"); + } +} diff --git a/hazelcast/pom.xml b/hazelcast/pom.xml index 5b467af655..2811bf8b12 100644 --- a/hazelcast/pom.xml +++ b/hazelcast/pom.xml @@ -22,7 +22,7 @@ com.hazelcast hazelcast-client - 3.7.2 + ${hazelcast.version} @@ -39,7 +39,7 @@ - 3.7.4 + 3.8.4 \ No newline at end of file diff --git a/hbase/pom.xml b/hbase/pom.xml index 3f5456777e..5fe47fcdc7 100644 --- a/hbase/pom.xml +++ b/hbase/pom.xml @@ -31,7 +31,7 @@ - 1.3.0 + 1.3.1 diff --git a/immutables/pom.xml b/immutables/pom.xml index 9b623c85e7..884ebc0c61 100644 --- a/immutables/pom.xml +++ b/immutables/pom.xml @@ -3,7 +3,6 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung immutables 1.0.0-SNAPSHOT @@ -34,7 +33,7 @@ - 2.3.10 + 2.5.6 3.6.1 0.9.6 diff --git a/javaxval/bean-validation/pom.xml b/javaxval/bean-validation/pom.xml new file mode 100644 index 0000000000..cdb5a814e2 --- /dev/null +++ b/javaxval/bean-validation/pom.xml @@ -0,0 +1,42 @@ + + 4.0.0 + + com.baeldung.beanvalidation + beanvalidation + 1.0 + jar + beanvalidation + http://maven.apache.org + + UTF-8 + + + + junit + junit + 4.12 + test + + + javax.validation + validation-api + 2.0.0.Final + + + org.hibernate + hibernate-validator + 6.0.2.Final + + + javax.el + javax.el-api + 3.0.0 + + + org.glassfish.web + javax.el + 2.2.4 + + + diff --git a/javaxval/bean-validation/src/main/java/com/baeldung/beanvalidation/application/Application.java b/javaxval/bean-validation/src/main/java/com/baeldung/beanvalidation/application/Application.java new file mode 100644 index 0000000000..7966b1046c --- /dev/null +++ b/javaxval/bean-validation/src/main/java/com/baeldung/beanvalidation/application/Application.java @@ -0,0 +1,17 @@ +package com.baeldung.beanvalidation.application; + +import javax.validation.Validation; +import javax.validation.Validator; +import com.baeldung.beanvalidation.model.User; + +public class Application { + + public static void main( String[] args ) { + Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); + User user = new User(); + user.setName("Mary"); + user.setEmail("no-email"); + user.setAge(36); + validator.validate(user).stream().forEach(violation -> System.out.println(violation.getMessage())); + } +} diff --git a/javaxval/bean-validation/src/main/java/com/baeldung/beanvalidation/container/IntegerContainer.java b/javaxval/bean-validation/src/main/java/com/baeldung/beanvalidation/container/IntegerContainer.java new file mode 100644 index 0000000000..a6006067cc --- /dev/null +++ b/javaxval/bean-validation/src/main/java/com/baeldung/beanvalidation/container/IntegerContainer.java @@ -0,0 +1,13 @@ +package com.baeldung.beanvalidation.container; + +import java.util.Optional; +import javax.validation.constraints.Positive; + +public class IntegerContainer { + + private Optional<@Positive(message = "Value must be a positive integer") Integer> container = Optional.empty(); + + public void addElement(int element) { + container = Optional.of(element); + } +} diff --git a/javaxval/bean-validation/src/main/java/com/baeldung/beanvalidation/container/StringContainer.java b/javaxval/bean-validation/src/main/java/com/baeldung/beanvalidation/container/StringContainer.java new file mode 100644 index 0000000000..eced996263 --- /dev/null +++ b/javaxval/bean-validation/src/main/java/com/baeldung/beanvalidation/container/StringContainer.java @@ -0,0 +1,14 @@ +package com.baeldung.beanvalidation.container; + +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.NotNull; + +public class StringContainer { + + private List<@NotNull String> container = new ArrayList<>(); + + public void addElement(String element) { + container.add(element); + } +} diff --git a/javaxval/bean-validation/src/main/java/com/baeldung/beanvalidation/model/User.java b/javaxval/bean-validation/src/main/java/com/baeldung/beanvalidation/model/User.java new file mode 100644 index 0000000000..2a019c37b3 --- /dev/null +++ b/javaxval/bean-validation/src/main/java/com/baeldung/beanvalidation/model/User.java @@ -0,0 +1,48 @@ +package com.baeldung.beanvalidation.model; + +import java.io.Serializable; +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import org.hibernate.validator.constraints.Email; + +public class User implements Serializable { + + private static final long serialVersionUID = 1L; + + @NotNull(message = "Name cannot be null") + @Size(min = 2, max = 32, message = "Name must be between 2 and 32 characters") + private String name; + + @Email(message = "Email must be a well-formed email address") + private String email; + + @Min(value = 1, message = "Age must not be lesser than 1") + @Max(value = 99, message = "Age must not be greater than 99") + private int age; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } +} diff --git a/javaxval/bean-validation/src/main/java/com/baeldung/beanvalidation/service/EntityService.java b/javaxval/bean-validation/src/main/java/com/baeldung/beanvalidation/service/EntityService.java new file mode 100644 index 0000000000..5362e7fbda --- /dev/null +++ b/javaxval/bean-validation/src/main/java/com/baeldung/beanvalidation/service/EntityService.java @@ -0,0 +1,8 @@ +package com.baeldung.beanvalidation.service; + +public interface EntityService { + + public String toString(); + + public void processEntity(); +} diff --git a/javaxval/bean-validation/src/main/java/com/baeldung/beanvalidation/service/UserService.java b/javaxval/bean-validation/src/main/java/com/baeldung/beanvalidation/service/UserService.java new file mode 100644 index 0000000000..7aae5b3077 --- /dev/null +++ b/javaxval/bean-validation/src/main/java/com/baeldung/beanvalidation/service/UserService.java @@ -0,0 +1,45 @@ +package com.baeldung.beanvalidation.service; + +import java.io.Serializable; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import com.baeldung.beanvalidation.model.User; + +public class UserService implements EntityService, Serializable { + + private static final long serialVersionUID = 1L; + + @Valid + private User user; + + @NotNull(message = "FileName cannot be null") + @Size(min = 5, max = 10, message = "FileName must be between 5 and 10 characters") + private String fileName; + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + @Override + public void processEntity() { + // process the user here + } + + @Override + public String toString() { + return "UserService [user=" + user + ", fileName=" + fileName + "]"; + } +} diff --git a/javaxval/bean-validation/src/test/java/com/baeldung/beanvalidation/ValidationTest.java b/javaxval/bean-validation/src/test/java/com/baeldung/beanvalidation/ValidationTest.java new file mode 100644 index 0000000000..1d36cf21f0 --- /dev/null +++ b/javaxval/bean-validation/src/test/java/com/baeldung/beanvalidation/ValidationTest.java @@ -0,0 +1,134 @@ +package com.baeldung.beanvalidation; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import com.baeldung.beanvalidation.container.IntegerContainer; +import com.baeldung.beanvalidation.container.StringContainer; +import com.baeldung.beanvalidation.model.User; +import com.baeldung.beanvalidation.service.UserService; +import java.util.Set; +import java.util.stream.Collectors; +import static org.junit.Assert.*; + +public class ValidationTest { + + private static Validator validator; + private static User user; + + @BeforeClass + public static void setUpHibernateValidatorInstance() { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @BeforeClass + public static void setUpUserInstance() { + user = new User(); + } + + @AfterClass + public static void tearDownHibernateValidatorInstance() { + validator = null; + } + + @AfterClass + public static void tearDownUserInstance() { + user = null; + } + + @Test + public void givenNullName_whenValidated_thenMessageDescriptorForName() { + user.setName(null); + user.setEmail("mary@domain.com"); + user.setAge(36); + assertEquals("Name cannot be null", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining())); + } + + @Test + public void givenInvalidEmail_whenValidated_thenMessageDescriptorforEmail() { + user.setName("Mary"); + user.setEmail("no-email"); + user.setAge(36); + assertEquals("Email must be a well-formed email address", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining())); + } + + @Test + public void givenAgeLesserThanLowerBound_whenValidated_thenMessageDescriptorforAge() { + user.setName("Mary"); + user.setEmail("mary@domain.com"); + user.setAge(0); + assertEquals("Age must not be lesser than 1", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining())); + } + + @Test + public void givenAgeGreaterThanUpperBound_whenValidated_thenMessageDescriptorforAge() { + user.setName("Mary"); + user.setEmail("mary@domain.com"); + user.setAge(100); + assertEquals("Age must not be greater than 99", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining())); + } + + @Test + public void givenNullFileName_whenValidated_thenMessageDescriptorforFileName() { + user.setName("Mary"); + user.setEmail("mary@domain.com"); + user.setAge(36); + UserService userService = new UserService(); + userService.setFileName(null); + userService.setUser(user); + assertEquals("FileName cannot be null", validator.validate(userService).stream().map(violation -> violation.getMessage()).collect(Collectors.joining())); + } + + @Test + public void givenFileNameShortherThanLowerBound_whenValidated_thenMessageDescriptorforFileName() { + user.setName("Mary"); + user.setEmail("mary@domain.com"); + user.setAge(36); + UserService userService = new UserService(); + userService.setFileName(""); + userService.setUser(user); + assertEquals("FileName must be between 5 and 10 characters", validator.validate(userService).stream().map(violation -> violation.getMessage()).collect(Collectors.joining())); + } + + @Test + public void givenFileNameLongerThanUpperBound_whenValidated_thenMessageDescriptorforFileName() { + user.setName("Mary"); + user.setEmail("mary@domain.com"); + user.setAge(36); + UserService userService = new UserService(); + userService.setFileName("waytoolongfilename"); + userService.setUser(user); + assertEquals("FileName must be between 5 and 10 characters", validator.validate(userService).stream().map(violation -> violation.getMessage()).collect(Collectors.joining())); + } + + @Test + public void givenNullUserAndNullFileName_whenValidated_thenTwoConstraintViolations() { + user.setName(null); + user.setEmail("mary@domain.com"); + user.setAge(36); + UserService userService = new UserService(); + userService.setFileName(null); + userService.setUser(user); + Set> constraintViolations = validator.validate(userService); + assertEquals(2, constraintViolations.size()); + } + + @Test + public void givenNullElement_whenValidated_thenOneConstraintViolation() { + StringContainer container = new StringContainer(); + container.addElement(null); + Set> constraintViolations = validator.validate(container); + assertEquals(1, constraintViolations.size()); + } + + @Test + public void givenNegativeInteger_whenValidated_thenOneConstraintViolation() { + IntegerContainer container = new IntegerContainer(); + container.addElement(-1); + Set> constraintViolations = validator.validate(container); + assertEquals(1, constraintViolations.size()); + } +} diff --git a/jee7/README.md b/jee7/README.md index a2493e561b..08a180cfa3 100644 --- a/jee7/README.md +++ b/jee7/README.md @@ -5,3 +5,4 @@ - [Introduction to JAX-WS](http://www.baeldung.com/jax-ws) - [A Guide to Java EE Web-Related Annotations](http://www.baeldung.com/javaee-web-annotations) - [Introduction to Testing with Arquillian](http://www.baeldung.com/arquillian) +- [Securing Java EE with Spring Security](http://www.baeldung.com/java-ee-spring-security) diff --git a/jee7/src/test/java/com/baeldung/arquillan/ArquillianTest.java b/jee7/src/test/java/com/baeldung/arquillan/ArquillianLiveTest.java similarity index 98% rename from jee7/src/test/java/com/baeldung/arquillan/ArquillianTest.java rename to jee7/src/test/java/com/baeldung/arquillan/ArquillianLiveTest.java index 5219f221ca..9807162606 100644 --- a/jee7/src/test/java/com/baeldung/arquillan/ArquillianTest.java +++ b/jee7/src/test/java/com/baeldung/arquillan/ArquillianLiveTest.java @@ -22,7 +22,7 @@ import com.baeldung.arquillian.Component; import com.baeldung.arquillian.ConvertToLowerCase; @RunWith(Arquillian.class) -public class ArquillianTest { +public class ArquillianLiveTest { @Deployment public static JavaArchive createDeployment() { diff --git a/json-path/pom.xml b/json-path/pom.xml index 8384ba68ed..0f8ff3bd31 100644 --- a/json-path/pom.xml +++ b/json-path/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung json-path 0.0.1-SNAPSHOT json-path diff --git a/junit5/README.md b/junit5/README.md index 49cd8e61a4..a3bb8fc1be 100644 --- a/junit5/README.md +++ b/junit5/README.md @@ -5,3 +5,5 @@ - [A Guide to @RepeatedTest in Junit 5](http://www.baeldung.com/junit-5-repeated-test) - [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests) - [A Guied to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions) +- [Inject Parameters into JUnit Jupiter Unit Tests](http://www.baeldung.com/junit-5-parameters) + diff --git a/kotlin/README.md b/kotlin/README.md index 91933e94dc..720187dc44 100644 --- a/kotlin/README.md +++ b/kotlin/README.md @@ -13,4 +13,7 @@ - [Overview of Kotlin Collections API](http://www.baeldung.com/kotlin-collections-api) - [Converting a List to Map in Kotlin](http://www.baeldung.com/kotlin-list-to-map) - [Data Classes in Kotlin](http://www.baeldung.com/kotlin-data-classes) +- [Delegated Properties in Kotlin](http://www.baeldung.com/kotlin-delegated-properties) +- [Sealed Classes in Kotlin](http://www.baeldung.com/kotlin-sealed-classes) + diff --git a/kotlin/src/main/kotlin/com/baeldung/kotlin/JvmSample.kt b/kotlin/src/main/kotlin/com/baeldung/kotlin/JvmSample.kt new file mode 100644 index 0000000000..610d5282b2 --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/kotlin/JvmSample.kt @@ -0,0 +1,12 @@ +package com.baeldung.kotlin + +class JvmSample(text:String) { + @JvmField + val sampleText:String = text +} + +class CompanionSample { + companion object { + @JvmField val MAX_LIMIT = 20 + } +} \ No newline at end of file diff --git a/kotlin/src/test/kotlin/com/baeldung/kotlin/JvmSampleTest.kt b/kotlin/src/test/kotlin/com/baeldung/kotlin/JvmSampleTest.kt new file mode 100644 index 0000000000..abe6edec92 --- /dev/null +++ b/kotlin/src/test/kotlin/com/baeldung/kotlin/JvmSampleTest.kt @@ -0,0 +1,26 @@ +package com.baeldung.kotlin + +import org.junit.Before +import org.junit.Test +import kotlin.test.assertTrue + +class JvmSampleTest { + + var sample = "" + + @Before + fun setUp() { + sample = JvmSample("Hello!").sampleText + } + + @Test + fun givenField_whenCheckValue_thenMatchesValue() { + assertTrue(sample == "Hello!") + } + + @Test + fun givenStaticVariable_whenCheckValue_thenMatchesValue() { + // Sample when is treated as a static variable + assertTrue(CompanionSample.MAX_LIMIT == 20) + } +} \ No newline at end of file diff --git a/libraries-data/README.md b/libraries-data/README.md new file mode 100644 index 0000000000..ca70c61146 --- /dev/null +++ b/libraries-data/README.md @@ -0,0 +1,2 @@ +### Relevant articles +- [Introduction to Reladomo](http://www.baeldung.com/reladomo) diff --git a/libraries/README.md b/libraries/README.md index ed6d214c7a..74766fb828 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -27,11 +27,20 @@ - [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils) - [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing) - [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog) -- [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph) +- [Introduction to Neuroph](http://www.baeldung.com/neuroph) - [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue) - [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss) - [Introduction to NoException](http://www.baeldung.com/intrduction-to-noexception) - +- [Introduction to PCollections](http://www.baeldung.com/java-pcollections) +- [Introduction to Hoverfly in Java](http://www.baeldung.com/hoverfly) +- [Apache Commons Chain](http://www.baeldung.com/apache-commons-chain) +- [Introduction to Eclipse Collections](http://www.baeldung.com/eclipse-collections) +- [DistinctBy in Java Stream API](http://www.baeldung.com/java-streams-distinct-by) +- [Introduction to Apache Commons CSV](http://www.baeldung.com/apache-commons-csv) +- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference) +- [Introduction to NoException](http://www.baeldung.com/no-exception) +- [Introduction to FunctionalJava](http://www.baeldung.com/functional-java) +- [Apache Commons IO](http://www.baeldung.com/apache-commons-io) The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/libraries/pom.xml b/libraries/pom.xml index 6d1098246e..77e7c2634a 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -105,7 +105,6 @@ - @@ -136,6 +135,11 @@ commons-text ${commons-text.version} + + tec.units + unit-ri + 1.0.3 + org.apache.commons commons-collections4 @@ -190,7 +194,7 @@ io.specto hoverfly-java - 0.8.0 + 0.8.1 org.apache.httpcomponents @@ -295,22 +299,22 @@ org.datanucleus javax.jdo - 3.2.0-m6 + 3.2.0-m7 org.datanucleus datanucleus-core - 5.1.0-m1 + 5.1.1 org.datanucleus datanucleus-api-jdo - 5.1.0-m1 + 5.1.1 org.datanucleus datanucleus-rdbms - 5.1.0-m1 + 5.1.1 org.datanucleus @@ -364,7 +368,7 @@ com.zaxxer HikariCP - 2.6.1 + 2.6.3 compile @@ -483,21 +487,79 @@ vavr ${vavr.version} - - org.geotools - gt-shapefile - ${geotools.version} + + + + com.squareup.retrofit2 + retrofit + ${retrofit.version} - org.geotools - gt-epsg-hsql - ${geotools.version} + com.squareup.retrofit2 + converter-gson + ${retrofit.version} - org.geotools - gt-swing - ${geotools.version} + com.squareup.retrofit2 + adapter-rxjava + ${retrofit.version} + + + com.squareup.okhttp3 + logging-interceptor + 3.9.0 + + com.darwinsys + hirondelle-date4j + RELEASE + test + + + joda-time + joda-time + ${joda-time.version} + + + com.darwinsys + hirondelle-date4j + ${hirondelle-date4j.version} + + + com.haulmont.yarg + yarg + 2.0.4 + + + net.engio + mbassador + 1.3.1 + + + org.jdeferred + jdeferred-core + 1.2.6 + + + com.codepoetics + protonpack + ${protonpack.version} + + + org.functionaljava + functionaljava + 4.7 + + + javax.cache + cache-api + ${cache.version} + + + com.hazelcast + hazelcast + ${hazelcast.version} + @@ -505,24 +567,19 @@ Java.net repository http://download.java.net/maven/2 - - osgeo - Open Source Geospatial Foundation Repository - http://download.osgeo.org/webdav/geotools/ - - true + false - opengeo - OpenGeo Maven Repository - http://repo.opengeo.org + bintray-cuba-platform-main + bintray + http://dl.bintray.com/cuba-platform/main 0.7.0 3.2.4 - 3.5 + 3.6 1.1 1.9.3 1.2 @@ -549,7 +606,7 @@ 1.1.3-rc.5 1.4.0 1.1.0 - 4.1.10.Final + 4.1.15.Final 4.1 4.12 0.10 @@ -563,6 +620,14 @@ 8.2.0 0.6.5 0.9.0 - 15.2 + 2.9.9 + 1.5.1 + 2.3.0 + 2.9.9 + 1.5.1 + 1.14 + 1.0.3 + 1.0.0 + 3.8.4 \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/io/FileMonitor.java b/libraries/src/main/java/com/baeldung/commons/io/FileMonitor.java new file mode 100644 index 0000000000..d42323a5df --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/io/FileMonitor.java @@ -0,0 +1,43 @@ +package com.baeldung.commons.io; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.monitor.FileAlterationListener; +import org.apache.commons.io.monitor.FileAlterationListenerAdaptor; +import org.apache.commons.io.monitor.FileAlterationMonitor; +import org.apache.commons.io.monitor.FileAlterationObserver; + +import java.io.File; + +public class FileMonitor { + + public static void main(String[] args) throws Exception { + File folder = FileUtils.getTempDirectory(); + startFileMonitor(folder); + } + + /** + * @param folder + * @throws Exception + */ + public static void startFileMonitor(File folder) throws Exception { + FileAlterationObserver observer = new FileAlterationObserver(folder); + FileAlterationMonitor monitor = new FileAlterationMonitor(5000); + + FileAlterationListener fal = new FileAlterationListenerAdaptor() { + + @Override + public void onFileCreate(File file) { + // on create action + } + + @Override + public void onFileDelete(File file) { + // on delete action + } + }; + + observer.addListener(fal); + monitor.addObserver(observer); + monitor.start(); + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java b/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java new file mode 100644 index 0000000000..c64f7e7511 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java @@ -0,0 +1,60 @@ +package com.baeldung.commons.lang3; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; + +public class BuilderMethods { + + private final int intValue; + private final String strSample; + + public BuilderMethods(final int newId, final String newName) { + this.intValue = newId; + this.strSample = newName; + } + + public int getId() { + return this.intValue; + } + + public String getName() { + return this.strSample; + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(this.intValue) + .append(this.strSample) + .toHashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof BuilderMethods == false) { + return false; + } + if (this == obj) { + return true; + } + final BuilderMethods otherObject = (BuilderMethods) obj; + + return new EqualsBuilder().append(this.intValue, otherObject.intValue) + .append(this.strSample, otherObject.strSample) + .isEquals(); + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("INTVALUE", this.intValue) + .append("STRINGVALUE", this.strSample) + .toString(); + } + + public static void main(final String[] arguments) { + final BuilderMethods simple1 = new BuilderMethods(1, "The First One"); + System.out.println(simple1.getName()); + System.out.println(simple1.hashCode()); + System.out.println(simple1.toString()); + } +} diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java b/libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java new file mode 100644 index 0000000000..56a49d2659 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java @@ -0,0 +1,11 @@ +package com.baeldung.commons.lang3; + +import org.apache.commons.lang3.concurrent.LazyInitializer; + +public class SampleLazyInitializer extends LazyInitializer { + + @Override + protected SampleObject initialize() { + return new SampleObject(); + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java b/libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java new file mode 100644 index 0000000000..0e61176732 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java @@ -0,0 +1,7 @@ +package com.baeldung.commons.lang3; + +public class SampleObject { + + //Ignored + +} diff --git a/libraries/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java b/libraries/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java new file mode 100644 index 0000000000..ebf0fa4d2d --- /dev/null +++ b/libraries/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java @@ -0,0 +1,47 @@ +package com.baeldung.fj; + +import fj.F; +import fj.F1Functions; +import fj.Unit; +import fj.data.IO; +import fj.data.IOFunctions; + +public class FunctionalJavaIOMain { + + public static IO printLetters(final String s) { + return () -> { + for (int i = 0; i < s.length(); i++) { + System.out.println(s.charAt(i)); + } + return Unit.unit(); + }; + } + + public static void main(String[] args) { + + F> printLetters = i -> printLetters(i); + + IO lowerCase = IOFunctions + .stdoutPrintln("What's your first Name ?"); + + IO input = IOFunctions.stdoutPrint("First Name: "); + + IO userInput = IOFunctions.append(lowerCase, input); + + IO readInput = IOFunctions.stdinReadLine(); + + F toUpperCase = i -> i.toUpperCase(); + + F> transformInput = F1Functions + ., String> o(printLetters).f(toUpperCase); + + IO readAndPrintResult = IOFunctions.bind(readInput, + transformInput); + + IO program = IOFunctions.bind(userInput, + nothing -> readAndPrintResult); + + IOFunctions.toSafe(program).run(); + + } +} diff --git a/libraries/src/main/java/com/baeldung/fj/FunctionalJavaMain.java b/libraries/src/main/java/com/baeldung/fj/FunctionalJavaMain.java new file mode 100644 index 0000000000..e4d731454d --- /dev/null +++ b/libraries/src/main/java/com/baeldung/fj/FunctionalJavaMain.java @@ -0,0 +1,48 @@ +package com.baeldung.fj; + +import fj.F; +import fj.Show; +import fj.data.Array; +import fj.data.List; +import fj.data.Option; +import fj.function.Characters; +import fj.function.Integers; + +public class FunctionalJavaMain { + + public static final F isEven = i -> i % 2 == 0; + + public static void main(String[] args) { + + List fList = List.list(3, 4, 5, 6); + List evenList = fList.map(isEven); + Show.listShow(Show.booleanShow).println(evenList); + + fList = fList.map(i -> i + 1); + Show.listShow(Show.intShow).println(fList); + + Array a = Array.array(17, 44, 67, 2, 22, 80, 1, 27); + Array b = a.filter(Integers.even); + Show.arrayShow(Show.intShow).println(b); + + Array array = Array.array("Welcome", "To", "baeldung"); + Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase)); + System.out.println(isExist); + + Array intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27); + int sum = intArray.foldLeft(Integers.add, 0); + System.out.println(sum); + + Option n1 = Option.some(1); + Option n2 = Option.some(2); + + F> f1 = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none(); + + Option result1 = n1.bind(f1); + Option result2 = n2.bind(f1); + + Show.optionShow(Show.intShow).println(result1); + Show.optionShow(Show.intShow).println(result2); + } + +} diff --git a/libraries/src/main/java/com/baeldung/jcache/SimpleCacheEntryListener.java b/libraries/src/main/java/com/baeldung/jcache/SimpleCacheEntryListener.java new file mode 100644 index 0000000000..b58182eab0 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jcache/SimpleCacheEntryListener.java @@ -0,0 +1,34 @@ +package com.baeldung.jcache; + +import java.io.Serializable; + +import javax.cache.event.CacheEntryCreatedListener; +import javax.cache.event.CacheEntryEvent; +import javax.cache.event.CacheEntryListenerException; +import javax.cache.event.CacheEntryUpdatedListener; + +public class SimpleCacheEntryListener implements CacheEntryCreatedListener, CacheEntryUpdatedListener, Serializable { + + /** + * + */ + private static final long serialVersionUID = -712657810462878763L; + private boolean updated; + private boolean created; + + public boolean getUpdated() { + return this.updated; + } + + public boolean getCreated() { + return this.created; + } + + public void onUpdated(Iterable> events) throws CacheEntryListenerException { + this.updated = true; + } + + public void onCreated(Iterable> events) throws CacheEntryListenerException { + this.created = true; + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/jcache/SimpleCacheLoader.java b/libraries/src/main/java/com/baeldung/jcache/SimpleCacheLoader.java new file mode 100644 index 0000000000..77ab8fb645 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jcache/SimpleCacheLoader.java @@ -0,0 +1,24 @@ +package com.baeldung.jcache; + +import java.util.HashMap; +import java.util.Map; + +import javax.cache.integration.CacheLoader; +import javax.cache.integration.CacheLoaderException; + +public class SimpleCacheLoader implements CacheLoader { + + @Override + public String load(Integer key) throws CacheLoaderException { + return "fromCache" + key; + } + + @Override + public Map loadAll(Iterable keys) throws CacheLoaderException { + Map data = new HashMap<>(); + for (int key : keys) { + data.put(key, load(key)); + } + return data; + } +} diff --git a/libraries/src/main/java/com/baeldung/jcache/SimpleEntryProcessor.java b/libraries/src/main/java/com/baeldung/jcache/SimpleEntryProcessor.java new file mode 100644 index 0000000000..bb585807fb --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jcache/SimpleEntryProcessor.java @@ -0,0 +1,25 @@ +package com.baeldung.jcache; + +import java.io.Serializable; + +import javax.cache.processor.EntryProcessor; +import javax.cache.processor.EntryProcessorException; +import javax.cache.processor.MutableEntry; + +public class SimpleEntryProcessor implements EntryProcessor, Serializable { + + /** + * + */ + private static final long serialVersionUID = -5616476363722945132L; + + public String process(MutableEntry entry, Object... args) throws EntryProcessorException { + + if (entry.exists()) { + String current = entry.getValue(); + entry.setValue(current + " - modified"); + return current; + } + return null; + } +} diff --git a/libraries/src/main/java/com/baeldung/jdeffered/FilterDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/FilterDemo.java new file mode 100644 index 0000000000..ec2c52d3b5 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jdeffered/FilterDemo.java @@ -0,0 +1,24 @@ +package com.baeldung.jdeffered; + +import org.jdeferred.Deferred; +import org.jdeferred.Promise; +import org.jdeferred.impl.DeferredObject; + +class FilterDemo { + + private static String modifiedMsg; + + static String filter(String msg) { + + Deferred d = new DeferredObject<>(); + Promise p = d.promise(); + Promise filtered = p.then((result) -> { + modifiedMsg = "Hello " + result; + }); + + filtered.done(r -> System.out.println("filtering done")); + + d.resolve(msg); + return modifiedMsg; + } +} diff --git a/libraries/src/main/java/com/baeldung/jdeffered/PipeDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/PipeDemo.java new file mode 100644 index 0000000000..95250cff76 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jdeffered/PipeDemo.java @@ -0,0 +1,35 @@ +package com.baeldung.jdeffered; + +import org.jdeferred.Deferred; +import org.jdeferred.DonePipe; +import org.jdeferred.Promise; +import org.jdeferred.impl.DeferredObject; + +class PipeDemo { + + public enum Result { + SUCCESS, FAILURE + }; + + private static Result status; + + static Result validate(int num) { + Deferred d = new DeferredObject<>(); + Promise p = d.promise(); + + p.then((DonePipe) result -> { + if (result < 90) { + return new DeferredObject() + .resolve(result); + } else { + return new DeferredObject() + .reject(new Exception("Unacceptable value")); + } + }).done(r -> status = Result.SUCCESS) + .fail(r -> status = Result.FAILURE); + + d.resolve(num); + + return status; + } +} diff --git a/libraries/src/main/java/com/baeldung/jdeffered/PromiseDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/PromiseDemo.java new file mode 100644 index 0000000000..2a9f83dc35 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jdeffered/PromiseDemo.java @@ -0,0 +1,24 @@ +package com.baeldung.jdeffered; + +import org.jdeferred.Deferred; +import org.jdeferred.Promise; +import org.jdeferred.impl.DeferredObject; + +class PromiseDemo { + + static void startJob(String jobName) { + + Deferred deferred = new DeferredObject<>(); + Promise promise = deferred.promise(); + + promise.done(result -> System.out.println("Job done")) + .fail(rejection -> System.out.println("Job fail")) + .progress(progress -> System.out.println("Job is in progress")) + .always((state, result, rejection) -> System.out.println("Job execution started")); + + deferred.resolve(jobName); + // deferred.notify(""); + // deferred.reject("oops"); + } + +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/jdeffered/ThreadSafeDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/ThreadSafeDemo.java new file mode 100644 index 0000000000..22fd51ed92 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jdeffered/ThreadSafeDemo.java @@ -0,0 +1,38 @@ +package com.baeldung.jdeffered; + +import org.jdeferred.Deferred; +import org.jdeferred.DeferredManager; +import org.jdeferred.Promise; +import org.jdeferred.impl.DefaultDeferredManager; +import org.jdeferred.impl.DeferredObject; + +public class ThreadSafeDemo { + + public static void task() { + DeferredManager dm = new DefaultDeferredManager(); + Deferred deferred = new DeferredObject<>(); + Promise p1 = deferred.promise(); + Promise p = dm.when(p1) + .done(r -> System.out.println("done")) + .fail(r -> System.out.println("fail")); + + synchronized (p) { + while (p.isPending()) { + try { + p.wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + try { + p.waitSafely(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + deferred.resolve("Hello Baeldung"); + } + +} diff --git a/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerDemo.java new file mode 100644 index 0000000000..d37a62e309 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerDemo.java @@ -0,0 +1,22 @@ +package com.baeldung.jdeffered.manager; + +import org.jdeferred.Deferred; +import org.jdeferred.DeferredManager; +import org.jdeferred.Promise; +import org.jdeferred.impl.DefaultDeferredManager; +import org.jdeferred.impl.DeferredObject; + +class DeferredManagerDemo { + + public static void initiate() { + Deferred deferred = new DeferredObject<>(); + DeferredManager dm = new DefaultDeferredManager(); + Promise p1 = deferred.promise(), p2 = deferred.promise(), p3 = deferred.promise(); + dm.when(p1, p2, p3).done((result) -> { + System.out.println("done"); + }).fail((result) -> { + System.out.println("fail"); + }); + deferred.resolve("Hello Baeldung"); + } +} diff --git a/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerWithExecutorDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerWithExecutorDemo.java new file mode 100644 index 0000000000..2abe9bc10f --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerWithExecutorDemo.java @@ -0,0 +1,24 @@ +package com.baeldung.jdeffered.manager; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.jdeferred.Deferred; +import org.jdeferred.DeferredManager; +import org.jdeferred.Promise; +import org.jdeferred.impl.DefaultDeferredManager; +import org.jdeferred.impl.DeferredObject; + +class DeferredManagerWithExecutorDemo { + + public static void initiate() { + ExecutorService executor = Executors.newFixedThreadPool(10); + Deferred deferred = new DeferredObject<>(); + DeferredManager dm = new DefaultDeferredManager(executor); + Promise p1 = deferred.promise(), p2 = deferred.promise(), p3 = deferred.promise(); + dm.when(p1, p2, p3) + .done(r -> System.out.println("done")) + .fail(r -> System.out.println("fail")); + deferred.resolve("done"); + } +} diff --git a/libraries/src/main/java/com/baeldung/jdeffered/manager/SimpleDeferredManagerDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/manager/SimpleDeferredManagerDemo.java new file mode 100644 index 0000000000..dc2e82495f --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jdeffered/manager/SimpleDeferredManagerDemo.java @@ -0,0 +1,14 @@ +package com.baeldung.jdeffered.manager; + +import org.jdeferred.DeferredManager; +import org.jdeferred.impl.DefaultDeferredManager; + +class SimpleDeferredManagerDemo { + + public static void initiate() { + DeferredManager dm = new DefaultDeferredManager(); + dm.when(() -> 1) + .done(r -> System.out.println("done")) + .fail(Throwable::printStackTrace); + } +} diff --git a/libraries/src/main/java/com/baeldung/mbassador/AckMessage.java b/libraries/src/main/java/com/baeldung/mbassador/AckMessage.java new file mode 100644 index 0000000000..a42b24b605 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/mbassador/AckMessage.java @@ -0,0 +1,5 @@ +package com.baeldung.mbassador; + +public class AckMessage extends Message { + +} diff --git a/libraries/src/main/java/com/baeldung/mbassador/Message.java b/libraries/src/main/java/com/baeldung/mbassador/Message.java new file mode 100644 index 0000000000..bb773dd1a0 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/mbassador/Message.java @@ -0,0 +1,5 @@ +package com.baeldung.mbassador; + +public class Message { + +} diff --git a/libraries/src/main/java/com/baeldung/mbassador/RejectMessage.java b/libraries/src/main/java/com/baeldung/mbassador/RejectMessage.java new file mode 100644 index 0000000000..f569002edd --- /dev/null +++ b/libraries/src/main/java/com/baeldung/mbassador/RejectMessage.java @@ -0,0 +1,15 @@ +package com.baeldung.mbassador; + +public class RejectMessage extends Message { + + int code; + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + +} diff --git a/libraries/src/main/java/com/baeldung/measurement/WaterTank.java b/libraries/src/main/java/com/baeldung/measurement/WaterTank.java new file mode 100644 index 0000000000..f3675ae689 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/measurement/WaterTank.java @@ -0,0 +1,26 @@ +package com.baeldung.measurement; + +import javax.measure.Quantity; +import javax.measure.quantity.Volume; + +public class WaterTank { + + private Quantity capacityMeasure; + private double capacityDouble; + + public void setCapacityMeasure(Quantity capacityMeasure) { + this.capacityMeasure = capacityMeasure; + } + + public void setCapacityDouble(double capacityDouble) { + this.capacityDouble = capacityDouble; + } + + public Quantity getCapacityMeasure() { + return capacityMeasure; + } + + public double getCapacityDouble() { + return capacityDouble; + } +} diff --git a/libraries/src/main/java/com/baeldung/protonpack/CollectorUtilsExample.java b/libraries/src/main/java/com/baeldung/protonpack/CollectorUtilsExample.java new file mode 100644 index 0000000000..016178083a --- /dev/null +++ b/libraries/src/main/java/com/baeldung/protonpack/CollectorUtilsExample.java @@ -0,0 +1,18 @@ +package com.baeldung.protonpack; + +import java.util.Optional; +import java.util.stream.Stream; + +import static com.codepoetics.protonpack.collectors.CollectorUtils.maxBy; +import static com.codepoetics.protonpack.collectors.CollectorUtils.minBy; + +public class CollectorUtilsExample { + + public void minMaxProjectionCollector() { + Stream integerStream = Stream.of("a", "bb", "ccc", "1"); + + Optional max = integerStream.collect(maxBy(String::length)); + Optional min = integerStream.collect(minBy(String::length)); + + } +} diff --git a/libraries/src/main/java/com/baeldung/protonpack/StreamUtilsExample.java b/libraries/src/main/java/com/baeldung/protonpack/StreamUtilsExample.java new file mode 100644 index 0000000000..eead34af71 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/protonpack/StreamUtilsExample.java @@ -0,0 +1,107 @@ +package com.baeldung.protonpack; + +import com.codepoetics.protonpack.Indexed; +import com.codepoetics.protonpack.StreamUtils; +import com.codepoetics.protonpack.selectors.Selectors; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.LongStream; +import java.util.stream.Stream; + +import static java.util.stream.Collectors.toList; + +public class StreamUtilsExample { + + public void createInfiniteIndex() { + LongStream indices = StreamUtils.indices(); + } + + public void zipAStreamWithIndex() { + Stream source = Stream.of("Foo", "Bar", "Baz"); + List> zipped = StreamUtils + .zipWithIndex(source) + .collect(Collectors.toList()); + } + + public void zipAPairOfStreams() { + Stream streamA = Stream.of("A", "B", "C"); + Stream streamB = Stream.of("Apple", "Banana", "Carrot"); + + List zipped = StreamUtils + .zip(streamA, streamB, (a, b) -> a + " is for " + b) + .collect(Collectors.toList()); + } + + public void zipThreeStreams() { + Stream streamA = Stream.of("A", "B", "C"); + Stream streamB = Stream.of("aggravating", "banausic", "complaisant"); + Stream streamC = Stream.of("Apple", "Banana", "Carrot"); + + List zipped = StreamUtils + .zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c) + .collect(Collectors.toList()); + } + + public void mergeThreeStreams() { + Stream streamA = Stream.of("A", "B", "C"); + Stream streamB = Stream.of("apple", "banana", "carrot", "date"); + Stream streamC = Stream.of("fritter", "split", "cake", "roll", "pastry"); + + Stream> merged = StreamUtils.mergeToList(streamA, streamB, streamC); + } + + public void interleavingStreamsUsingRoundRobin() { + Stream streamA = Stream.of("Peter", "Paul", "Mary"); + Stream streamB = Stream.of("A", "B", "C", "D", "E"); + Stream streamC = Stream.of("foo", "bar", "baz", "xyzzy"); + + Stream interleaved = StreamUtils.interleave(Selectors.roundRobin(), streamA, streamB, streamC); + } + + public void takeWhileAndTakeUntilStream() { + Stream infiniteInts = Stream.iterate(0, i -> i + 1); + Stream finiteIntsWhileLessThan10 = StreamUtils.takeWhile(infiniteInts, i -> i < 10); + Stream finiteIntsUntilGreaterThan10 = StreamUtils.takeUntil(infiniteInts, i -> i > 10); + } + + public void skipWhileAndSkipUntilStream() { + Stream ints = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + Stream skippedWhileConditionMet = StreamUtils.skipWhile(ints, i -> i < 4); + Stream skippedUntilConditionMet = StreamUtils.skipWhile(ints, i -> i > 4); + } + + public void unfoldStream() { + Stream unfolded = StreamUtils.unfold(1, i -> (i < 10) ? Optional.of(i + 1) : Optional.empty()); + } + + public void windowedStream() { + Stream integerStream = Stream.of(1, 2, 3, 4, 5); + + List> windows = StreamUtils + .windowed(integerStream, 2) + .collect(toList()); + List> windowsWithSkipIndex = StreamUtils + .windowed(integerStream, 3, 2) + .collect(toList()); + List> windowsWithSkipIndexAndAllowLowerSize = StreamUtils + .windowed(integerStream, 2, 2, true) + .collect(toList()); + + } + + public void groupRunsStreams() { + Stream integerStream = Stream.of(1, 1, 2, 2, 3, 4, 5); + + List> runs = StreamUtils + .groupRuns(integerStream) + .collect(toList()); + } + + public void aggreagateOnBiElementPredicate() { + Stream stream = Stream.of("a1", "b1", "b2", "c1"); + Stream> aggregated = StreamUtils.aggregate(stream, (e1, e2) -> e1.charAt(0) == e2.charAt(0)); + } + +} diff --git a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApi.java b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApi.java new file mode 100644 index 0000000000..4e071d3384 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApi.java @@ -0,0 +1,33 @@ +package com.baeldung.retrofit.basic; + +import java.util.List; + +import com.baeldung.retrofit.models.Contributor; +import com.baeldung.retrofit.models.Repository; + +import retrofit2.Call; +import retrofit2.http.GET; +import retrofit2.http.Path; + +public interface GitHubBasicApi { + + /** + * List GitHub repositories of user + * @param user GitHub Account + * @return GitHub repositories + */ + @GET("users/{user}/repos") + Call> listRepos(@Path("user") String user); + + /** + * List Contributors of a GitHub Repository + * @param user GitHub Account + * @param repo GitHub Repository + * @return GitHub Repository Contributors + */ + @GET("repos/{user}/{repo}/contributors") + Call> listRepoContributors( + @Path("user") String user, + @Path("repo") String repo); + +} diff --git a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApp.java b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApp.java new file mode 100644 index 0000000000..6b2cd14252 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApp.java @@ -0,0 +1,14 @@ +package com.baeldung.retrofit.basic; + +import java.io.IOException; +import java.util.List; + +public class GitHubBasicApp { + + public static void main(String[] args) throws IOException { + String userName = "eugenp"; + List topContributors = new GitHubBasicService() + .getTopContributors(userName); + topContributors.forEach(System.out::println); + } +} diff --git a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicService.java b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicService.java new file mode 100644 index 0000000000..20256fb540 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicService.java @@ -0,0 +1,60 @@ +package com.baeldung.retrofit.basic; + +import com.baeldung.retrofit.models.Contributor; +import com.baeldung.retrofit.models.Repository; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +import java.io.IOException; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +class GitHubBasicService { + + private GitHubBasicApi gitHubApi; + + GitHubBasicService() { + Retrofit retrofit = new Retrofit.Builder() + .baseUrl("https://api.github.com/") + .addConverterFactory(GsonConverterFactory.create()) + .build(); + + gitHubApi = retrofit.create(GitHubBasicApi.class); + } + + List getTopContributors(String userName) throws IOException { + List repos = gitHubApi + .listRepos(userName) + .execute() + .body(); + + repos = repos != null ? repos : Collections.emptyList(); + + return repos.stream() + .flatMap(repo -> getContributors(userName, repo)) + .sorted((a, b) -> b.getContributions() - a.getContributions()) + .map(Contributor::getName) + .distinct() + .sorted() + .collect(Collectors.toList()); + } + + private Stream getContributors(String userName, Repository repo) { + List contributors = null; + try { + contributors = gitHubApi + .listRepoContributors(userName, repo.getName()) + .execute() + .body(); + } catch (IOException e) { + e.printStackTrace(); + } + + contributors = contributors != null ? contributors : Collections.emptyList(); + + return contributors.stream() + .filter(c -> c.getContributions() > 100); + } +} diff --git a/libraries/src/main/java/com/baeldung/retrofit/models/Contributor.java b/libraries/src/main/java/com/baeldung/retrofit/models/Contributor.java new file mode 100644 index 0000000000..2f8697f603 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/retrofit/models/Contributor.java @@ -0,0 +1,30 @@ +package com.baeldung.retrofit.models; + +import com.google.gson.annotations.SerializedName; + +public class Contributor { + + @SerializedName("login") + private String name; + + private Integer contributions; + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public Integer getContributions() { + return contributions; + } + public void setContributions(Integer contributions) { + this.contributions = contributions; + } + + @Override + public String toString() { + return "Contributer [name=" + name + ", contributions=" + contributions + "]"; + } + +} diff --git a/libraries/src/main/java/com/baeldung/retrofit/models/Repository.java b/libraries/src/main/java/com/baeldung/retrofit/models/Repository.java new file mode 100644 index 0000000000..f12fcdf8f2 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/retrofit/models/Repository.java @@ -0,0 +1,27 @@ +package com.baeldung.retrofit.models; + +public class Repository { + + private String name; + + private String description; + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + + @Override + public String toString() { + return "Repository [name=" + name + ", description=" + description + "]"; + } + +} diff --git a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApi.java b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApi.java new file mode 100644 index 0000000000..4e40aff448 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApi.java @@ -0,0 +1,33 @@ +package com.baeldung.retrofit.rx; + +import java.util.List; + +import com.baeldung.retrofit.models.Contributor; +import com.baeldung.retrofit.models.Repository; + +import retrofit2.http.GET; +import retrofit2.http.Path; +import rx.Observable; + +public interface GitHubRxApi { + + /** + * List GitHub repositories of user + * @param user GitHub Account + * @return GitHub repositories + */ + @GET("users/{user}/repos") + Observable> listRepos(@Path("user") String user); + + /** + * List Contributors of a GitHub Repository + * @param user GitHub Account + * @param repo GitHub Repository + * @return GitHub Repository Contributors + */ + @GET("repos/{user}/{repo}/contributors") + Observable> listRepoContributors( + @Path("user") String user, + @Path("repo") String repo); + +} diff --git a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApp.java b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApp.java new file mode 100644 index 0000000000..b136a1e40b --- /dev/null +++ b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApp.java @@ -0,0 +1,12 @@ +package com.baeldung.retrofit.rx; + +import java.io.IOException; + +public class GitHubRxApp { + + public static void main(String[] args) throws IOException { + String userName = "eugenp"; + new GitHubRxService().getTopContributors(userName) + .subscribe(System.out::println); + } +} diff --git a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxService.java b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxService.java new file mode 100644 index 0000000000..2ad50a9f39 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxService.java @@ -0,0 +1,33 @@ +package com.baeldung.retrofit.rx; + +import com.baeldung.retrofit.models.Contributor; +import retrofit2.Retrofit; +import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; +import retrofit2.converter.gson.GsonConverterFactory; +import rx.Observable; + +class GitHubRxService { + + private GitHubRxApi gitHubApi; + + GitHubRxService() { + Retrofit retrofit = new Retrofit.Builder() + .baseUrl("https://api.github.com/") + .addConverterFactory(GsonConverterFactory.create()) + .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) + .build(); + + gitHubApi = retrofit.create(GitHubRxApi.class); + } + + Observable getTopContributors(String userName) { + return gitHubApi.listRepos(userName) + .flatMapIterable(x -> x) + .flatMap(repo -> gitHubApi.listRepoContributors(userName, repo.getName())) + .flatMapIterable(x -> x) + .filter(c -> c.getContributions() > 100) + .sorted((a, b) -> b.getContributions() - a.getContributions()) + .map(Contributor::getName) + .distinct(); + } +} diff --git a/libraries/src/main/java/com/baeldung/retrofitguide/GitHubServiceGenerator.java b/libraries/src/main/java/com/baeldung/retrofitguide/GitHubServiceGenerator.java new file mode 100644 index 0000000000..d32891be9e --- /dev/null +++ b/libraries/src/main/java/com/baeldung/retrofitguide/GitHubServiceGenerator.java @@ -0,0 +1,58 @@ +package com.baeldung.retrofitguide; + +import java.io.IOException; +import okhttp3.Interceptor; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.logging.HttpLoggingInterceptor; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class GitHubServiceGenerator { + + private static final String BASE_URL = "https://api.github.com/"; + + private static Retrofit.Builder builder + = new Retrofit.Builder() + .baseUrl(BASE_URL) + .addConverterFactory(GsonConverterFactory.create()); + + private static Retrofit retrofit = builder.build(); + + private static OkHttpClient.Builder httpClient + = new OkHttpClient.Builder(); + + private static HttpLoggingInterceptor logging + = new HttpLoggingInterceptor() + .setLevel(HttpLoggingInterceptor.Level.BASIC); + + public static S createService(Class serviceClass) { + if (!httpClient.interceptors().contains(logging)) { + httpClient.addInterceptor(logging); + builder.client(httpClient.build()); + retrofit = builder.build(); + } + return retrofit.create(serviceClass); + } + + public static S createService(Class serviceClass, final String token) { + if (token != null) { + httpClient.interceptors().clear(); + httpClient.addInterceptor(new Interceptor() { + @Override + public Response intercept(Interceptor.Chain chain) throws IOException { + Request original = chain.request(); + Request.Builder builder = original.newBuilder() + .header("Authorization", token); + Request request = builder.build(); + return chain.proceed(request); + } + }); + builder.client(httpClient.build()); + retrofit = builder.build(); + } + return retrofit.create(serviceClass); + } + +} diff --git a/libraries/src/main/java/com/baeldung/retrofitguide/Main.java b/libraries/src/main/java/com/baeldung/retrofitguide/Main.java new file mode 100644 index 0000000000..8a674f634b --- /dev/null +++ b/libraries/src/main/java/com/baeldung/retrofitguide/Main.java @@ -0,0 +1,49 @@ +package com.baeldung.retrofitguide; + +import java.io.IOException; +import okhttp3.OkHttpClient; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class Main { + + public static void main(String[] args) { + //Manual creation + OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); + Retrofit retrofit = new Retrofit.Builder() + .baseUrl("https://api.github.com/") + .addConverterFactory(GsonConverterFactory.create()) + .client(httpClient.build()) + .build(); + UserService service = retrofit.create(UserService.class); + //Using GitHubServiceGenerator + service = GitHubServiceGenerator.createService(UserService.class); + Call callSync = service.getUser("eugenp"); + Call callAsync = service.getUser("eugenp"); + + try { + Response response = callSync.execute(); + User user = response.body(); + System.out.println(user); + } catch (IOException ex) { + } + + // Execute the call asynchronously. Get a positive or negative callback. + callAsync.enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + User user = response.body(); + System.out.println(user); + } + + @Override + public void onFailure(Call call, Throwable throwable) { + System.out.println(throwable); + } + }); + + } +} diff --git a/libraries/src/main/java/com/baeldung/retrofitguide/User.java b/libraries/src/main/java/com/baeldung/retrofitguide/User.java new file mode 100644 index 0000000000..1b097aa4f1 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/retrofitguide/User.java @@ -0,0 +1,65 @@ +package com.baeldung.retrofitguide; + +public class User { + + private String login; + private long id; + private String url; + private String company; + private String blog; + private String email; + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + + public String getBlog() { + return blog; + } + + public void setBlog(String blog) { + this.blog = blog; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String toString() { + return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}'; + } + +} diff --git a/libraries/src/main/java/com/baeldung/retrofitguide/UserService.java b/libraries/src/main/java/com/baeldung/retrofitguide/UserService.java new file mode 100644 index 0000000000..6e18e685ca --- /dev/null +++ b/libraries/src/main/java/com/baeldung/retrofitguide/UserService.java @@ -0,0 +1,17 @@ +package com.baeldung.retrofitguide; + +import java.util.List; +import retrofit2.Call; +import retrofit2.http.GET; +import retrofit2.http.Path; +import retrofit2.http.Query; + +public interface UserService { + + @GET("/users") + public Call> getUsers(@Query("per_page") int per_page, @Query("page") int page); + + @GET("/users/{username}") + public Call getUser(@Path("username") String username); + +} diff --git a/libraries/src/main/java/com/baeldung/yarg/DocumentController.java b/libraries/src/main/java/com/baeldung/yarg/DocumentController.java new file mode 100644 index 0000000000..0e1bbca561 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/yarg/DocumentController.java @@ -0,0 +1,56 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.baeldung.yarg; + +import com.haulmont.yarg.formatters.factory.DefaultFormatterFactory; +import com.haulmont.yarg.loaders.factory.DefaultLoaderFactory; +import com.haulmont.yarg.loaders.impl.JsonDataLoader; +import com.haulmont.yarg.reporting.Reporting; +import com.haulmont.yarg.reporting.RunParams; +import com.haulmont.yarg.structure.Report; +import com.haulmont.yarg.structure.ReportBand; +import com.haulmont.yarg.structure.ReportOutputType; +import com.haulmont.yarg.structure.impl.BandBuilder; +import com.haulmont.yarg.structure.impl.ReportBuilder; +import com.haulmont.yarg.structure.impl.ReportTemplateBuilder; +import java.io.File; +import java.io.IOException; +import javax.servlet.http.HttpServletResponse; +import org.apache.commons.io.FileUtils; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class DocumentController { + + @RequestMapping(path = "/generate/doc", method = RequestMethod.GET) + public void generateDocument(HttpServletResponse response) throws IOException { + ReportBuilder reportBuilder = new ReportBuilder(); + ReportTemplateBuilder reportTemplateBuilder = new ReportTemplateBuilder() + .documentPath("./src/main/resources/Letter.docx") + .documentName("Letter.docx") + .outputType(ReportOutputType.docx) + .readFileFromPath(); + reportBuilder.template(reportTemplateBuilder.build()); + BandBuilder bandBuilder = new BandBuilder(); + String json = FileUtils.readFileToString(new File("./src/main/resources/Data.json")); + ReportBand main = bandBuilder.name("Main") + .query("Main", "parameter=param1 $.main", "json") + .build(); + reportBuilder.band(main); + Report report = reportBuilder.build(); + + Reporting reporting = new Reporting(); + reporting.setFormatterFactory(new DefaultFormatterFactory()); + reporting.setLoaderFactory( + new DefaultLoaderFactory() + .setJsonDataLoader(new JsonDataLoader())); + response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); + reporting.runReport(new RunParams(report).param("param1", json), response.getOutputStream()); + } + +} diff --git a/libraries/src/main/resources/Data.json b/libraries/src/main/resources/Data.json new file mode 100644 index 0000000000..d098839d51 --- /dev/null +++ b/libraries/src/main/resources/Data.json @@ -0,0 +1,7 @@ +{ + "main": { + "title" : "INTRODUCTION TO YARG", + "name" : "Baeldung", + "content" : "This is the content of the letter, can be anything we like." + } +} diff --git a/libraries/src/main/resources/Letter.docx b/libraries/src/main/resources/Letter.docx new file mode 100644 index 0000000000..fbd01271d0 Binary files /dev/null and b/libraries/src/main/resources/Letter.docx differ diff --git a/libraries/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java b/libraries/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java new file mode 100644 index 0000000000..3c82c30d9b --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java @@ -0,0 +1,151 @@ +package com.baeldung.commons.io; + +import org.apache.commons.io.FileSystemUtils; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.io.IOCase; +import org.apache.commons.io.comparator.PathFileComparator; +import org.apache.commons.io.comparator.SizeFileComparator; +import org.apache.commons.io.filefilter.AndFileFilter; +import org.apache.commons.io.filefilter.NameFileFilter; +import org.apache.commons.io.filefilter.SuffixFileFilter; +import org.apache.commons.io.filefilter.WildcardFileFilter; +import org.apache.commons.io.input.TeeInputStream; +import org.apache.commons.io.output.TeeOutputStream; +import org.junit.Assert; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FilterOutputStream; +import java.io.IOException; +import java.nio.charset.Charset; + +public class CommonsIOUnitTest { + + @Test + public void whenCopyANDReadFileTesttxt_thenMatchExpectedData() + throws IOException { + + String expectedData = "Hello World from fileTest.txt!!!"; + + File file = FileUtils.getFile(getClass().getClassLoader() + .getResource("fileTest.txt") + .getPath()); + File tempDir = FileUtils.getTempDirectory(); + FileUtils.copyFileToDirectory(file, tempDir); + File newTempFile = FileUtils.getFile(tempDir, file.getName()); + String data = FileUtils.readFileToString(newTempFile, + Charset.defaultCharset()); + + Assert.assertEquals(expectedData, data.trim()); + } + + @Test + public void whenUsingFileNameUtils_thenshowdifferentFileOperations() + throws IOException { + + String path = getClass().getClassLoader() + .getResource("fileTest.txt") + .getPath(); + + String fullPath = FilenameUtils.getFullPath(path); + String extension = FilenameUtils.getExtension(path); + String baseName = FilenameUtils.getBaseName(path); + + System.out.println("full path" + fullPath); + System.out.println("Extension" + extension); + System.out.println("Base name" + baseName); + } + + @Test + public void whenUsingFileSystemUtils_thenDriveFreeSpace() + throws IOException { + + long freeSpace = FileSystemUtils.freeSpaceKb("/"); + } + + @SuppressWarnings("resource") + @Test + public void whenUsingTeeInputOutputStream_thenWriteto2OutputStreams() + throws IOException { + + final String str = "Hello World."; + ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes()); + ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream(); + ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream(); + + FilterOutputStream teeOutputStream = new TeeOutputStream(outputStream1,outputStream2); + new TeeInputStream(inputStream, teeOutputStream, true).read(new byte[str.length()]); + + Assert.assertEquals(str, String.valueOf(outputStream1)); + Assert.assertEquals(str, String.valueOf(outputStream2)); + } + + @Test + public void whenGetFilewithNameFileFilter_thenFindfileTesttxt() + throws IOException { + + final String testFile = "fileTest.txt"; + + String path = getClass().getClassLoader() + .getResource(testFile) + .getPath(); + File dir = FileUtils.getFile(FilenameUtils.getFullPath(path)); + + String[] possibleNames = { "NotThisOne", testFile }; + + Assert.assertEquals(testFile, + dir.list(new NameFileFilter(possibleNames, IOCase.INSENSITIVE))[0]); + } + + @Test + public void whenGetFilewith_ANDFileFilter_thenFindsampletxt() + throws IOException { + + String path = getClass().getClassLoader() + .getResource("fileTest.txt") + .getPath(); + File dir = FileUtils.getFile(FilenameUtils.getFullPath(path)); + + Assert.assertEquals("sample.txt", + dir.list(new AndFileFilter( + new WildcardFileFilter("*ple*", IOCase.INSENSITIVE), + new SuffixFileFilter("txt")))[0]); + } + + @Test + public void whenSortDirWithPathFileComparator_thenFirstFileaaatxt() + throws IOException { + + PathFileComparator pathFileComparator = new PathFileComparator( + IOCase.INSENSITIVE); + String path = FilenameUtils.getFullPath(getClass().getClassLoader() + .getResource("fileTest.txt") + .getPath()); + File dir = new File(path); + File[] files = dir.listFiles(); + + pathFileComparator.sort(files); + + Assert.assertEquals("aaa.txt", files[0].getName()); + } + + @Test + public void whenSizeFileComparator_thenLargerFile() + throws IOException { + + SizeFileComparator sizeFileComparator = new SizeFileComparator(); + File largerFile = FileUtils.getFile(getClass().getClassLoader() + .getResource("fileTest.txt") + .getPath()); + File smallerFile = FileUtils.getFile(getClass().getClassLoader() + .getResource("sample.txt") + .getPath()); + + int i = sizeFileComparator.compare(largerFile, smallerFile); + + Assert.assertTrue(i > 0); + } +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsTest.java new file mode 100644 index 0000000000..af70ccecc7 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsTest.java @@ -0,0 +1,136 @@ +package com.baeldung.commons.lang3; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.io.File; +import java.lang.reflect.Field; +import java.util.Locale; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +import org.apache.commons.lang3.ArchUtils; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.SystemUtils; +import org.apache.commons.lang3.arch.Processor; +import org.apache.commons.lang3.concurrent.ConcurrentException; +import org.apache.commons.lang3.concurrent.ConcurrentRuntimeException; +import org.apache.commons.lang3.concurrent.ConcurrentUtils; +import org.apache.commons.lang3.event.EventUtils; +import org.apache.commons.lang3.reflect.FieldUtils; +import org.apache.commons.lang3.time.FastDateFormat; +import org.junit.Assert; +import org.junit.Test; + +public class Lang3UtilsTest { + + @Test + public void test_to_Boolean_fromString() { + assertFalse(BooleanUtils.toBoolean("off")); + assertTrue(BooleanUtils.toBoolean("true")); + assertTrue(BooleanUtils.toBoolean("tRue")); + assertFalse(BooleanUtils.toBoolean("no")); + assertFalse(BooleanUtils.isTrue(Boolean.FALSE)); + assertFalse(BooleanUtils.isTrue(null)); + } + + @Test + public void testGetUserHome() { + final File dir = SystemUtils.getUserHome(); + Assert.assertNotNull(dir); + Assert.assertTrue(dir.exists()); + } + + @Test + public void testGetJavaHome() { + final File dir = SystemUtils.getJavaHome(); + Assert.assertNotNull(dir); + Assert.assertTrue(dir.exists()); + } + + @Test + public void testProcessorArchType() { + Processor processor = ArchUtils.getProcessor("x86"); + assertTrue(processor.is32Bit()); + assertFalse(processor.is64Bit()); + } + + @Test + public void testProcessorArchType64Bit() { + Processor processor = ArchUtils.getProcessor("x86_64"); + assertFalse(processor.is32Bit()); + assertTrue(processor.is64Bit()); + } + + @Test(expected = IllegalArgumentException.class) + public void testConcurrentRuntimeExceptionCauseError() { + new ConcurrentRuntimeException("An error", new Error()); + } + + @Test + public void testConstantFuture_Integer() throws Exception { + Future test = ConcurrentUtils.constantFuture(5); + assertTrue(test.isDone()); + assertSame(5, test.get()); + assertFalse(test.isCancelled()); + } + + @Test + public void testFieldUtilsGetAllFields() { + final Field[] fieldsNumber = Number.class.getDeclaredFields(); + assertArrayEquals(fieldsNumber, FieldUtils.getAllFields(Number.class)); + } + + @Test + public void test_getInstance_String_Locale() { + final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.US); + final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); + + assertNotSame(format1, format3); + } + + @Test + public void testAddEventListenerThrowsException() { + final ExceptionEventSource src = new ExceptionEventSource(); + try { + EventUtils.addEventListener(src, PropertyChangeListener.class, (PropertyChangeEvent e) -> { + /* Change event*/}); + fail("Add method should have thrown an exception, so method should fail."); + } catch (final RuntimeException e) { + + } + } + + @Test + public void ConcurrentExceptionSample() throws ConcurrentException { + final Error err = new AssertionError("Test"); + try { + ConcurrentUtils.handleCause(new ExecutionException(err)); + fail("Error not thrown!"); + } catch (final Error e) { + assertEquals("Wrong error", err, e); + } + } + + public static class ExceptionEventSource { + public void addPropertyChangeListener(final PropertyChangeListener listener) { + throw new RuntimeException(); + } + } + + @Test + public void testLazyInitializer() throws Exception { + SampleLazyInitializer sampleLazyInitializer = new SampleLazyInitializer(); + SampleObject sampleObjectOne = sampleLazyInitializer.get(); + SampleObject sampleObjectTwo = sampleLazyInitializer.get(); + assertEquals(sampleObjectOne, sampleObjectTwo); + } + +} diff --git a/core-java/src/test/java/com/baeldung/DateDiffUnitTest.java b/libraries/src/test/java/com/baeldung/date/DateDiffUnitTest.java similarity index 86% rename from core-java/src/test/java/com/baeldung/DateDiffUnitTest.java rename to libraries/src/test/java/com/baeldung/date/DateDiffUnitTest.java index 324a0d4587..14d3f925f5 100644 --- a/core-java/src/test/java/com/baeldung/DateDiffUnitTest.java +++ b/libraries/src/test/java/com/baeldung/date/DateDiffUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.date; import org.junit.Test; @@ -28,17 +28,6 @@ public class DateDiffUnitTest { assertEquals(diff, 6); } - @Test - public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() { - LocalDate now = LocalDate.now(); - LocalDate sixDaysBehind = now.minusDays(6); - - Duration duration = Duration.between(now, sixDaysBehind); - long diff = Math.abs(duration.toDays()); - - assertEquals(diff, 6); - } - @Test public void givenTwoDateTimesInJava8_whenDifferentiating_thenWeGetSix() { LocalDateTime now = LocalDateTime.now(); diff --git a/libraries/src/test/java/com/baeldung/fj/FunctionalJavaTest.java b/libraries/src/test/java/com/baeldung/fj/FunctionalJavaTest.java new file mode 100644 index 0000000000..04ab6e43be --- /dev/null +++ b/libraries/src/test/java/com/baeldung/fj/FunctionalJavaTest.java @@ -0,0 +1,79 @@ +package com.baeldung.fj; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import fj.F; +import fj.data.Array; +import fj.data.List; +import fj.data.Option; +import fj.function.Characters; +import fj.function.Integers; + +public class FunctionalJavaTest { + + public static final F isEven = i -> i % 2 == 0; + + @Test + public void calculateEvenNumbers_givenIntList_returnTrue() { + List fList = List.list(3, 4, 5, 6); + List evenList = fList.map(isEven); + List evenListTrueResult = List.list(false, true, false, true); + List evenListFalseResult = List.list(true, false, false, true); + assertEquals(evenList.equals(evenListTrueResult), true); + assertEquals(evenList.equals(evenListFalseResult), false); + } + + @Test + public void mapList_givenIntList_returnResult() { + List fList = List.list(3, 4, 5, 6); + fList = fList.map(i -> i + 100); + List resultList = List.list(103, 104, 105, 106); + List falseResultList = List.list(15, 504, 105, 106); + assertEquals(fList.equals(resultList), true); + assertEquals(fList.equals(falseResultList), false); + } + + @Test + public void filterList_givenIntList_returnResult() { + Array array = Array.array(3, 4, 5, 6); + Array filteredArray = array.filter(Integers.even); + Array result = Array.array(4, 6); + Array wrongResult = Array.array(3, 5); + assertEquals(filteredArray.equals(result), true); + assertEquals(filteredArray.equals(wrongResult), false); + } + + @Test + public void checkForLowerCase_givenStringArray_returnResult() { + Array array = Array.array("Welcome", "To", "baeldung"); + Array array2 = Array.array("Welcome", "To", "Baeldung"); + Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase)); + Boolean isExist2 = array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase)); + assertEquals(isExist, true); + assertEquals(isExist2, false); + } + + @Test + public void checkOptions_givenOptions_returnResult() { + Option n1 = Option.some(1); + Option n2 = Option.some(2); + + F> f1 = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none(); + + Option result1 = n1.bind(f1); + Option result2 = n2.bind(f1); + + assertEquals(result1, Option.none()); + assertEquals(result2, Option.some(102)); + } + + @Test + public void foldLeft_givenArray_returnResult() { + Array intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27); + int sum = intArray.foldLeft(Integers.add, 0); + assertEquals(sum, 260); + } + +} diff --git a/libraries/src/test/java/com/baeldung/java/io/JavaDirectoryDeleteUnitTest.java b/libraries/src/test/java/com/baeldung/java/io/JavaDirectoryDeleteUnitTest.java new file mode 100644 index 0000000000..1cd390b873 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/java/io/JavaDirectoryDeleteUnitTest.java @@ -0,0 +1,141 @@ +package com.baeldung.java.io; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; + +import org.apache.commons.io.FileUtils; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.util.FileSystemUtils; + +public class JavaDirectoryDeleteUnitTest { + private static Path TEMP_DIRECTORY; + private static final String DIRECTORY_NAME = "toBeDeleted"; + + private static final List ALL_LINES = Arrays.asList("This is line 1", "This is line 2", "This is line 3", "This is line 4", "This is line 5", "This is line 6"); + + @BeforeClass + public static void initializeTempDirectory() throws IOException { + TEMP_DIRECTORY = Files.createTempDirectory("tmpForJUnit"); + } + + @AfterClass + public static void cleanTempDirectory() throws IOException { + FileUtils.deleteDirectory(TEMP_DIRECTORY.toFile()); + } + + @Before + public void setupDirectory() throws IOException { + Path tempPathForEachTest = Files.createDirectory(TEMP_DIRECTORY.resolve(DIRECTORY_NAME)); + + // Create a directory structure + Files.write(tempPathForEachTest.resolve("file1.txt"), ALL_LINES.subList(0, 2)); + Files.write(tempPathForEachTest.resolve("file2.txt"), ALL_LINES.subList(2, 4)); + + Files.createDirectories(tempPathForEachTest.resolve("Empty")); + + Path aSubDir = Files.createDirectories(tempPathForEachTest.resolve("notEmpty")); + Files.write(aSubDir.resolve("file3.txt"), ALL_LINES.subList(3, 5)); + Files.write(aSubDir.resolve("file4.txt"), ALL_LINES.subList(0, 3)); + + aSubDir = Files.createDirectories(aSubDir.resolve("anotherSubDirectory")); + Files.write(aSubDir.resolve("file5.txt"), ALL_LINES.subList(4, 5)); + Files.write(aSubDir.resolve("file6.txt"), ALL_LINES.subList(0, 2)); + } + + @After + public void checkAndCleanupIfRequired() throws IOException { + Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); + if (Files.exists(pathToBeDeleted)) { + FileUtils.deleteDirectory(pathToBeDeleted.toFile()); + } + } + + private boolean deleteDirectory(File directoryToBeDeleted) { + File[] allContents = directoryToBeDeleted.listFiles(); + + if (allContents != null) { + for (File file : allContents) { + deleteDirectory(file); + } + } + + return directoryToBeDeleted.delete(); + } + + @Test + public void givenDirectory_whenDeletedWithRecursion_thenIsGone() throws IOException { + Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); + + boolean result = deleteDirectory(pathToBeDeleted.toFile()); + + assertTrue("Could not delete directory", result); + assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); + } + + @Test + public void givenDirectory_whenDeletedWithCommonsIOFileUtils_thenIsGone() throws IOException { + Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); + + FileUtils.deleteDirectory(pathToBeDeleted.toFile()); + + assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); + } + + @Test + public void givenDirectory_whenDeletedWithSpringFileSystemUtils_thenIsGone() throws IOException { + Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); + + boolean result = FileSystemUtils.deleteRecursively(pathToBeDeleted.toFile()); + + assertTrue("Could not delete directory", result); + assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); + } + + @Test + public void givenDirectory_whenDeletedWithFilesWalk_thenIsGone() throws IOException { + Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); + + Files.walk(pathToBeDeleted) + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + + assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); + } + + @Test + public void givenDirectory_whenDeletedWithNIO2WalkFileTree_thenIsGone() throws IOException { + Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); + + Files.walkFileTree(pathToBeDeleted, new SimpleFileVisitor() { + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + Files.delete(dir); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Files.delete(file); + return FileVisitResult.CONTINUE; + } + }); + + assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); + } +} diff --git a/libraries/src/test/java/com/baeldung/jcache/CacheLoaderTest.java b/libraries/src/test/java/com/baeldung/jcache/CacheLoaderTest.java new file mode 100644 index 0000000000..e1219e6c49 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/jcache/CacheLoaderTest.java @@ -0,0 +1,44 @@ +package com.baeldung.jcache; + +import static org.junit.Assert.assertEquals; + +import javax.cache.Cache; +import javax.cache.CacheManager; +import javax.cache.Caching; +import javax.cache.configuration.FactoryBuilder; +import javax.cache.configuration.MutableConfiguration; +import javax.cache.spi.CachingProvider; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class CacheLoaderTest { + + private static final String CACHE_NAME = "SimpleCache"; + + private Cache cache; + + @Before + public void setup() { + CachingProvider cachingProvider = Caching.getCachingProvider(); + CacheManager cacheManager = cachingProvider.getCacheManager(); + MutableConfiguration config = new MutableConfiguration().setReadThrough(true) + .setCacheLoaderFactory(new FactoryBuilder.SingletonFactory<>(new SimpleCacheLoader())); + this.cache = cacheManager.createCache("SimpleCache", config); + } + + @After + public void tearDown() { + Caching.getCachingProvider() + .getCacheManager().destroyCache(CACHE_NAME); + } + + @Test + public void whenReadingFromStorage_thenCorrect() { + for (int i = 1; i < 4; i++) { + String value = cache.get(i); + assertEquals("fromCache" + i, value); + } + } +} diff --git a/libraries/src/test/java/com/baeldung/jcache/EntryProcessorTest.java b/libraries/src/test/java/com/baeldung/jcache/EntryProcessorTest.java new file mode 100644 index 0000000000..741bdc7389 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/jcache/EntryProcessorTest.java @@ -0,0 +1,41 @@ +package com.baeldung.jcache; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import javax.cache.Cache; +import javax.cache.CacheManager; +import javax.cache.Caching; +import javax.cache.configuration.MutableConfiguration; +import javax.cache.spi.CachingProvider; + +import static org.junit.Assert.assertEquals; + +public class EntryProcessorTest { + + private static final String CACHE_NAME = "MyCache"; + + private Cache cache; + + @Before + public void instantiateCache() { + CachingProvider cachingProvider = Caching.getCachingProvider(); + CacheManager cacheManager = cachingProvider.getCacheManager(); + MutableConfiguration config = new MutableConfiguration<>(); + this.cache = cacheManager.createCache(CACHE_NAME, config); + this.cache.put("key", "value"); + } + + @After + public void tearDown() { + Caching.getCachingProvider() + .getCacheManager().destroyCache(CACHE_NAME); + } + + @Test + public void whenModifyValue_thenCorrect() { + this.cache.invoke("key", new SimpleEntryProcessor()); + assertEquals("value - modified", cache.get("key")); + } +} diff --git a/libraries/src/test/java/com/baeldung/jcache/EventListenerTest.java b/libraries/src/test/java/com/baeldung/jcache/EventListenerTest.java new file mode 100644 index 0000000000..b32fe795de --- /dev/null +++ b/libraries/src/test/java/com/baeldung/jcache/EventListenerTest.java @@ -0,0 +1,56 @@ +package com.baeldung.jcache; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import javax.cache.Cache; +import javax.cache.CacheManager; +import javax.cache.Caching; +import javax.cache.configuration.FactoryBuilder; +import javax.cache.configuration.MutableCacheEntryListenerConfiguration; +import javax.cache.configuration.MutableConfiguration; +import javax.cache.spi.CachingProvider; + +import static org.junit.Assert.assertEquals; + +public class EventListenerTest { + + private static final String CACHE_NAME = "MyCache"; + + private Cache cache; + private SimpleCacheEntryListener listener; + private MutableCacheEntryListenerConfiguration listenerConfiguration; + + @Before + public void setup() { + CachingProvider cachingProvider = Caching.getCachingProvider(); + CacheManager cacheManager = cachingProvider.getCacheManager(); + MutableConfiguration config = new MutableConfiguration(); + this.cache = cacheManager.createCache("MyCache", config); + this.listener = new SimpleCacheEntryListener(); + } + + @After + public void tearDown() { + Caching.getCachingProvider() + .getCacheManager().destroyCache(CACHE_NAME); + } + + @Test + public void whenRunEvent_thenCorrect() throws InterruptedException { + this.listenerConfiguration = new MutableCacheEntryListenerConfiguration<>(FactoryBuilder + .factoryOf(this.listener), null, false, true); + this.cache.registerCacheEntryListener(this.listenerConfiguration); + + assertEquals(false, this.listener.getCreated()); + + this.cache.put("key", "value"); + assertEquals(true, this.listener.getCreated()); + assertEquals(false, this.listener.getUpdated()); + + this.cache.put("key", "newValue"); + assertEquals(true, this.listener.getUpdated()); + } + +} diff --git a/libraries/src/test/java/com/baeldung/jcache/JCacheTest.java b/libraries/src/test/java/com/baeldung/jcache/JCacheTest.java new file mode 100644 index 0000000000..faf3ec9597 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/jcache/JCacheTest.java @@ -0,0 +1,27 @@ +package com.baeldung.jcache; + +import org.junit.Test; + +import javax.cache.Cache; +import javax.cache.CacheManager; +import javax.cache.Caching; +import javax.cache.configuration.MutableConfiguration; +import javax.cache.spi.CachingProvider; + +import static org.junit.Assert.assertEquals; + +public class JCacheTest { + + @Test + public void instantiateCache() { + CachingProvider cachingProvider = Caching.getCachingProvider(); + CacheManager cacheManager = cachingProvider.getCacheManager(); + MutableConfiguration config = new MutableConfiguration<>(); + Cache cache = cacheManager.createCache("simpleCache", config); + cache.put("key1", "value1"); + cache.put("key2", "value2"); + assertEquals("value1", cache.get("key1")); + assertEquals("value2", cache.get("key2")); + cacheManager.close(); + } +} diff --git a/libraries/src/test/java/com/baeldung/jdeffered/AppTest.java b/libraries/src/test/java/com/baeldung/jdeffered/AppTest.java new file mode 100644 index 0000000000..97b20cda57 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/jdeffered/AppTest.java @@ -0,0 +1,26 @@ +package com.baeldung.jdeffered; + +import com.baeldung.jdeffered.PipeDemo.Result; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class AppTest { + + @Test + public void givenJob_expectPromise() { + PromiseDemo.startJob("Baeldung Job"); + } + + @Test + public void givenMsg_expectModifiedMsg() { + String msg = FilterDemo.filter("Baeldung"); + assertEquals("Hello Baeldung", msg); + } + + @Test + public void givenNum_validateNum_expectStatus() { + Result result = PipeDemo.validate(80); + assertEquals(result, Result.SUCCESS); + } +} diff --git a/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncDispatchTest.java b/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncDispatchTest.java new file mode 100644 index 0000000000..0cab612a7b --- /dev/null +++ b/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncDispatchTest.java @@ -0,0 +1,37 @@ +package com.baeldung.mbassador; + +import net.engio.mbassy.bus.MBassador; +import net.engio.mbassy.listener.Handler; +import org.junit.Before; +import org.junit.Test; + +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.awaitility.Awaitility.await; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertNotNull; + +public class MBassadorAsyncDispatchTest { + + private MBassador dispatcher = new MBassador(); + private String testString; + private AtomicBoolean ready = new AtomicBoolean(false); + + @Before + public void prepareTests() { + dispatcher.subscribe(this); + } + + @Test + public void whenAsyncDispatched_thenMessageReceived() { + dispatcher.post("foobar").asynchronously(); + await().untilAtomic(ready, equalTo(true)); + assertNotNull(testString); + } + + @Handler + public void handleStringMessage(String message) { + this.testString = message; + ready.set(true); + } +} diff --git a/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncInvocationTest.java b/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncInvocationTest.java new file mode 100644 index 0000000000..d0b1cafd71 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncInvocationTest.java @@ -0,0 +1,47 @@ +package com.baeldung.mbassador; + +import net.engio.mbassy.bus.MBassador; +import net.engio.mbassy.listener.Handler; +import net.engio.mbassy.listener.Invoke; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.awaitility.Awaitility.await; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertFalse; + +public class MBassadorAsyncInvocationTest { + + private MBassador dispatcher = new MBassador(); + + private Integer testInteger; + private String invocationThreadName; + private AtomicBoolean ready = new AtomicBoolean(false); + + @Before + public void prepareTests() { + dispatcher.subscribe(this); + } + + @Test + public void whenHandlerAsync_thenHandled() { + + dispatcher.post(42).now(); + + await().untilAtomic(ready, equalTo(true)); + assertNotNull(testInteger); + assertFalse(Thread.currentThread().getName().equals(invocationThreadName)); + } + + @Handler(delivery = Invoke.Asynchronously) + public void handleIntegerMessage(Integer message) { + this.invocationThreadName = Thread.currentThread().getName(); + this.testInteger = message; + ready.set(true); + } +} diff --git a/libraries/src/test/java/com/baeldung/mbassador/MBassadorBasicTest.java b/libraries/src/test/java/com/baeldung/mbassador/MBassadorBasicTest.java new file mode 100644 index 0000000000..04f6272412 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/mbassador/MBassadorBasicTest.java @@ -0,0 +1,69 @@ +package com.baeldung.mbassador; + +import net.engio.mbassy.bus.MBassador; +import net.engio.mbassy.bus.common.DeadMessage; +import net.engio.mbassy.listener.Handler; +import org.junit.Before; +import org.junit.Test; + +import static junit.framework.TestCase.assertTrue; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +public class MBassadorBasicTest { + + private MBassador dispatcher = new MBassador(); + + private String messageString; + private Integer messageInteger; + private Object deadEvent; + + @Before + public void prepareTests() { + dispatcher.subscribe(this); + } + + @Test + public void whenStringDispatched_thenHandleString() { + dispatcher.post("TestString").now(); + assertNotNull(messageString); + assertEquals("TestString", messageString); + } + + @Test + public void whenIntegerDispatched_thenHandleInteger() { + dispatcher.post(42).now(); + assertNull(messageString); + assertNotNull(messageInteger); + assertTrue(42 == messageInteger); + } + + @Test + public void whenLongDispatched_thenDeadEvent() { + dispatcher.post(42L).now(); + assertNull(messageString); + assertNull(messageInteger); + assertNotNull(deadEvent); + assertTrue(deadEvent instanceof Long); + assertTrue(42L == (Long) deadEvent); + } + + @Handler + public void handleString(String message) { + messageString = message; + } + + @Handler + public void handleInteger(Integer message) { + messageInteger = message; + } + + @Handler + public void handleDeadEvent(DeadMessage message) { + + deadEvent = message.getMessage(); + + } + +} diff --git a/libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationTest.java b/libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationTest.java new file mode 100644 index 0000000000..fe9c130d93 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationTest.java @@ -0,0 +1,91 @@ +package com.baeldung.mbassador; + +import net.engio.mbassy.bus.MBassador; +import net.engio.mbassy.bus.error.IPublicationErrorHandler; +import net.engio.mbassy.bus.error.PublicationError; +import net.engio.mbassy.listener.Handler; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.*; + +import static junit.framework.TestCase.assertTrue; +import static org.junit.Assert.*; + +public class MBassadorConfigurationTest implements IPublicationErrorHandler { + + private MBassador dispatcher; + private String messageString; + private Throwable errorCause; + + private LinkedList list = new LinkedList<>(); + + @Before + public void prepareTests() { + + dispatcher = new MBassador(this); + dispatcher.subscribe(this); + } + + @Test + public void whenErrorOccurs_thenErrorHandler() { + dispatcher.post("Error").now(); + assertNull(messageString); + assertNotNull(errorCause); + } + + @Test + public void whenNoErrorOccurs_thenStringHandler() { + dispatcher.post("Errol").now(); + assertNull(errorCause); + assertNotNull(messageString); + } + + @Test + public void whenRejectDispatched_thenPriorityHandled() { + dispatcher.post(new RejectMessage()).now(); + + // Items should pop() off in reverse priority order + assertTrue(1 == list.pop()); + assertTrue(3 == list.pop()); + assertTrue(5 == list.pop()); + } + + @Handler + public void handleString(String message) { + + if ("Error".equals(message)) { + throw new Error("BOOM"); + } + + messageString = message; + + } + + @Override + public void handleError(PublicationError error) { + errorCause = error.getCause().getCause(); + } + + @Handler(priority = 5) + public void handleRejectMessage5(RejectMessage rejectMessage) { + list.push(5); + } + + @Handler(priority = 3) + public void handleRejectMessage3(RejectMessage rejectMessage) { + list.push(3); + } + + @Handler(priority = 2, rejectSubtypes = true) + public void handleMessage(Message rejectMessage) { + list.push(3); + } + + @Handler(priority = 0) + public void handleRejectMessage0(RejectMessage rejectMessage) { + list.push(1); + } +} diff --git a/libraries/src/test/java/com/baeldung/mbassador/MBassadorFilterTest.java b/libraries/src/test/java/com/baeldung/mbassador/MBassadorFilterTest.java new file mode 100644 index 0000000000..e90ae15d3d --- /dev/null +++ b/libraries/src/test/java/com/baeldung/mbassador/MBassadorFilterTest.java @@ -0,0 +1,103 @@ +package com.baeldung.mbassador; + +import net.engio.mbassy.bus.MBassador; +import net.engio.mbassy.bus.common.DeadMessage; +import net.engio.mbassy.bus.common.FilteredMessage; +import net.engio.mbassy.listener.Filter; +import net.engio.mbassy.listener.Filters; +import net.engio.mbassy.listener.Handler; +import org.junit.Before; +import org.junit.Test; + +import static junit.framework.TestCase.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +public class MBassadorFilterTest { + + private MBassador dispatcher = new MBassador(); + + private Message baseMessage; + private Message subMessage; + private String testString; + private FilteredMessage filteredMessage; + private RejectMessage rejectMessage; + private DeadMessage deadMessage; + + @Before + public void prepareTests() { + dispatcher.subscribe(this); + } + + @Test + public void whenMessageDispatched_thenMessageFiltered() { + dispatcher.post(new Message()).now(); + assertNotNull(baseMessage); + assertNull(subMessage); + } + + @Test + public void whenRejectDispatched_thenRejectFiltered() { + dispatcher.post(new RejectMessage()).now(); + assertNotNull(subMessage); + assertNull(baseMessage); + } + + @Test + public void whenShortStringDispatched_thenStringHandled() { + dispatcher.post("foobar").now(); + assertNotNull(testString); + } + + @Test + public void whenLongStringDispatched_thenStringFiltered() { + dispatcher.post("foobar!").now(); + assertNull(testString); + // filtered only populated when messages does not pass any filters + assertNotNull(filteredMessage); + assertTrue(filteredMessage.getMessage() instanceof String); + assertNull(deadMessage); + } + + @Test + public void whenWrongRejectDispatched_thenRejectFiltered() { + RejectMessage testReject = new RejectMessage(); + testReject.setCode(-1); + dispatcher.post(testReject).now(); + assertNull(rejectMessage); + assertNotNull(subMessage); + assertEquals(-1, ((RejectMessage) subMessage).getCode()); + } + + @Handler(filters = { @Filter(Filters.RejectSubtypes.class) }) + public void handleBaseMessage(Message message) { + this.baseMessage = message; + } + + @Handler(filters = { @Filter(Filters.SubtypesOnly.class) }) + public void handleSubMessage(Message message) { + this.subMessage = message; + } + + @Handler(condition = "msg.length() < 7") + public void handleStringMessage(String message) { + this.testString = message; + } + + @Handler(condition = "msg.getCode() != -1") + public void handleRejectMessage(RejectMessage rejectMessage) { + this.rejectMessage = rejectMessage; + } + + @Handler + public void handleFilterMessage(FilteredMessage message) { + this.filteredMessage = message; + } + + @Handler + public void handleDeadMessage(DeadMessage deadMessage) { + this.deadMessage = deadMessage; + } + +} diff --git a/libraries/src/test/java/com/baeldung/mbassador/MBassadorHierarchyTest.java b/libraries/src/test/java/com/baeldung/mbassador/MBassadorHierarchyTest.java new file mode 100644 index 0000000000..be5c9d4897 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/mbassador/MBassadorHierarchyTest.java @@ -0,0 +1,61 @@ +package com.baeldung.mbassador; + +import net.engio.mbassy.bus.MBassador; +import net.engio.mbassy.listener.Handler; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class MBassadorHierarchyTest { + + private MBassador dispatcher = new MBassador(); + + private Message message; + private AckMessage ackMessage; + private RejectMessage rejectMessage; + + @Before + public void prepareTests() { + dispatcher.subscribe(this); + } + + @Test + public void whenMessageDispatched_thenMessageHandled() { + dispatcher.post(new Message()).now(); + assertNotNull(message); + assertNull(ackMessage); + assertNull(rejectMessage); + } + + @Test + public void whenRejectDispatched_thenMessageAndRejectHandled() { + dispatcher.post(new RejectMessage()).now(); + assertNotNull(message); + assertNotNull(rejectMessage); + assertNull(ackMessage); + } + + @Test + public void whenAckDispatched_thenMessageAndAckHandled() { + dispatcher.post(new AckMessage()).now(); + assertNotNull(message); + assertNotNull(ackMessage); + assertNull(rejectMessage); + } + + @Handler + public void handleMessage(Message message) { + this.message = message; + } + + @Handler + public void handleRejectMessage(RejectMessage message) { + rejectMessage = message; + } + + @Handler + public void handleAckMessage(AckMessage message) { + ackMessage = message; + } +} diff --git a/libraries/src/test/java/com/baeldung/measurement/WaterTankTests.java b/libraries/src/test/java/com/baeldung/measurement/WaterTankTests.java new file mode 100644 index 0000000000..b023ffe8d9 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/measurement/WaterTankTests.java @@ -0,0 +1,86 @@ +package com.baeldung.measurement; + +import javax.measure.Quantity; +import javax.measure.quantity.Area; +import javax.measure.quantity.Length; +import javax.measure.quantity.Pressure; +import javax.measure.quantity.Volume; + +import javax.measure.Unit; +import javax.measure.UnitConverter; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +import com.baeldung.measurement.WaterTank; + +import tec.units.ri.format.SimpleUnitFormat; +import tec.units.ri.quantity.Quantities; +import tec.units.ri.unit.MetricPrefix; +import static tec.units.ri.unit.Units.*; + +public class WaterTankTests { + + @Test + public void givenQuantity_whenGetUnitAndConvertValue_thenSuccess() { + WaterTank waterTank = new WaterTank(); + waterTank.setCapacityMeasure(Quantities.getQuantity(9.2, LITRE)); + assertEquals(LITRE, waterTank.getCapacityMeasure().getUnit()); + + Quantity waterCapacity = waterTank.getCapacityMeasure(); + double volumeInLitre = waterCapacity.getValue().doubleValue(); + assertEquals(9.2, volumeInLitre, 0.0f); + + double volumeInMilliLitre = waterCapacity.to(MetricPrefix.MILLI(LITRE)).getValue().doubleValue(); + assertEquals(9200.0, volumeInMilliLitre, 0.0f); + + // compilation error + // volumeInMilliLitre = waterCapacity.to(MetricPrefix.MILLI(KILOGRAM)); + + Unit Kilometer = MetricPrefix.KILO(METRE); + + // compilation error + // Unit Centimeter = MetricPrefix.CENTI(LITRE); + } + + @Test + public void givenUnit_whenAlternateUnit_ThenGetAlternateUnit() { + + Unit PASCAL = NEWTON.divide(METRE.pow(2)).alternate("Pa").asType(Pressure.class); + assertTrue(SimpleUnitFormat.getInstance().parse("Pa").equals(PASCAL)); + } + + @Test + public void givenUnit_whenProduct_ThenGetProductUnit() { + Unit squareMetre = METRE.multiply(METRE).asType(Area.class); + Quantity line = Quantities.getQuantity(2, METRE); + assertEquals(line.multiply(line).getUnit(), squareMetre); + } + + @Test + public void givenMeters_whenConvertToKilometer_ThenConverted() { + double distanceInMeters = 50.0; + UnitConverter metreToKilometre = METRE.getConverterTo(MetricPrefix.KILO(METRE)); + double distanceInKilometers = metreToKilometre.convert(distanceInMeters); + assertEquals(0.05, distanceInKilometers, 0.00f); + } + + @Test + public void givenSymbol_WhenCompareToSystemUnit_ThenSuccess() { + assertTrue(SimpleUnitFormat.getInstance().parse("kW").equals(MetricPrefix.KILO(WATT))); + assertTrue(SimpleUnitFormat.getInstance().parse("ms").equals(SECOND.divide(1000))); + } + + @Test + public void givenUnits_WhenAdd_ThenSuccess() { + Quantity total = Quantities.getQuantity(2, METRE).add(Quantities.getQuantity(3, METRE)); + assertEquals(total.getValue().intValue(), 5); + + // compilation error + // Quantity total = Quantities.getQuantity(2, METRE).add(Quantities.getQuantity(3, LITRE)); + + Quantity totalKm = Quantities.getQuantity(2, METRE).add(Quantities.getQuantity(3, MetricPrefix.KILO(METRE))); + assertEquals(totalKm.getValue().intValue(), 3002); + } +} diff --git a/libraries/src/test/java/com/baeldung/pairs/ApacheCommonsPairUnitTest.java b/libraries/src/test/java/com/baeldung/pairs/ApacheCommonsPairUnitTest.java new file mode 100644 index 0000000000..0e6242b8a3 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/pairs/ApacheCommonsPairUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.pairs; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.MutablePair; +import org.junit.Assert; +import org.junit.Test; + +public class ApacheCommonsPairUnitTest { + + @Test + public void givenMutablePair_whenGetValue_shouldPass() { + int key = 5; + String value = "Five"; + + MutablePair mutablePair = new MutablePair<>(key, value); + Assert.assertTrue(mutablePair.getKey() == key); + Assert.assertEquals(mutablePair.getValue(), value); + } + + @Test + public void givenMutablePair_whenSetValue_shouldPass() { + int key = 6; + String value = "Six"; + String newValue = "New Six"; + + MutablePair mutablePair = new MutablePair<>(key, value); + Assert.assertTrue(mutablePair.getKey() == key); + Assert.assertEquals(mutablePair.getValue(), value); + mutablePair.setValue(newValue); + Assert.assertEquals(mutablePair.getValue(), newValue); + } + + @Test + public void givenImmutablePair_whenGetValue_shouldPass() { + int key = 2; + String value = "Two"; + + ImmutablePair immutablePair = new ImmutablePair<>(key, value); + Assert.assertTrue(immutablePair.getKey() == key); + Assert.assertEquals(immutablePair.getValue(), value); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenImmutablePair_whenSetValue_shouldFail() { + ImmutablePair immutablePair = new ImmutablePair<>(1, "One"); + immutablePair.setValue("Another One"); + } + + +} diff --git a/libraries/src/test/java/com/baeldung/pairs/CoreJavaPairUnitTest.java b/libraries/src/test/java/com/baeldung/pairs/CoreJavaPairUnitTest.java new file mode 100644 index 0000000000..ac258b9c77 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/pairs/CoreJavaPairUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.pairs; + +import javafx.util.Pair; +import org.junit.Assert; +import org.junit.Test; + +public class CoreJavaPairUnitTest { + @Test + public void givenPair_whenGetValue_shouldSucceed() { + String key = "Good Day"; + boolean value = true; + Pair pair = new Pair<>(key, value); + + Assert.assertEquals(key, pair.getKey()); + Assert.assertEquals(value, pair.getValue()); + } +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/pairs/VavrPairsUnitTest.java b/libraries/src/test/java/com/baeldung/pairs/VavrPairsUnitTest.java new file mode 100644 index 0000000000..9c318c7744 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/pairs/VavrPairsUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.pairs; + +import io.vavr.Tuple2; +import org.junit.Assert; +import org.junit.Test; + +public class VavrPairsUnitTest { + @Test + public void givenTuple_whenSetValue_shouldSucceed() { + String key = "Eleven"; + double value = 11.0; + double newValue = 11.1; + + Tuple2 pair = new Tuple2<>(key, value); + + pair = pair.update2(newValue); + Assert.assertTrue(newValue == pair._2()); + } + + @Test + public void givenPair_whenGetValue_shouldSucceed() { + String key = "Twelve"; + double value = 12.0; + + Tuple2 pair = new Tuple2<>(key, value); + + Assert.assertTrue(value == pair._2()); + } +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/protonpack/CollectorUtilsTests.java b/libraries/src/test/java/com/baeldung/protonpack/CollectorUtilsTests.java new file mode 100644 index 0000000000..cf6a1e5ec5 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/protonpack/CollectorUtilsTests.java @@ -0,0 +1,66 @@ +package com.baeldung.protonpack; + +import com.codepoetics.protonpack.collectors.CollectorUtils; +import com.codepoetics.protonpack.collectors.NonUniqueValueException; +import org.junit.Test; + +import java.util.Optional; +import java.util.stream.Stream; + +import static com.codepoetics.protonpack.collectors.CollectorUtils.maxBy; +import static com.codepoetics.protonpack.collectors.CollectorUtils.minBy; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +public class CollectorUtilsTests { + + @Test + public void givenIntegerStream_whenCollectOnMaxByProjection_shouldReturnOptionalMaxValue() { + Stream integerStream = Stream.of("a", "bb", "ccc", "1"); + + Optional max = integerStream.collect(maxBy(String::length)); + + assertThat(max.get(), is("ccc")); + } + + @Test + public void givenIntegerStream_whenCollectOnMinByProjection_shouldReturnOptionalMinValue() { + Stream integerStream = Stream.of("abc", "bb", "ccc", "1"); + + Optional max = integerStream.collect(minBy(String::length)); + + assertThat(max.get(), is("1")); + } + + @Test + public void givenEmptyStream_withCollectorUnique_shouldReturnEmpty() { + assertThat(Stream + .empty() + .collect(CollectorUtils.unique()), equalTo(Optional.empty())); + } + + @Test + public void givenIntegerStream_withCollectorUnique_shouldReturnUniqueValue() { + assertThat(Stream + .of(1, 2, 3) + .filter(i -> i > 2) + .collect(CollectorUtils.unique()), equalTo(Optional.of(3))); + } + + @Test + public void givenIntegerStream_withUniqueNullable_shouldReturnUniqueValue() { + assertThat(Stream + .of(1, 2, 3) + .filter(i -> i > 2) + .collect(CollectorUtils.uniqueNullable()), equalTo(3)); + } + + @Test(expected = NonUniqueValueException.class) + public void givenIntegerStream_withCollectorUnique_shouldThrowNonUniqueValueException() { + Stream + .of(1, 2, 3) + .filter(i -> i > 1) + .collect(CollectorUtils.unique()); + } +} diff --git a/libraries/src/test/java/com/baeldung/protonpack/StreamUtilsTests.java b/libraries/src/test/java/com/baeldung/protonpack/StreamUtilsTests.java new file mode 100644 index 0000000000..37ca71287f --- /dev/null +++ b/libraries/src/test/java/com/baeldung/protonpack/StreamUtilsTests.java @@ -0,0 +1,202 @@ +package com.baeldung.protonpack; + +import com.codepoetics.protonpack.Indexed; +import com.codepoetics.protonpack.StreamUtils; +import com.codepoetics.protonpack.selectors.Selectors; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.LongStream; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; +import static java.util.stream.Collectors.maxBy; +import static java.util.stream.Collectors.toList; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; + +public class StreamUtilsTests { + + @Test + public void givenStream_whenZipWithIndex_shouldReturnZippedStreamWithIndex() { + Stream source = Stream.of("Foo", "Bar", "Baz"); + + List> zipped = StreamUtils + .zipWithIndex(source) + .collect(Collectors.toList()); + + assertThat(zipped, contains(Indexed.index(0, "Foo"), Indexed.index(1, "Bar"), Indexed.index(2, "Baz"))); + } + + @Test + public void givenTwoStreams_whenZip_shouldReturnZippedStream() { + Stream streamA = Stream.of("A", "B", "C"); + Stream streamB = Stream.of("Apple", "Banana", "Carrot"); + + List zipped = StreamUtils + .zip(streamA, streamB, (a, b) -> a + " is for " + b) + .collect(Collectors.toList()); + + assertThat(zipped, contains("A is for Apple", "B is for Banana", "C is for Carrot")); + } + + @Test + public void givenThreeStreams_whenZip_shouldReturnZippedStream() { + Stream streamA = Stream.of("A", "B", "C"); + Stream streamB = Stream.of("aggravating", "banausic", "complaisant"); + Stream streamC = Stream.of("Apple", "Banana", "Carrot"); + + List zipped = StreamUtils + .zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c) + .collect(Collectors.toList()); + + assertThat(zipped, contains("A is for aggravating Apple", "B is for banausic Banana", "C is for complaisant Carrot")); + } + + @Test + //givenThreeStreams_whenMerge_shouldReturnMergedStream + public void givenThreeStreams_whenMerge_shouldReturnMergedStream() { + Stream streamA = Stream.of("A", "B", "C"); + Stream streamB = Stream.of("apple", "banana", "carrot", "date"); + Stream streamC = Stream.of("fritter", "split", "cake", "roll", "pastry"); + + Stream> merged = StreamUtils.mergeToList(streamA, streamB, streamC); + + assertThat(merged.collect(toList()), contains(asList("A", "apple", "fritter"), asList("B", "banana", "split"), asList("C", "carrot", "cake"), asList("date", "roll"), asList("pastry"))); + } + + @Test + //givenThreeStreams_whenInterleave_shouldReturnRoundRobinInterleavingStream + public void givenThreeStreams_whenInterleave_shouldReturnRoundRobinInterleavingStream() { + Stream streamA = Stream.of("Peter", "Paul", "Mary"); + Stream streamB = Stream.of("A", "B", "C", "D", "E"); + Stream streamC = Stream.of("foo", "bar", "baz", "xyzzy"); + + Stream interleaved = StreamUtils.interleave(Selectors.roundRobin(), streamA, streamB, streamC); + + assertThat(interleaved.collect(Collectors.toList()), contains("Peter", "A", "foo", "Paul", "B", "bar", "Mary", "C", "baz", "D", "xyzzy", "E")); + } + + @Test + //givenInfiniteStream_whenTakeWhile10_shouldReturnStreamOfSize10 + public void givenInfiniteStream_whenTakeWhile10_shouldReturnStream() { + Stream infiniteInts = Stream.iterate(0, i -> i + 1); + Stream finiteInts = StreamUtils.takeWhile(infiniteInts, i -> i < 10); + + assertThat(finiteInts.collect(Collectors.toList()), hasSize(10)); + } + + @Test + public void givenInfiniteStream_whenTakeUntil10_shouldReturnStreamUpto10() { + Stream infiniteInts = Stream.iterate(0, i -> i + 1); + Stream finiteInts = StreamUtils.takeUntil(infiniteInts, i -> i > 10); + + assertThat(finiteInts.collect(Collectors.toList()), hasSize(11)); + } + + @Test + public void givenIntegerStreamOfTen_whenSkipWhileLessThanFour_shouldReturnStreamFromFourToTen() { + Stream ints = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + Stream skipped = StreamUtils.skipWhile(ints, i -> i < 4); + List collected = skipped.collect(Collectors.toList()); + + assertThat(collected, contains(4, 5, 6, 7, 8, 9, 10)); + } + + @Test + public void givenIntegerStreamOfTen_whenSkipUntilFour_shouldReturnStreamFromFiveToTen() { + Stream ints = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + Stream skipped = StreamUtils.skipUntil(ints, i -> i > 4); + List collected = skipped.collect(Collectors.toList()); + + assertThat(collected, contains(5, 6, 7, 8, 9, 10)); + } + + @Test + public void givenSeedValue_withUnfold_shouldReturnStreamAccordingToGeneratorMethod() { + Stream unfolded = StreamUtils.unfold(1, i -> (i < 10) ? Optional.of(i + 1) : Optional.empty()); + + assertThat(unfolded.collect(Collectors.toList()), contains(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); + } + + @Test + public void giveIntegerStream_whenGroupRuns_shouldReturnListGroupItems() { + Stream integerStream = Stream.of(1, 1, 2, 2, 3, 4, 5); + List> runs = StreamUtils + .groupRuns(integerStream) + .collect(toList()); + + assertThat(runs, contains(asList(1, 1), asList(2, 2), asList(3), asList(4), asList(5))); + } + + @Test + public void givenAStream_whenAggregate_shouldReturnAggregatedStreamOnTheBasisOfBiFunction() { + Stream stream = Stream.of("a1", "b1", "b2", "c1"); + Stream> aggregated = StreamUtils.aggregate(stream, (e1, e2) -> e1.charAt(0) == e2.charAt(0)); + assertThat(aggregated.collect(toList()), contains(asList("a1"), asList("b1", "b2"), asList("c1"))); + } + + @Test + public void givenIntegerStream_whenWindowed_shouldReturnListOfListOfItemsOfWindowSize() { + Stream integerStream = Stream.of(1, 2, 3, 4, 5); + + List> windows = StreamUtils + .windowed(integerStream, 2) + .collect(toList()); + + assertThat(windows, contains(asList(1, 2), asList(2, 3), asList(3, 4), asList(4, 5))); + } + + @Test + //givenIntegerStream_whenWindowedWithWindowSizeAndSkip_shouldReturnListOfListOfWindowSizeAddingASkip + public void givenIntegerStream_whenWindowedWithWindowSizeAndSkip_shouldReturnListOfListOfWindowSizeAddingASkip() { + Stream integerStream = Stream.of(1, 2, 3, 4, 5); + + List> windows = StreamUtils + .windowed(integerStream, 3, 2) + .collect(toList()); + + assertThat(windows, contains(asList(1, 2, 3), asList(3, 4, 5))); + } + + @Test + public void givenEmptyStream_whenWindowed_shouldReturnIterableWithSizeZero() { + ArrayList ints = new ArrayList<>(); + + ints + .stream() + .collect(maxBy((a, b) -> a + .toString() + .compareTo(b.toString()))); + + List> windows = StreamUtils + .windowed(ints.stream(), 2) + .collect(toList()); + + assertThat(windows, iterableWithSize(0)); + } + + @Test + public void givenIntegerStream_whenWindowedWithWindowSizeAndSkipAndAllowLesserSize_shouldReturnListOfListOfInteger() { + Stream integerStream = Stream.of(1, 2, 3, 4, 5); + + List> windows = StreamUtils + .windowed(integerStream, 2, 2, true) + .collect(toList()); + + assertThat(windows, contains(asList(1, 2), asList(3, 4), asList(5))); + } + + @Test + public void givenLimit_withIndices_shouldReturnLongStreamUptoLimit() { + LongStream indices = StreamUtils + .indices() + .limit(500); + + assertThat(indices.count(), equalTo(500)); + } + +} diff --git a/libraries/src/test/java/com/baeldung/retrofit/basic/GitHubBasicApiLiveTest.java b/libraries/src/test/java/com/baeldung/retrofit/basic/GitHubBasicApiLiveTest.java new file mode 100644 index 0000000000..7170d35aa5 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/retrofit/basic/GitHubBasicApiLiveTest.java @@ -0,0 +1,65 @@ +package com.baeldung.retrofit.basic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.retrofit.basic.GitHubBasicApi; +import com.baeldung.retrofit.models.Contributor; +import com.baeldung.retrofit.models.Repository; + +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class GitHubBasicApiLiveTest { + + GitHubBasicApi gitHub; + + @Before + public void init() { + Retrofit retrofit = new Retrofit.Builder() + .baseUrl("https://api.github.com/") + .addConverterFactory(GsonConverterFactory.create()) + .build(); + + gitHub = retrofit.create(GitHubBasicApi.class); + } + + @Test + public void whenListRepos_thenExpectReposThatContainTutorials() { + try { + List repos = gitHub + .listRepos("eugenp") + .execute() + .body(); + + assertThat(repos) + .isNotEmpty() + .extracting(Repository::getName).contains("tutorials"); + } catch (IOException e) { + fail("Can not communicate with GitHub API"); + } + } + + @Test + public void whenListRepoContributers_thenExpectContributorsThatContainEugenp() { + try { + List contributors = gitHub + .listRepoContributors("eugenp", "tutorials") + .execute() + .body(); + + assertThat(contributors) + .isNotEmpty() + .extracting(Contributor::getName).contains("eugenp"); + } catch (IOException e) { + fail("Can not communicate with GitHub API"); + } + } + +} diff --git a/libraries/src/test/java/com/baeldung/retrofit/rx/GitHubRxApiTest.java b/libraries/src/test/java/com/baeldung/retrofit/rx/GitHubRxApiTest.java new file mode 100644 index 0000000000..c2fbd9bf60 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/retrofit/rx/GitHubRxApiTest.java @@ -0,0 +1,53 @@ +package com.baeldung.retrofit.rx; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.retrofit.models.Contributor; +import com.baeldung.retrofit.models.Repository; +import com.baeldung.retrofit.rx.GitHubRxApi; + +import retrofit2.Retrofit; +import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; +import retrofit2.converter.gson.GsonConverterFactory; + +public class GitHubRxApiTest { + + GitHubRxApi gitHub; + + @Before + public void init() { + Retrofit retrofit = new Retrofit.Builder() + .baseUrl("https://api.github.com/") + .addConverterFactory(GsonConverterFactory.create()) + .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) + .build(); + + gitHub = retrofit.create(GitHubRxApi.class); + } + + @Test + public void whenListRepos_thenExpectReposThatContainTutorials() { + gitHub + .listRepos("eugenp") + .subscribe( repos -> { + assertThat(repos) + .isNotEmpty() + .extracting(Repository::getName).contains("tutorials"); + }); + } + + @Test + public void whenListRepoContributers_thenExpectContributorsThatContainEugenp() { + gitHub + .listRepoContributors("eugenp", "tutorials") + .subscribe(contributors -> { + assertThat(contributors) + .isNotEmpty() + .extracting(Contributor::getName).contains("eugenp"); + }); + } + +} diff --git a/libraries/src/test/resources/ABC.txt b/libraries/src/test/resources/ABC.txt new file mode 100644 index 0000000000..f78e42598c --- /dev/null +++ b/libraries/src/test/resources/ABC.txt @@ -0,0 +1 @@ +Hello World from ABC.txt!!! \ No newline at end of file diff --git a/libraries/src/test/resources/aaa.txt b/libraries/src/test/resources/aaa.txt new file mode 100644 index 0000000000..e5875f97d6 --- /dev/null +++ b/libraries/src/test/resources/aaa.txt @@ -0,0 +1 @@ +Hello World from aaa.txt!!! \ No newline at end of file diff --git a/libraries/src/test/resources/fileTest.txt b/libraries/src/test/resources/fileTest.txt new file mode 100644 index 0000000000..ce4bea208b --- /dev/null +++ b/libraries/src/test/resources/fileTest.txt @@ -0,0 +1 @@ +Hello World from fileTest.txt!!! \ No newline at end of file diff --git a/libraries/src/test/resources/sample.txt b/libraries/src/test/resources/sample.txt new file mode 100644 index 0000000000..20f137b416 --- /dev/null +++ b/libraries/src/test/resources/sample.txt @@ -0,0 +1,2 @@ +line 1 +a second line \ No newline at end of file diff --git a/linkrest/WebContent/META-INF/MANIFEST.MF b/linkrest/WebContent/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..254272e1c0 --- /dev/null +++ b/linkrest/WebContent/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/linkrest/WebContent/WEB-INF/web.xml b/linkrest/WebContent/WEB-INF/web.xml new file mode 100644 index 0000000000..046c82b08a --- /dev/null +++ b/linkrest/WebContent/WEB-INF/web.xml @@ -0,0 +1,20 @@ + + + linkrest + + linkrest + org.glassfish.jersey.servlet.ServletContainer + + javax.ws.rs.Application + com.baeldung.LinkRestApplication + + 1 + + + linkrest + /* + + \ No newline at end of file diff --git a/linkrest/pom.xml b/linkrest/pom.xml new file mode 100644 index 0000000000..aa2f0f8bda --- /dev/null +++ b/linkrest/pom.xml @@ -0,0 +1,81 @@ + + 4.0.0 + com.baeldung + linkrest + 0.0.1-SNAPSHOT + war + + + + com.nhl.link.rest + link-rest + ${linkrest.version} + + + org.glassfish.jersey.containers + jersey-container-servlet + ${jersey.version} + + + org.glassfish.jersey.media + jersey-media-moxy + ${jersey.version} + + + com.h2database + h2 + ${h2.version} + + + + + + + maven-compiler-plugin + 3.5 + + 1.8 + 1.8 + + + + maven-war-plugin + 2.6 + + WebContent + false + + + + org.apache.cayenne.plugins + cayenne-maven-plugin + ${cayenne.version} + + + ${project.basedir}/src/main/resources/linkrest.map.xml + + + + + + cgen + + + + + + org.apache.cayenne.plugins + cayenne-modeler-maven-plugin + ${cayenne.version} + + + + + + 2.9 + 4.0.B1 + 1.4.196 + 2.25.1 + + \ No newline at end of file diff --git a/linkrest/src/main/java/com/baeldung/LinkRestApplication.java b/linkrest/src/main/java/com/baeldung/LinkRestApplication.java new file mode 100644 index 0000000000..7a2f7c8903 --- /dev/null +++ b/linkrest/src/main/java/com/baeldung/LinkRestApplication.java @@ -0,0 +1,24 @@ +package com.baeldung; + + +import javax.ws.rs.ApplicationPath; + +import org.apache.cayenne.configuration.server.ServerRuntime; +import org.glassfish.jersey.server.ResourceConfig; + +import com.nhl.link.rest.runtime.LinkRestBuilder; +import com.nhl.link.rest.runtime.LinkRestRuntime; + +@ApplicationPath("/linkrest") +public class LinkRestApplication extends ResourceConfig { + + public LinkRestApplication() { + ServerRuntime cayenneRuntime = ServerRuntime.builder() + .addConfig("cayenne-linkrest-project.xml") + .build(); + LinkRestRuntime lrRuntime = LinkRestBuilder.build(cayenneRuntime); + super.register(lrRuntime); + packages("com.baeldung.linkrest.apis"); + } + +} diff --git a/linkrest/src/main/java/com/baeldung/cayenne/Department.java b/linkrest/src/main/java/com/baeldung/cayenne/Department.java new file mode 100644 index 0000000000..ed7a2bd795 --- /dev/null +++ b/linkrest/src/main/java/com/baeldung/cayenne/Department.java @@ -0,0 +1,9 @@ +package com.baeldung.cayenne; + +import com.baeldung.cayenne.auto._Department; + +public class Department extends _Department { + + private static final long serialVersionUID = 1L; + +} diff --git a/linkrest/src/main/java/com/baeldung/cayenne/Employee.java b/linkrest/src/main/java/com/baeldung/cayenne/Employee.java new file mode 100644 index 0000000000..632ea4fbf9 --- /dev/null +++ b/linkrest/src/main/java/com/baeldung/cayenne/Employee.java @@ -0,0 +1,9 @@ +package com.baeldung.cayenne; + +import com.baeldung.cayenne.auto._Employee; + +public class Employee extends _Employee { + + private static final long serialVersionUID = 1L; + +} diff --git a/linkrest/src/main/java/com/baeldung/cayenne/auto/_Department.java b/linkrest/src/main/java/com/baeldung/cayenne/auto/_Department.java new file mode 100644 index 0000000000..4111a8c8b2 --- /dev/null +++ b/linkrest/src/main/java/com/baeldung/cayenne/auto/_Department.java @@ -0,0 +1,44 @@ +package com.baeldung.cayenne.auto; + +import java.util.List; + +import org.apache.cayenne.CayenneDataObject; +import org.apache.cayenne.exp.Property; + +import com.baeldung.cayenne.Employee; + +/** + * Class _Department was generated by Cayenne. + * It is probably a good idea to avoid changing this class manually, + * since it may be overwritten next time code is regenerated. + * If you need to make any customizations, please use subclass. + */ +public abstract class _Department extends CayenneDataObject { + + private static final long serialVersionUID = 1L; + + public static final String DEP_ID_PK_COLUMN = "dep_id"; + + public static final Property NAME = Property.create("name", String.class); + public static final Property> EMPLOYEES = Property.create("employees", List.class); + + public void setName(String name) { + writeProperty("name", name); + } + public String getName() { + return (String)readProperty("name"); + } + + public void addToEmployees(Employee obj) { + addToManyTarget("employees", obj, true); + } + public void removeFromEmployees(Employee obj) { + removeToManyTarget("employees", obj, true); + } + @SuppressWarnings("unchecked") + public List getEmployees() { + return (List)readProperty("employees"); + } + + +} diff --git a/linkrest/src/main/java/com/baeldung/cayenne/auto/_Employee.java b/linkrest/src/main/java/com/baeldung/cayenne/auto/_Employee.java new file mode 100644 index 0000000000..50e1880a56 --- /dev/null +++ b/linkrest/src/main/java/com/baeldung/cayenne/auto/_Employee.java @@ -0,0 +1,39 @@ +package com.baeldung.cayenne.auto; + +import org.apache.cayenne.CayenneDataObject; +import org.apache.cayenne.exp.Property; + +import com.baeldung.cayenne.Department; + +/** + * Class _Employee was generated by Cayenne. + * It is probably a good idea to avoid changing this class manually, + * since it may be overwritten next time code is regenerated. + * If you need to make any customizations, please use subclass. + */ +public abstract class _Employee extends CayenneDataObject { + + private static final long serialVersionUID = 1L; + + public static final String EMP_ID_PK_COLUMN = "emp_id"; + + public static final Property NAME = Property.create("name", String.class); + public static final Property DEPARTMENT = Property.create("department", Department.class); + + public void setName(String name) { + writeProperty("name", name); + } + public String getName() { + return (String)readProperty("name"); + } + + public void setDepartment(Department department) { + setToOneTarget("department", department, true); + } + + public Department getDepartment() { + return (Department)readProperty("department"); + } + + +} diff --git a/linkrest/src/main/java/com/baeldung/linkrest/apis/DepartmentResource.java b/linkrest/src/main/java/com/baeldung/linkrest/apis/DepartmentResource.java new file mode 100644 index 0000000000..f4090b580e --- /dev/null +++ b/linkrest/src/main/java/com/baeldung/linkrest/apis/DepartmentResource.java @@ -0,0 +1,58 @@ +package com.baeldung.linkrest.apis; + +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Configuration; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import com.baeldung.cayenne.Department; +import com.nhl.link.rest.DataResponse; +import com.nhl.link.rest.LinkRest; +import com.nhl.link.rest.SimpleResponse; + +@Path("department") +@Produces(MediaType.APPLICATION_JSON) +public class DepartmentResource { + + @Context + private Configuration config; + + @GET + public DataResponse getAll(@Context UriInfo uriInfo) { + return LinkRest.select(Department.class, config).uri(uriInfo).get(); + } + + @GET + @Path("{id}") + public DataResponse getOne(@PathParam("id") int id, @Context UriInfo uriInfo) { + return LinkRest.select(Department.class, config).byId(id).uri(uriInfo).getOne(); + } + + @POST + public SimpleResponse create(String data) { + return LinkRest.create(Department.class, config).sync(data); + } + + @PUT + public SimpleResponse createOrUpdate(String data) { + return LinkRest.createOrUpdate(Department.class, config).sync(data); + } + + @Path("{id}/employees") + public EmployeeSubResource getEmployees(@PathParam("id") int id, @Context UriInfo uriInfo) { + return new EmployeeSubResource(id, config); + } + + @DELETE + @Path("{id}") + public SimpleResponse delete(@PathParam("id") int id) { + return LinkRest.delete(Department.class, config).id(id).delete(); + } +} diff --git a/linkrest/src/main/java/com/baeldung/linkrest/apis/EmployeeSubResource.java b/linkrest/src/main/java/com/baeldung/linkrest/apis/EmployeeSubResource.java new file mode 100644 index 0000000000..ba9c3759bb --- /dev/null +++ b/linkrest/src/main/java/com/baeldung/linkrest/apis/EmployeeSubResource.java @@ -0,0 +1,65 @@ +package com.baeldung.linkrest.apis; + +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Configuration; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import com.baeldung.cayenne.Department; +import com.baeldung.cayenne.Employee; +import com.nhl.link.rest.DataResponse; +import com.nhl.link.rest.LinkRest; +import com.nhl.link.rest.SimpleResponse; + +@Produces(MediaType.APPLICATION_JSON) +public class EmployeeSubResource { + + private Configuration config; + + private int departmentId; + + public EmployeeSubResource(int departmentId, Configuration config) { + this.departmentId = departmentId; + this.config = config; + } + + public EmployeeSubResource() { + } + + @GET + public DataResponse getAll(@Context UriInfo uriInfo) { + return LinkRest.select(Employee.class, config).toManyParent(Department.class, departmentId, Department.EMPLOYEES).uri(uriInfo).get(); + } + + @GET + @Path("{id}") + public DataResponse getOne(@PathParam("id") int id, @Context UriInfo uriInfo) { + return LinkRest.select(Employee.class, config).toManyParent(Department.class, departmentId, Department.EMPLOYEES).byId(id).uri(uriInfo).getOne(); + } + + @POST + public SimpleResponse create(String data) { + + return LinkRest.create(Employee.class, config).toManyParent(Department.class, departmentId, Department.EMPLOYEES).sync(data); + } + + @PUT + public SimpleResponse createOrUpdate(String data) { + return LinkRest.create(Employee.class, config).toManyParent(Department.class, departmentId, Department.EMPLOYEES).sync(data); + } + + @DELETE + @Path("{id}") + public SimpleResponse delete(@PathParam("id") int id) { + return LinkRest.delete(Employee.class, config).toManyParent(Department.class, departmentId, Department.EMPLOYEES).id(id).delete(); + + } + +} diff --git a/linkrest/src/main/resources/cayenne-linkrest-project.xml b/linkrest/src/main/resources/cayenne-linkrest-project.xml new file mode 100644 index 0000000000..8a4ba39c4d --- /dev/null +++ b/linkrest/src/main/resources/cayenne-linkrest-project.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + diff --git a/linkrest/src/main/resources/linkrest.map.xml b/linkrest/src/main/resources/linkrest.map.xml new file mode 100644 index 0000000000..105d7d9d14 --- /dev/null +++ b/linkrest/src/main/resources/linkrest.map.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/log4j2/README.md b/log4j2/README.md index 3afd842c82..57ca4df21b 100644 --- a/log4j2/README.md +++ b/log4j2/README.md @@ -1,3 +1,4 @@ ### Relevant articles - [Intro to Log4j2 – Appenders, Layouts and Filters](http://www.baeldung.com/log4j2-appenders-layouts-filters) +- [Log4j 2 and Lambda Expressions](http://www.baeldung.com/log4j-2-lazy-logging) diff --git a/lombok/pom.xml b/lombok/pom.xml index 472516de4d..bea05b38f3 100644 --- a/lombok/pom.xml +++ b/lombok/pom.xml @@ -6,8 +6,6 @@ 4.0.0 lombok - - com.baeldung lombok 0.1-SNAPSHOT @@ -81,7 +79,7 @@ UTF-8 - 1.16.12 + 1.16.18 1.0.0.Final diff --git a/mapstruct/pom.xml b/mapstruct/pom.xml index 17cf882d2b..ba67ccc2df 100644 --- a/mapstruct/pom.xml +++ b/mapstruct/pom.xml @@ -5,7 +5,6 @@ 4.0.0 mapstruct mapstruct - com.baeldung 1.0 jar diff --git a/mocks/mock-comparisons/pom.xml b/mocks/mock-comparisons/pom.xml index e350457f54..11bc59d710 100644 --- a/mocks/mock-comparisons/pom.xml +++ b/mocks/mock-comparisons/pom.xml @@ -13,9 +13,9 @@ mock-comparisons - 2.8.9 + 2.9.0 3.4 - 1.29 + 1.34 UTF-8 diff --git a/mustache/pom.xml b/mustache/pom.xml index d5d80b58e9..8aab038313 100644 --- a/mustache/pom.xml +++ b/mustache/pom.xml @@ -8,9 +8,11 @@ mustache - com.baeldung - parent-modules - 1.0.0-SNAPSHOT + org.springframework.boot + spring-boot-starter-parent + 1.5.4.RELEASE + + @@ -32,6 +34,28 @@ log4j ${log4j.version} + + + org.springframework.boot + spring-boot-starter-mustache + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.webjars + bootstrap + 3.3.7 + + + org.fluttercode.datafactory + datafactory + 0.8 + + junit junit @@ -41,6 +65,102 @@ + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + true + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/AutoconfigurationTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + + 0.9.2 3.7.0 @@ -52,6 +172,8 @@ 3.6.0 2.19.1 + + 1.8 \ No newline at end of file diff --git a/mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java b/mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java new file mode 100644 index 0000000000..8cdf89d08a --- /dev/null +++ b/mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java @@ -0,0 +1,32 @@ +package com.baeldung.springmustache; + +import com.samskivert.mustache.Mustache; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.mustache.MustacheEnvironmentCollector; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.core.env.Environment; + +@SpringBootApplication +@ComponentScan(basePackages = {"com.baeldung"}) +public class SpringMustacheApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringMustacheApplication.class, args); + } + + @Bean + public Mustache.Compiler mustacheCompiler(Mustache.TemplateLoader templateLoader, Environment environment) { + + MustacheEnvironmentCollector collector = new MustacheEnvironmentCollector(); + collector.setEnvironment(environment); + + return Mustache.compiler() + .defaultValue("Some Default Value") + .withLoader(templateLoader) + .withCollector(collector); + + } +} + diff --git a/mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java b/mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java new file mode 100644 index 0000000000..880fb337fd --- /dev/null +++ b/mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java @@ -0,0 +1,42 @@ +package com.baeldung.springmustache.controller; + +import com.baeldung.springmustache.model.Article; +import org.fluttercode.datafactory.impl.DataFactory; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.servlet.ModelAndView; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +@Controller +public class ArticleController { + + @GetMapping("/article") + public ModelAndView displayArticle(Map model) { + + List
articles = IntStream.range(0, 10) + .mapToObj(i -> generateArticle("Article Title " + i)) + .collect(Collectors.toList()); + + model.put("articles", articles); + + return new ModelAndView("index", model); + } + + private Article generateArticle(String title) { + Article article = new Article(); + DataFactory factory = new DataFactory(); + article.setTitle(title); + article.setBody( + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur faucibus tempor diam. In molestie arcu eget ante facilisis sodales. Maecenas porta tellus sapien, eget rutrum nisi blandit in. Mauris tempor auctor ante, ut blandit velit venenatis id. Ut varius, augue aliquet feugiat congue, arcu ipsum finibus purus, dapibus semper velit sapien venenatis magna. Nunc quam ex, aliquet at rutrum sed, vestibulum quis libero. In laoreet libero cursus maximus vulputate. Nullam in fermentum sem. Duis aliquam ullamcorper dui, et dictum justo placerat id. Aliquam pretium orci quis sapien convallis, non blandit est tempus."); + article.setPublishDate(factory.getBirthDate().toString()); + article.setAuthor(factory.getName()); + return article; + } +} + + diff --git a/mustache/src/main/java/com/baeldung/springmustache/model/Article.java b/mustache/src/main/java/com/baeldung/springmustache/model/Article.java new file mode 100644 index 0000000000..78b08f877f --- /dev/null +++ b/mustache/src/main/java/com/baeldung/springmustache/model/Article.java @@ -0,0 +1,41 @@ +package com.baeldung.springmustache.model; + +public class Article { + private String title; + private String body; + private String author; + private String publishDate; + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getPublishDate() { + return publishDate; + } + + public void setPublishDate(String publishDate) { + this.publishDate = publishDate; + } + +} diff --git a/mustache/src/main/resources/application.properties b/mustache/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/mustache/src/main/resources/templates/error/error.html b/mustache/src/main/resources/templates/error/error.html new file mode 100644 index 0000000000..fa29db41c4 --- /dev/null +++ b/mustache/src/main/resources/templates/error/error.html @@ -0,0 +1,9 @@ + + + + + + Something went wrong: {{status}} {{error}} + + + \ No newline at end of file diff --git a/mustache/src/main/resources/templates/index.html b/mustache/src/main/resources/templates/index.html new file mode 100644 index 0000000000..bda60f9d8f --- /dev/null +++ b/mustache/src/main/resources/templates/index.html @@ -0,0 +1,9 @@ +{{>layout/header}} + +
{{>layout/article}}
+ + + + +{{>layout/footer}} diff --git a/mustache/src/main/resources/templates/layout/article.html b/mustache/src/main/resources/templates/layout/article.html new file mode 100644 index 0000000000..9d573580d3 --- /dev/null +++ b/mustache/src/main/resources/templates/layout/article.html @@ -0,0 +1,8 @@ +
+ {{#articles}} +

{{title}}

+

{{publishDate}}

+

{{author}}

+

{{body}}

+ {{/articles}} +
\ No newline at end of file diff --git a/mustache/src/main/resources/templates/layout/footer.html b/mustache/src/main/resources/templates/layout/footer.html new file mode 100644 index 0000000000..04f34cac54 --- /dev/null +++ b/mustache/src/main/resources/templates/layout/footer.html @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/mustache/src/main/resources/templates/layout/header.html b/mustache/src/main/resources/templates/layout/header.html new file mode 100644 index 0000000000..d203ef800b --- /dev/null +++ b/mustache/src/main/resources/templates/layout/header.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/mustache/src/test/java/com/baeldung/mustache/TodoMustacheServiceTest.java b/mustache/src/test/java/com/baeldung/mustache/TodoMustacheServiceTest.java index 17a59aa6a1..0df2f7f8a4 100644 --- a/mustache/src/test/java/com/baeldung/mustache/TodoMustacheServiceTest.java +++ b/mustache/src/test/java/com/baeldung/mustache/TodoMustacheServiceTest.java @@ -1,100 +1,98 @@ package com.baeldung.mustache; -import static org.assertj.core.api.Assertions.assertThat; +import com.baeldung.mustache.model.Todo; +import com.github.mustachejava.Mustache; +import org.junit.Test; import java.io.IOException; import java.io.StringWriter; import java.time.Instant; -import java.time.LocalDateTime; -import java.time.temporal.TemporalUnit; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.function.Function; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; -import com.baeldung.mustache.model.Todo; -import com.github.mustachejava.Mustache; public class TodoMustacheServiceTest { - private String executeTemplate(Mustache m, Map context) throws IOException{ + private String executeTemplate(Mustache m, Map context) throws IOException { StringWriter writer = new StringWriter(); m.execute(writer, context).flush(); return writer.toString(); } - - private String executeTemplate(Mustache m, Todo todo) throws IOException{ + + private String executeTemplate(Mustache m, Todo todo) throws IOException { StringWriter writer = new StringWriter(); m.execute(writer, todo).flush(); return writer.toString(); } - + @Test - public void givenTodoObject_whenGetHtml_thenSuccess() throws IOException{ + public void givenTodoObject_whenGetHtml_thenSuccess() throws IOException { Todo todo = new Todo("Todo 1", "Todo description"); Mustache m = MustacheUtil.getMustacheFactory().compile("todo.mustache"); Map context = new HashMap<>(); context.put("todo", todo); - + String expected = "

Todo 1

"; assertThat(executeTemplate(m, todo)).contains(expected); } - + @Test - public void givenNullTodoObject_whenGetHtml_thenEmptyHtml() throws IOException{ + public void givenNullTodoObject_whenGetHtml_thenEmptyHtml() throws IOException { Mustache m = MustacheUtil.getMustacheFactory().compile("todo-section.mustache"); Map context = new HashMap<>(); assertThat(executeTemplate(m, context)).isEmpty(); } - + @Test - public void givenTodoList_whenGetHtml_thenSuccess() throws IOException{ + public void givenTodoList_whenGetHtml_thenSuccess() throws IOException { Mustache m = MustacheUtil.getMustacheFactory().compile("todos.mustache"); - + List todos = Arrays.asList( - new Todo("Todo 1", "Todo description"), - new Todo("Todo 2", "Todo description another"), - new Todo("Todo 3", "Todo description another") - ); + new Todo("Todo 1", "Todo description"), + new Todo("Todo 2", "Todo description another"), + new Todo("Todo 3", "Todo description another") + ); Map context = new HashMap<>(); context.put("todos", todos); - + assertThat(executeTemplate(m, context)) .contains("

Todo 1

") .contains("

Todo 2

") .contains("

Todo 3

"); } - + @Test - public void givenEmptyList_whenGetHtml_thenEmptyHtml() throws IOException{ + public void givenEmptyList_whenGetHtml_thenEmptyHtml() throws IOException { Mustache m = MustacheUtil.getMustacheFactory().compile("todos.mustache"); - + Map context = new HashMap<>(); - assertThat(executeTemplate(m, context)).isEmpty();; + assertThat(executeTemplate(m, context)).isEmpty(); + ; } - + @Test - public void givenEmptyList_whenGetHtmlUsingInvertedSection_thenHtml() throws IOException{ + public void givenEmptyList_whenGetHtmlUsingInvertedSection_thenHtml() throws IOException { Mustache m = MustacheUtil.getMustacheFactory().compile("todos-inverted-section.mustache"); - + Map context = new HashMap<>(); assertThat(executeTemplate(m, context).trim()).isEqualTo("

No todos!

"); } - + @Test - public void givenTodoList_whenGetHtmlUsingLamdba_thenHtml() throws IOException{ + public void givenTodoList_whenGetHtmlUsingLamdba_thenHtml() throws IOException { Mustache m = MustacheUtil.getMustacheFactory().compile("todos-lambda.mustache"); List todos = Arrays.asList( - new Todo("Todo 1", "Todo description"), - new Todo("Todo 2", "Todo description another"), - new Todo("Todo 3", "Todo description another") - ); + new Todo("Todo 1", "Todo description"), + new Todo("Todo 2", "Todo description another"), + new Todo("Todo 3", "Todo description another") + ); todos.get(2).setDone(true); todos.get(2).setCompletedOn(Date.from(Instant.now().plusSeconds(300))); - + Map context = new HashMap<>(); context.put("todos", todos); assertThat(executeTemplate(m, context).trim()).contains("Done 5 minutes ago"); diff --git a/mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationIntegrationTest.java b/mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationIntegrationTest.java new file mode 100644 index 0000000000..1eecf58986 --- /dev/null +++ b/mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationIntegrationTest.java @@ -0,0 +1,30 @@ +package com.baeldung.springmustache; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringMustacheApplicationIntegrationTest { + + @Autowired + private TestRestTemplate restTemplate; + + @Test + public void givenIndexPageWhenContainsArticleThenTrue() { + + ResponseEntity entity = this.restTemplate.getForEntity("/article", String.class); + + Assert.assertTrue(entity.getStatusCode().equals(HttpStatus.OK)); + Assert.assertTrue(entity.getBody().contains("Article Title 0")); + } + +} diff --git a/pom.xml b/pom.xml index 1804ff1166..015efbab05 100644 --- a/pom.xml +++ b/pom.xml @@ -45,11 +45,13 @@ core-java core-java-8 core-java-concurrency - couchbase-sdk + couchbase deltaspike dozer + ethereumj + feign @@ -57,7 +59,7 @@ - + geotools groovy-spock gson guava @@ -95,7 +97,8 @@ jws libraries - libraries-data + libraries-data + linkrest log-mdc log4j log4j2 @@ -125,6 +128,7 @@ rest-testing resteasy rxjava + spring-swagger-codegen selenium-junit-testng solr @@ -241,6 +245,7 @@ spring-boot-property-exp mockserver undertow + vertx-and-rxjava diff --git a/ratpack/README.md b/ratpack/README.md index 8215f74148..02b91da0bd 100644 --- a/ratpack/README.md +++ b/ratpack/README.md @@ -3,3 +3,5 @@ - [Introduction to Ratpack](http://www.baeldung.com/ratpack) - [Ratpack Google Guice Integration](http://www.baeldung.com/ratpack-google-guice) - [Ratpack Integration with Spring Boot](http://www.baeldung.com/ratpack-spring-boot) +- [Ratpack with Hystrix](http://www.baeldung.com/ratpack-hystrix) + diff --git a/rxjava/README.md b/rxjava/README.md index 7670dd4ed3..c7fd0c595d 100644 --- a/rxjava/README.md +++ b/rxjava/README.md @@ -2,3 +2,4 @@ - [Dealing with Backpressure with RxJava](http://www.baeldung.com/rxjava-backpressure) - [How to Test RxJava?](http://www.baeldung.com/rxjava-testing) +- [Implementing Custom Operators in RxJava](http://www.baeldung.com/rxjava-custom-operators) diff --git a/rxjava/pom.xml b/rxjava/pom.xml index 578eda3fcf..bf5f073d8d 100644 --- a/rxjava/pom.xml +++ b/rxjava/pom.xml @@ -19,6 +19,18 @@ rxjava ${rx.java.version} + + + io.reactivex.rxjava2 + rxjava + 2.1.3 + + + + com.jayway.awaitility + awaitility + 1.7.0 + diff --git a/rxjava/src/main/java/com/baelding/rxjava/ConnectableObservableImpl.java b/rxjava/src/main/java/com/baelding/rxjava/ConnectableObservableImpl.java new file mode 100644 index 0000000000..005487dae8 --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/ConnectableObservableImpl.java @@ -0,0 +1,22 @@ +package com.baelding.rxjava; + +import rx.Observable; +import rx.observables.ConnectableObservable; + +import java.util.concurrent.TimeUnit; + +public class ConnectableObservableImpl { + + public static void main(String[] args) throws InterruptedException { + + ConnectableObservable connectable + = Observable.interval(200, TimeUnit.MILLISECONDS).publish(); + connectable.subscribe(System.out::println); + + System.out.println("Connect"); + connectable.connect(); + + Thread.sleep(500); + System.out.println("Sleep"); + } +} diff --git a/rxjava/src/main/java/com/baelding/rxjava/ObservableImpl.java b/rxjava/src/main/java/com/baelding/rxjava/ObservableImpl.java new file mode 100644 index 0000000000..9ab0d0e1e6 --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/ObservableImpl.java @@ -0,0 +1,81 @@ +package com.baelding.rxjava; + +import rx.Observable; +import rx.observables.BlockingObservable; + +import java.util.Arrays; +import java.util.List; + +public class ObservableImpl { + + static Integer[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + + static String[] letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i"}; + static String[] titles = {"title"}; + public static List titleList = Arrays.asList(titles); + + public static Observable getTitle() { + return Observable.from(titleList); + } + + public static void main(String[] args) { + + System.out.println("-------Just-----------"); + Observable observable = Observable.just("Hello"); + observable.subscribe( + System.out::println, //onNext + Throwable::printStackTrace, //onError + () -> System.out.println("onCompleted") //onCompleted + ); + + BlockingObservable blockingObservable = observable.toBlocking(); + + System.out.println(); + System.out.println("-------Map-----------"); + Observable.from(letters) + .map(String::toUpperCase) + .subscribe(System.out::print); + + System.out.println(); + System.out.println("-------FlatMap-----------"); + Observable.just("book1", "book2") + .flatMap(s -> getTitle()) + .subscribe(System.out::print); + + System.out.println(); + System.out.println("--------Scan----------"); + Observable.from(letters) + .scan(new StringBuilder(), StringBuilder::append) + .subscribe(System.out::println); + + System.out.println(); + System.out.println("------GroubBy------------"); + Observable.from(numbers) + .groupBy(i -> 0 == (i % 2) ? "EVEN" : "ODD") + .subscribe((group) -> group.subscribe((number) -> { + System.out.println(group.getKey() + " : " + number); + })); + + System.out.println(); + System.out.println("-------Filter-----------"); + Observable.from(numbers) + .filter(i -> (i % 2 == 1)) + .subscribe(System.out::println); + + System.out.println("------DefaultIfEmpty------------"); + Observable.empty() + .defaultIfEmpty("Observable is empty") + .subscribe(System.out::println); + + System.out.println("------DefaultIfEmpty-2-----------"); + Observable.from(letters) + .defaultIfEmpty("Observable is empty") + .first() + .subscribe(System.out::println); + + System.out.println("-------TakeWhile-----------"); + Observable.from(numbers) + .takeWhile(i -> i < 5) + .subscribe(System.out::println); + } +} \ No newline at end of file diff --git a/rxjava/src/main/java/com/baelding/rxjava/ResourceManagement.java b/rxjava/src/main/java/com/baelding/rxjava/ResourceManagement.java new file mode 100644 index 0000000000..44bbd7edda --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/ResourceManagement.java @@ -0,0 +1,30 @@ +package com.baelding.rxjava; + +import rx.Observable; + +public class ResourceManagement { + + public static void main(String[] args) { + + Observable values = Observable.using( + () -> { + String resource = "MyResource"; + System.out.println("Leased: " + resource); + return resource; + }, + r -> Observable.create(o -> { + for (Character c : r.toCharArray()) { + o.onNext(c); + } + o.onCompleted(); + }), + r -> System.out.println("Disposed: " + r) + ); + + values.subscribe( + System.out::println, + System.out::println + ); + } +} + diff --git a/rxjava/src/main/java/com/baelding/rxjava/SingleImpl.java b/rxjava/src/main/java/com/baelding/rxjava/SingleImpl.java new file mode 100644 index 0000000000..f625ab6b44 --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/SingleImpl.java @@ -0,0 +1,18 @@ +package com.baelding.rxjava; + +import rx.Observable; +import rx.Single; + +public class SingleImpl { + + public static void main(String[] args) { + + Single single = Observable.just("Hello") + .toSingle() + .doOnSuccess(System.out::print) + .doOnError(e -> { + throw new RuntimeException(e.getMessage()); + }); + single.subscribe(); + } +} diff --git a/rxjava/src/main/java/com/baelding/rxjava/SubjectImpl.java b/rxjava/src/main/java/com/baelding/rxjava/SubjectImpl.java new file mode 100644 index 0000000000..aac9b4454a --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/SubjectImpl.java @@ -0,0 +1,73 @@ +package com.baelding.rxjava; + +import rx.Observer; +import rx.subjects.PublishSubject; + +public class SubjectImpl { + + public static Integer subscriber1 = 0; + public static Integer subscriber2 = 0; + + public static Integer subjectMethod() { + PublishSubject subject = PublishSubject.create(); + + subject.subscribe(getFirstObserver()); + + subject.onNext(1); + subject.onNext(2); + subject.onNext(3); + + subject.subscribe(getSecondObserver()); + + subject.onNext(4); + subject.onCompleted(); + return subscriber1 + subscriber2; + } + + + public static Observer getFirstObserver() { + return new Observer() { + + @Override + public void onNext(Integer value) { + subscriber1 += value; + System.out.println("Subscriber1: " + value); + } + + @Override + public void onError(Throwable e) { + System.out.println("error"); + } + + @Override + public void onCompleted() { + System.out.println("Subscriber1 completed"); + } + }; + } + + public static Observer getSecondObserver() { + return new Observer() { + + @Override + public void onNext(Integer value) { + subscriber2 += value; + System.out.println("Subscriber2: " + value); + } + + @Override + public void onError(Throwable e) { + System.out.println("error"); + } + + @Override + public void onCompleted() { + System.out.println("Subscriber2 completed"); + } + }; + } + + public static void main(String[] args) throws InterruptedException { + System.out.println(subjectMethod()); + } +} diff --git a/rxjava/src/main/java/com/baelding/rxjava/operator/ToCleanString.java b/rxjava/src/main/java/com/baelding/rxjava/operator/ToCleanString.java index f6cf9fba68..32db92c8fe 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/operator/ToCleanString.java +++ b/rxjava/src/main/java/com/baelding/rxjava/operator/ToCleanString.java @@ -39,5 +39,4 @@ public class ToCleanString implements Operator { } }; } - } \ No newline at end of file diff --git a/rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableTest.java b/rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableTest.java new file mode 100644 index 0000000000..031ff0c5bb --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableTest.java @@ -0,0 +1,27 @@ +package com.baeldung.rxjava; + +import org.junit.Test; +import rx.Observable; +import rx.observables.ConnectableObservable; + +import java.util.concurrent.TimeUnit; + +import static com.jayway.awaitility.Awaitility.await; +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertTrue; + +public class ConnectableObservableTest { + + @Test + public void givenConnectableObservable_whenConnect_thenGetMessage() throws InterruptedException { + String[] result = {""}; + ConnectableObservable connectable + = Observable.interval(500, TimeUnit.MILLISECONDS).publish(); + connectable.subscribe(i -> result[0] += i); + assertFalse(result[0].equals("01")); + + connectable.connect(); + await() + .until(() -> assertTrue(result[0].equals("01"))); + } +} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/ObservableTest.java b/rxjava/src/test/java/com/baeldung/rxjava/ObservableTest.java new file mode 100644 index 0000000000..08fccfb238 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/ObservableTest.java @@ -0,0 +1,145 @@ +package com.baeldung.rxjava; + +import org.junit.Test; +import rx.Observable; + +import static com.baelding.rxjava.ObservableImpl.getTitle; +import static junit.framework.Assert.assertTrue; + +public class ObservableTest { + + String result = ""; + + @Test + public void givenString_whenJustAndSubscribe_thenEmitsSingleItem() { + Observable observable = Observable.just("Hello"); + observable.subscribe(s -> result = s); + assertTrue(result.equals("Hello")); + } + + @Test + public void givenArray_whenFromAndSubscribe_thenEmitsItems() { + String[] letters = {"a", "b", "c", "d", "e", "f", "g"}; + Observable observable = Observable.from(letters); + observable.subscribe( + i -> result += i, + Throwable::printStackTrace, + () -> result += "_Complete" + ); + assertTrue(result.equals("abcdefg_Complete")); + } + + @Test + public void givenArray_whenConvertsObservabletoBlockingObservable_thenReturnFirstElement() { + String[] letters = {"a", "b", "c", "d", "e", "f", "g"}; + Observable observable = Observable.from(letters); + String blockingObservable = observable.toBlocking().first(); + + observable.subscribe( + i -> result += i, + Throwable::printStackTrace, + () -> result += "_Completed" + ); + assertTrue(String.valueOf(result.charAt(0)).equals(blockingObservable)); + } + + @Test + public void givenArray_whenMapAndSubscribe_thenReturnCapitalLetters() { + String[] letters = {"a", "b", "c", "d", "e", "f", "g"}; + + Observable.from(letters) + .map(String::toUpperCase) + .subscribe(letter -> result += letter); + + assertTrue(result.equals("ABCDEFG")); + } + + @Test + public void givenArray_whenFlatMapAndSubscribe_thenReturnUpperAndLowerCaseLetters() { + + Observable.just("book1", "book2") + .flatMap(s -> getTitle()) + .subscribe(l -> result += l); + + assertTrue(result.equals("titletitle")); + } + + @Test + public void givenArray_whenScanAndSubscribe_thenReturnTheSumOfAllLetters() { + String[] letters = {"a", "b", "c"}; + + Observable.from(letters) + .scan(new StringBuilder(), StringBuilder::append) + .subscribe(total -> result += total.toString()); + + assertTrue(result.equals("aababc")); + } + + @Test + public void givenArrayOfNumbers_whenGroupBy_thenCreateTwoGroupsBasedOnParity() { + Integer[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + String[] EVEN = {""}; + String[] ODD = {""}; + + Observable.from(numbers) + .groupBy(i -> 0 == (i % 2) ? "EVEN" : "ODD") + .subscribe(group -> + group.subscribe((number) -> { + if (group.getKey().toString().equals("EVEN")) { + EVEN[0] += number; + } else { + ODD[0] += number; + } + }) + ); + + assertTrue(EVEN[0].equals("0246810")); + assertTrue(ODD[0].equals("13579")); + } + + @Test + public void givenArrayOfNumbers_whenFilter_thenGetAllOddNumbers() { + Integer[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + + Observable.from(numbers) + .filter(i -> (i % 2 == 1)) + .subscribe(i -> result += i); + + assertTrue(result.equals("13579")); + } + + @Test + public void givenEmptyObservable_whenDefaultIfEmpty_thenGetDefaultMessage() { + + Observable.empty() + .defaultIfEmpty("Observable is empty") + .subscribe(s -> result += s); + + assertTrue(result.equals("Observable is empty")); + } + + @Test + public void givenObservableFromArray_whenDefaultIfEmptyAndFirst_thenGetFirstLetterFromArray() { + String[] letters = {"a", "b", "c", "d", "e", "f", "g"}; + + Observable.from(letters) + .defaultIfEmpty("Observable is empty") + .first() + .subscribe(s -> result += s); + + assertTrue(result.equals("a")); + } + + @Test + public void givenObservableFromArray_whenTakeWhile_thenGetSumOfNumbersFromCondition() { + Integer[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + final Integer[] sum = {0}; + + Observable.from(numbers) + .takeWhile(i -> i < 5) + .subscribe(s -> sum[0] += s); + + assertTrue(sum[0] == 10); + } + +} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementTest.java b/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementTest.java new file mode 100644 index 0000000000..9c52af61d0 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementTest.java @@ -0,0 +1,34 @@ +package com.baeldung.rxjava; + +import org.junit.Test; +import rx.Observable; + +import static junit.framework.Assert.assertTrue; + +public class ResourceManagementTest { + + @Test + public void givenResource_whenUsingOberservable_thenCreatePrintDisposeResource() throws InterruptedException { + + String[] result = {""}; + Observable values = Observable.using( + () -> { + return "MyResource"; + }, + r -> { + return Observable.create(o -> { + for (Character c : r.toCharArray()) + o.onNext(c); + o.onCompleted(); + }); + }, + r -> System.out.println("Disposed: " + r) + ); + + values.subscribe( + v -> result[0] += v, + e -> result[0] += e + ); + assertTrue(result[0].equals("MyResource")); + } +} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SingleTest.java b/rxjava/src/test/java/com/baeldung/rxjava/SingleTest.java new file mode 100644 index 0000000000..6d428d856b --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/SingleTest.java @@ -0,0 +1,24 @@ +package com.baeldung.rxjava; + +import org.junit.Test; +import rx.Observable; +import rx.Single; + +import static junit.framework.Assert.assertTrue; + +public class SingleTest { + + @Test + public void givenSingleObservable_whenSuccess_thenGetMessage() throws InterruptedException { + String[] result = {""}; + Single single = Observable.just("Hello") + .toSingle() + .doOnSuccess(i -> result[0] += i) + .doOnError(error -> { + throw new RuntimeException(error.getMessage()); + }); + single.subscribe(); + assertTrue(result[0].equals("Hello")); + } + +} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SubjectTest.java b/rxjava/src/test/java/com/baeldung/rxjava/SubjectTest.java new file mode 100644 index 0000000000..429a7fe231 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/SubjectTest.java @@ -0,0 +1,26 @@ +package com.baeldung.rxjava; + +import com.baelding.rxjava.SubjectImpl; +import org.junit.Test; +import rx.subjects.PublishSubject; + +import static junit.framework.Assert.assertTrue; + +public class SubjectTest { + + @Test + public void givenSubjectAndTwoSubscribers_whenSubscribeOnSubject_thenSubscriberBeginsToAdd(){ + PublishSubject subject = PublishSubject.create(); + + subject.subscribe(SubjectImpl.getFirstObserver()); + subject.onNext(1); + subject.onNext(2); + subject.onNext(3); + + subject.subscribe(SubjectImpl.getSecondObserver()); + subject.onNext(4); + subject.onCompleted(); + + assertTrue(SubjectImpl.subscriber1 + SubjectImpl.subscriber2 == 14); + } +} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java new file mode 100644 index 0000000000..8ce370e356 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java @@ -0,0 +1,273 @@ +package com.baeldung.rxjava; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import rx.Observable; +import rx.Observer; +import rx.exceptions.OnErrorNotImplementedException; +import rx.schedulers.Schedulers; + +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertTrue; + +public class UtilityOperatorsTest { + + int emittedTotal = 0; + int receivedTotal = 0; + String result = ""; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void givenObservable_whenObserveOnAfterOnNext_thenEmitsEventsOnComputeScheduler() throws InterruptedException { + + Observable.range(1, 5) + .map(i -> i * 100) + .doOnNext(i -> { + emittedTotal += i; + System.out.println("Emitting " + i + + " on thread " + Thread.currentThread().getName()); + }) + .observeOn(Schedulers.computation()) + .map(i -> i * 10) + .subscribe(i -> { + receivedTotal += i; + System.out.println("Received " + i + " on thread " + + Thread.currentThread().getName()); + }); + + Thread.sleep(2000); + assertTrue(emittedTotal == 1500); + assertTrue(receivedTotal == 15000); + } + + + @Test + public void givenObservable_whenObserveOnBeforeOnNext_thenEmitsEventsOnComputeScheduler() throws InterruptedException { + + Observable.range(1, 5) + .map(i -> i * 100) + .observeOn(Schedulers.computation()) + .doOnNext(i -> { + emittedTotal += i; + System.out.println("Emitting " + i + + " on thread " + Thread.currentThread().getName()); + }) + .map(i -> i * 10) + .subscribe(i -> { + receivedTotal += i; + System.out.println("Received " + i + " on thread " + + Thread.currentThread().getName()); + }); + + Thread.sleep(2000); + assertTrue(emittedTotal == 1500); + assertTrue(receivedTotal == 15000); + } + + + @Test + public void givenObservable_whenSubscribeOn_thenEmitsEventsOnComputeScheduler() throws InterruptedException { + + Observable.range(1, 5) + .map(i -> i * 100) + .doOnNext(i -> { + emittedTotal += i; + System.out.println("Emitting " + i + + " on thread " + Thread.currentThread().getName()); + }) + .subscribeOn(Schedulers.computation()) + .map(i -> i * 10) + .subscribe(i -> { + receivedTotal += i; + System.out.println("Received " + i + " on thread " + + Thread.currentThread().getName()); + }); + + Thread.sleep(2000); + assertTrue(emittedTotal == 1500); + assertTrue(receivedTotal == 15000); + } + + + @Test + public void givenObservableWithOneEvent_whenSingle_thenEmitEvent() { + + Observable.range(1, 1) + .single() + .subscribe(i -> receivedTotal += i); + assertTrue(receivedTotal == 1); + } + + @Test + public void givenObservableWithNoEvents_whenSingle_thenThrowException() { + + Observable.range(1, 3) + .single() + .onErrorReturn(e -> receivedTotal += 10) + .subscribe(); + assertTrue(receivedTotal == 10); + } + + @Test + public void givenObservableWihNoEvents_whenSingleOrDefault_thenDefaultMessage() { + + Observable.empty() + .singleOrDefault("Default") + .subscribe(i -> result += i); + assertTrue(result.equals("Default")); + } + + @Test + public void givenObservableWithManyEvents_whenSingleOrDefault_thenThrowException() { + + Observable.range(1, 3) + .singleOrDefault(5) + .onErrorReturn(e -> receivedTotal += 10) + .subscribe(); + assertTrue(receivedTotal == 10); + } + + @Test + public void givenObservable_whenDoOnNextAndDoOnCompleted_thenSumAllEventsAndShowMessage() { + + Observable.range(1, 10) + .doOnNext(r -> receivedTotal += r) + .doOnCompleted(() -> result = "Completed") + .subscribe(); + assertTrue(receivedTotal == 55); + assertTrue(result.equals("Completed")); + } + + @Test + public void givenObservable_whenDoOnEachAndDoOnSubscribe_thenSumAllValuesAndShowMessage() { + + Observable.range(1, 10) + .doOnEach(new Observer() { + @Override + public void onCompleted() { + System.out.println("Complete"); + } + + @Override + public void onError(Throwable e) { + e.printStackTrace(); + } + + @Override + public void onNext(Integer value) { + receivedTotal += value; + } + }) + .doOnSubscribe(() -> result = "Subscribed") + .subscribe(); + assertTrue(receivedTotal == 55); + assertTrue(result.equals("Subscribed")); + } + + @Test + public void givenObservable_whenDoOnErrorDoOnTerminateAndDoAfterTerminate_thenShowErrorTerminateAndAfterTerminateMessages() { + + thrown.expect(OnErrorNotImplementedException.class); + Observable.empty() + .single() + .doOnError(throwable -> { + throw new RuntimeException("error"); + }) + .doOnTerminate(() -> result += "doOnTerminate") + .doAfterTerminate(() -> result += "_doAfterTerminate") + .subscribe(); + assertTrue(result.equals("doOnTerminate_doAfterTerminate")); + } + + @Test + public void givenObservable_whenTimestamp_thenEventsShouldAppearTimestamped() { + + Observable.range(1, 10) + .timestamp() + .map(o -> result = o.getClass().toString()) + .last() + .subscribe(); + assertTrue(result.equals("class rx.schedulers.Timestamped")); + } + + @Test + public void givenObservables_whenDelay_thenEventsStartAppearAfterATime() throws InterruptedException { + + Observable source + = Observable.interval(1, TimeUnit.SECONDS) + .take(5) + .timestamp(); + + Observable delay + = source.delaySubscription(2, TimeUnit.SECONDS); + + source.subscribe( + value -> System.out.println("source :" + value), + t -> System.out.println("source error"), + () -> System.out.println("source completed")); + + delay.subscribe( + value -> System.out.println("delay : " + value), + t -> System.out.println("delay error"), + () -> System.out.println("delay completed")); + Thread.sleep(8000); + } + + @Test + public void givenObservable_whenRepeat_thenSumNumbersThreeTimes() { + + Observable.range(1, 3) + .repeat(3) + .subscribe(i -> receivedTotal += i); + assertTrue(receivedTotal == 18); + } + + @Test + public void givenObservable_whenUsing_thenReturnCreatedResource() { + + Observable values = Observable.using( + () -> "resource", + r -> { + return Observable.create(o -> { + for (Character c : r.toCharArray()) { + o.onNext(c); + } + o.onCompleted(); + }); + }, + r -> System.out.println("Disposed: " + r) + ); + values.subscribe( + v -> result += v, + e -> result += e + ); + assertTrue(result.equals("resource")); + } + + + @Test + public void givenObservableCached_whenSubscribesWith2Actions_thenEmitsCachedValues() { + + Observable source = + Observable.create(subscriber -> { + System.out.println("Create"); + subscriber.onNext(receivedTotal += 5); + subscriber.onCompleted(); + } + ).cache(); + source.subscribe(i -> { + System.out.println("element 1"); + receivedTotal += 1; + }); + source.subscribe(i -> { + System.out.println("element 2"); + receivedTotal += 2; + }); + assertTrue(receivedTotal == 8); + } + +} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingTest.java b/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingTest.java new file mode 100644 index 0000000000..297cfa980b --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingTest.java @@ -0,0 +1,141 @@ +package com.baeldung.rxjava.onerror; + +import io.reactivex.Observable; +import io.reactivex.exceptions.CompositeException; +import io.reactivex.observers.TestObserver; +import org.junit.Test; + +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.junit.Assert.assertTrue; + +/** + * @author aiet + */ +public class ExceptionHandlingTest { + + private Error UNKNOWN_ERROR = new Error("unknown error"); + private Exception UNKNOWN_EXCEPTION = new Exception("unknown exception"); + + @Test + public void givenSubscriberAndError_whenHandleOnErrorReturn_thenResumed() { + TestObserver testObserver = new TestObserver(); + + Observable + .error(UNKNOWN_ERROR) + .onErrorReturn(Throwable::getMessage) + .subscribe(testObserver); + + testObserver.assertNoErrors(); + testObserver.assertComplete(); + testObserver.assertValueCount(1); + testObserver.assertValue("unknown error"); + } + + @Test + public void givenSubscriberAndError_whenHandleOnErrorResume_thenResumed() { + TestObserver testObserver = new TestObserver(); + + Observable + .error(UNKNOWN_ERROR) + .onErrorResumeNext(Observable.just("one", "two")) + .subscribe(testObserver); + + testObserver.assertNoErrors(); + testObserver.assertComplete(); + testObserver.assertValueCount(2); + testObserver.assertValues("one", "two"); + } + + @Test + public void givenSubscriberAndError_whenHandleOnErrorResumeItem_thenResumed() { + TestObserver testObserver = new TestObserver(); + + Observable + .error(UNKNOWN_ERROR) + .onErrorReturnItem("singleValue") + .subscribe(testObserver); + + testObserver.assertNoErrors(); + testObserver.assertComplete(); + testObserver.assertValueCount(1); + testObserver.assertValue("singleValue"); + } + + @Test + public void givenSubscriberAndError_whenHandleOnErrorResumeFunc_thenResumed() { + TestObserver testObserver = new TestObserver(); + + Observable + .error(UNKNOWN_ERROR) + .onErrorResumeNext(throwable -> { + return Observable.just(throwable.getMessage(), "nextValue"); + }) + .subscribe(testObserver); + + testObserver.assertNoErrors(); + testObserver.assertComplete(); + testObserver.assertValueCount(2); + testObserver.assertValues("unknown error", "nextValue"); + } + + @Test + public void givenSubscriberAndError_whenChangeStateOnError_thenErrorThrown() { + TestObserver testObserver = new TestObserver(); + final AtomicBoolean state = new AtomicBoolean(false); + + Observable + .error(UNKNOWN_ERROR) + .doOnError(throwable -> state.set(true)) + .subscribe(testObserver); + + testObserver.assertError(UNKNOWN_ERROR); + testObserver.assertNotComplete(); + testObserver.assertNoValues(); + assertTrue("state should be changed", state.get()); + } + + @Test + public void givenSubscriberAndError_whenExceptionOccurOnError_thenCompositeExceptionThrown() { + TestObserver testObserver = new TestObserver(); + + Observable + .error(UNKNOWN_ERROR) + .doOnError(throwable -> { + throw new RuntimeException("unexcepted"); + }) + .subscribe(testObserver); + + testObserver.assertError(CompositeException.class); + testObserver.assertNotComplete(); + testObserver.assertNoValues(); + } + + @Test + public void givenSubscriberAndException_whenHandleOnException_thenResumed() { + TestObserver testObserver = new TestObserver(); + + Observable + .error(UNKNOWN_EXCEPTION) + .onExceptionResumeNext(Observable.just("exceptionResumed")) + .subscribe(testObserver); + + testObserver.assertNoErrors(); + testObserver.assertComplete(); + testObserver.assertValueCount(1); + testObserver.assertValue("exceptionResumed"); + } + + @Test + public void givenSubscriberAndError_whenHandleOnException_thenNotResumed() { + TestObserver testObserver = new TestObserver(); + Observable + .error(UNKNOWN_ERROR) + .onExceptionResumeNext(Observable.just("exceptionResumed")) + .subscribe(testObserver); + + testObserver.assertError(UNKNOWN_ERROR); + testObserver.assertNotComplete(); + } + +} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryTest.java b/rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryTest.java new file mode 100644 index 0000000000..0f9c39ad1b --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryTest.java @@ -0,0 +1,149 @@ +package com.baeldung.rxjava.onerror; + +import io.reactivex.Observable; +import io.reactivex.observers.TestObserver; +import org.junit.Test; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.assertTrue; + +/** + * @author aiet + */ +public class OnErrorRetryTest { + + private Error UNKNOWN_ERROR = new Error("unknown error"); + + @Test + public void givenSubscriberAndError_whenRetryOnError_thenRetryConfirmed() { + TestObserver testObserver = new TestObserver(); + AtomicInteger atomicCounter = new AtomicInteger(0); + + Observable + .error(() -> { + atomicCounter.incrementAndGet(); + return UNKNOWN_ERROR; + }) + .retry(1) + .subscribe(testObserver); + + testObserver.assertError(UNKNOWN_ERROR); + testObserver.assertNotComplete(); + testObserver.assertNoValues(); + assertTrue("should call twice", atomicCounter.get() == 2); + } + + @Test + public void givenSubscriberAndError_whenRetryConditionallyOnError_thenRetryConfirmed() { + TestObserver testObserver = new TestObserver(); + + AtomicInteger atomicCounter = new AtomicInteger(0); + + Observable + .error(() -> { + atomicCounter.incrementAndGet(); + return UNKNOWN_ERROR; + }) + .retry((integer, throwable) -> integer < 4) + .subscribe(testObserver); + + testObserver.assertError(UNKNOWN_ERROR); + testObserver.assertNotComplete(); + testObserver.assertNoValues(); + assertTrue("should call 4 times", atomicCounter.get() == 4); + } + + @Test + public void givenSubscriberAndError_whenRetryUntilOnError_thenRetryConfirmed() { + TestObserver testObserver = new TestObserver(); + AtomicInteger atomicCounter = new AtomicInteger(0); + + Observable + .error(UNKNOWN_ERROR) + .retryUntil(() -> atomicCounter.incrementAndGet() > 3) + .subscribe(testObserver); + + testObserver.assertError(UNKNOWN_ERROR); + testObserver.assertNotComplete(); + testObserver.assertNoValues(); + assertTrue("should call 4 times", atomicCounter.get() == 4); + } + + @Test + public void givenSubscriberAndError_whenRetryWhenOnError_thenRetryConfirmed() { + TestObserver testObserver = new TestObserver(); + Exception noretryException = new Exception("don't retry"); + + Observable + .error(UNKNOWN_ERROR) + .retryWhen(throwableObservable -> Observable.error(noretryException)) + .subscribe(testObserver); + + testObserver.assertError(noretryException); + testObserver.assertNotComplete(); + testObserver.assertNoValues(); + } + + @Test + public void givenSubscriberAndError_whenRetryWhenOnError_thenCompleted() { + TestObserver testObserver = new TestObserver(); + AtomicInteger atomicCounter = new AtomicInteger(0); + + Observable + .error(() -> { + atomicCounter.incrementAndGet(); + return UNKNOWN_ERROR; + }) + .retryWhen(throwableObservable -> Observable.empty()) + .subscribe(testObserver); + + testObserver.assertNoErrors(); + testObserver.assertComplete(); + testObserver.assertNoValues(); + assertTrue("should not retry", atomicCounter.get() == 0); + } + + @Test + public void givenSubscriberAndError_whenRetryWhenOnError_thenResubscribed() { + TestObserver testObserver = new TestObserver(); + AtomicInteger atomicCounter = new AtomicInteger(0); + + Observable + .error(() -> { + atomicCounter.incrementAndGet(); + return UNKNOWN_ERROR; + }) + .retryWhen(throwableObservable -> Observable.just("anything")) + .subscribe(testObserver); + + testObserver.assertNoErrors(); + testObserver.assertComplete(); + testObserver.assertNoValues(); + assertTrue("should retry once", atomicCounter.get() == 1); + } + + @Test + public void givenSubscriberAndError_whenRetryWhenForMultipleTimesOnError_thenResumed() { + TestObserver testObserver = new TestObserver(); + long before = System.currentTimeMillis(); + + Observable + .error(UNKNOWN_ERROR) + .retryWhen(throwableObservable -> throwableObservable + .zipWith(Observable.range(1, 3), (throwable, integer) -> integer) + .flatMap(integer -> { + System.out.println("retried " + integer + " times"); + return Observable.timer(integer, TimeUnit.SECONDS); + })) + .blockingSubscribe(testObserver); + + testObserver.assertNoErrors(); + testObserver.assertComplete(); + testObserver.assertNoValues(); + long secondsElapsed = (System.currentTimeMillis() - before) / 1000; + assertTrue("6 seconds should elapse", secondsElapsed == 6); + } + +} diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index db4ffa9abb..27dfec6939 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -66,7 +66,6 @@ com.fasterxml.jackson.module jackson-module-kotlin - 2.8.7 diff --git a/spring-5-mvc/src/test/kotlin/com/baeldung/LiveTest.java b/spring-5-mvc/src/test/kotlin/com/baeldung/LiveTest.java index 1b52f89117..b2f2852dbe 100644 --- a/spring-5-mvc/src/test/kotlin/com/baeldung/LiveTest.java +++ b/spring-5-mvc/src/test/kotlin/com/baeldung/LiveTest.java @@ -14,16 +14,19 @@ public class LiveTest { private static String APP_ROOT = "http://localhost:8081"; - @Test public void givenUser_whenResourceCreatedWithNullName_then400BadRequest() { - final Response response = givenAuth("user", "pass").contentType(MediaType.APPLICATION_JSON.toString()).body(resourceWithNullName()).post(APP_ROOT + "/foos"); + final Response response = givenAuth("user", "pass").contentType(MediaType.APPLICATION_JSON.toString()) + .body(resourceWithNullName()) + .post(APP_ROOT + "/foos"); assertEquals(400, response.getStatusCode()); } - + @Test public void givenUser_whenResourceCreated_then201Created() { - final Response response = givenAuth("user", "pass").contentType(MediaType.APPLICATION_JSON.toString()).body(resourceString()).post(APP_ROOT + "/foos"); + final Response response = givenAuth("user", "pass").contentType(MediaType.APPLICATION_JSON.toString()) + .body(resourceString()) + .post(APP_ROOT + "/foos"); assertEquals(201, response.getStatusCode()); } @@ -32,21 +35,22 @@ public class LiveTest { final Response response = givenAuth("user", "pass").get(APP_ROOT + "/foos"); assertEquals(200, response.getStatusCode()); }*/ - - // private final String resourceWithNullName() { return "{\"name\":null}"; } - + private final String resourceString() { return "{\"name\":\"" + randomAlphabetic(8) + "\"}"; - } + } private final RequestSpecification givenAuth(String username, String password) { - return RestAssured.given().auth().preemptive().basic(username, password); + return RestAssured.given() + .auth() + .preemptive() + .basic(username, password); } } \ No newline at end of file diff --git a/spring-5/README.md b/spring-5/README.md index 4ce0fd4c79..15e12cb5dc 100644 --- a/spring-5/README.md +++ b/spring-5/README.md @@ -9,3 +9,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Introduction to the Functional Web Framework in Spring 5](http://www.baeldung.com/spring-5-functional-web) - [Exploring the Spring 5 MVC URL Matching Improvements](http://www.baeldung.com/spring-5-mvc-url-matching) - [Spring 5 WebClient](http://www.baeldung.com/spring-5-webclient) +- [Spring 5 Functional Bean Registration](http://www.baeldung.com/spring-5-functional-beans) + diff --git a/spring-5/pom.xml b/spring-5/pom.xml index c2c565aef6..b77d89b532 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -1,188 +1,196 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - com.baeldung - spring-5 - 0.0.1-SNAPSHOT - jar + com.baeldung + spring-5 + 0.0.1-SNAPSHOT + jar - spring-5 - spring 5 sample project about new features + spring-5 + spring 5 sample project about new features - - org.springframework.boot - spring-boot-starter-parent - 2.0.0.M1 - - + + org.springframework.boot + spring-boot-starter-parent + 2.0.0.M1 + + - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-validation - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-webflux - - - org.projectreactor - reactor-spring - 1.0.1.RELEASE - + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-webflux + + + org.projectreactor + reactor-spring + ${reactor-spring.version} + + + javax.json.bind + javax.json.bind-api + ${jsonb-api.version} + + + org.apache.geronimo.specs + geronimo-json_1.1_spec + ${geronimo-json_1.1_spec.version} + + + org.apache.johnzon + johnzon-jsonb + ${johnzon.version} + + + + org.apache.commons + commons-lang3 + - - - org.apache.commons - commons-lang3 - + - + + org.springframework.boot + spring-boot-devtools + runtime + + + com.h2database + h2 + runtime + - - org.springframework.boot - spring-boot-devtools - runtime - - - com.h2database - h2 - runtime - + + org.springframework + spring-test + + + org.springframework.boot + spring-boot-starter-test + test + - - org.springframework - spring-test - - - org.springframework.boot - spring-boot-starter-test - test - + + org.junit.jupiter + junit-jupiter-api + ${junit.jupiter.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + - - org.junit.jupiter - junit-jupiter-api - ${junit.jupiter.version} - - - org.junit.jupiter - junit-jupiter-engine - ${junit.jupiter.version} - test - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - test - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - + - + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.Spring5Application + JAR + + - - - - org.springframework.boot - spring-boot-maven-plugin - - com.baeldung.Spring5Application - JAR - - + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + methods + true + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*LiveTest.java - - - + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - methods - true - - - - - - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - UTF-8 - UTF-8 - 1.8 - 1.0.0-M4 - 5.0.0-M4 - 2.20 - 5.0.0.RC2 - + + UTF-8 + UTF-8 + 1.8 + 1.0.0-M4 + 5.0.0-M4 + 2.20 + 5.0.0.RC2 + 1.0.1.RELEASE + 1.1.3 + 1.0 + 1.0 + diff --git a/spring-5/src/main/java/com/baeldung/Spring5Application.java b/spring-5/src/main/java/com/baeldung/Spring5Application.java index aaff1797ff..f321871646 100644 --- a/spring-5/src/main/java/com/baeldung/Spring5Application.java +++ b/spring-5/src/main/java/com/baeldung/Spring5Application.java @@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication -@ComponentScan(basePackages = {"com.baeldung.web"}) +@ComponentScan(basePackages = { "com.baeldung.web" }) public class Spring5Application { public static void main(String[] args) { diff --git a/spring-5/src/main/java/com/baeldung/functional/FormHandler.java b/spring-5/src/main/java/com/baeldung/functional/FormHandler.java index 857d22a67f..05069735bb 100644 --- a/spring-5/src/main/java/com/baeldung/functional/FormHandler.java +++ b/spring-5/src/main/java/com/baeldung/functional/FormHandler.java @@ -17,28 +17,25 @@ import static org.springframework.web.reactive.function.server.ServerResponse.ok public class FormHandler { Mono handleLogin(ServerRequest request) { - return request - .body(toFormData()) - .map(MultiValueMap::toSingleValueMap) - .filter(formData -> "baeldung".equals(formData.get("user"))) - .filter(formData -> "you_know_what_to_do".equals(formData.get("token"))) - .flatMap(formData -> ok().body(Mono.just("welcome back!"), String.class)) - .switchIfEmpty(ServerResponse.badRequest().build()); + return request.body(toFormData()) + .map(MultiValueMap::toSingleValueMap) + .filter(formData -> "baeldung".equals(formData.get("user"))) + .filter(formData -> "you_know_what_to_do".equals(formData.get("token"))) + .flatMap(formData -> ok().body(Mono.just("welcome back!"), String.class)) + .switchIfEmpty(ServerResponse.badRequest() + .build()); } Mono handleUpload(ServerRequest request) { - return request - .body(toDataBuffers()) - .collectList() - .flatMap(dataBuffers -> ok() - .body(fromObject(extractData(dataBuffers).toString()))); + return request.body(toDataBuffers()) + .collectList() + .flatMap(dataBuffers -> ok().body(fromObject(extractData(dataBuffers).toString()))); } private AtomicLong extractData(List dataBuffers) { AtomicLong atomicLong = new AtomicLong(0); - dataBuffers.forEach(d -> atomicLong.addAndGet(d - .asByteBuffer() - .array().length)); + dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer() + .array().length)); return atomicLong; } } diff --git a/spring-5/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java b/spring-5/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java index 8a808fc83a..f181dcb8e8 100644 --- a/spring-5/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java +++ b/spring-5/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java @@ -40,28 +40,25 @@ public class FunctionalSpringBootApplication { private RouterFunction routingFunction() { FormHandler formHandler = new FormHandler(); - RouterFunction restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest - .bodyToMono(Actor.class) - .doOnNext(actors::add) - .then(ok().build())); + RouterFunction restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class) + .doOnNext(actors::add) + .then(ok().build())); - return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))) - .andRoute(POST("/login"), formHandler::handleLogin) - .andRoute(POST("/upload"), formHandler::handleUpload) - .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) - .andNest(path("/actor"), restfulRouter) - .filter((request, next) -> { - System.out.println("Before handler invocation: " + request.path()); - return next.handle(request); - }); + return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin) + .andRoute(POST("/upload"), formHandler::handleUpload) + .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) + .andNest(path("/actor"), restfulRouter) + .filter((request, next) -> { + System.out.println("Before handler invocation: " + request.path()); + return next.handle(request); + }); } @Bean public ServletRegistrationBean servletRegistrationBean() throws Exception { - HttpHandler httpHandler = WebHttpHandlerBuilder - .webHandler((WebHandler) toHttpHandler(routingFunction())) - .prependFilter(new IndexRewriteFilter()) - .build(); + HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction())) + .prependFilter(new IndexRewriteFilter()) + .build(); ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(new RootServlet(httpHandler), "/"); registrationBean.setLoadOnStartup(1); registrationBean.setAsyncSupported(true); @@ -74,10 +71,9 @@ public class FunctionalSpringBootApplication { static class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(final HttpSecurity http) throws Exception { - http - .authorizeRequests() - .anyRequest() - .permitAll(); + http.authorizeRequests() + .anyRequest() + .permitAll(); } } diff --git a/spring-5/src/main/java/com/baeldung/functional/FunctionalWebApplication.java b/spring-5/src/main/java/com/baeldung/functional/FunctionalWebApplication.java index 29f9ea43da..2a4642c484 100644 --- a/spring-5/src/main/java/com/baeldung/functional/FunctionalWebApplication.java +++ b/spring-5/src/main/java/com/baeldung/functional/FunctionalWebApplication.java @@ -33,28 +33,25 @@ public class FunctionalWebApplication { private RouterFunction routingFunction() { FormHandler formHandler = new FormHandler(); - RouterFunction restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest - .bodyToMono(Actor.class) - .doOnNext(actors::add) - .then(ok().build())); + RouterFunction restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class) + .doOnNext(actors::add) + .then(ok().build())); - return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))) - .andRoute(POST("/login"), formHandler::handleLogin) - .andRoute(POST("/upload"), formHandler::handleUpload) - .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) - .andNest(path("/actor"), restfulRouter) - .filter((request, next) -> { - System.out.println("Before handler invocation: " + request.path()); - return next.handle(request); - }); + return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin) + .andRoute(POST("/upload"), formHandler::handleUpload) + .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) + .andNest(path("/actor"), restfulRouter) + .filter((request, next) -> { + System.out.println("Before handler invocation: " + request.path()); + return next.handle(request); + }); } WebServer start() throws Exception { WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction()); - HttpHandler httpHandler = WebHttpHandlerBuilder - .webHandler(webHandler) - .prependFilter(new IndexRewriteFilter()) - .build(); + HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler) + .prependFilter(new IndexRewriteFilter()) + .build(); Tomcat tomcat = new Tomcat(); tomcat.setHostname("localhost"); diff --git a/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java b/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java index d218bba581..3e91a0354b 100644 --- a/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java +++ b/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java @@ -11,17 +11,15 @@ class IndexRewriteFilter implements WebFilter { @Override public Mono filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) { ServerHttpRequest request = serverWebExchange.getRequest(); - if (request - .getURI() - .getPath() - .equals("/")) { - return webFilterChain.filter(serverWebExchange - .mutate() - .request(builder -> builder - .method(request.getMethod()) - .contextPath(request.getPath().toString()) - .path("/test")) - .build()); + if (request.getURI() + .getPath() + .equals("/")) { + return webFilterChain.filter(serverWebExchange.mutate() + .request(builder -> builder.method(request.getMethod()) + .contextPath(request.getPath() + .toString()) + .path("/test")) + .build()); } return webFilterChain.filter(serverWebExchange); } diff --git a/spring-5/src/main/java/com/baeldung/functional/MyService.java b/spring-5/src/main/java/com/baeldung/functional/MyService.java index d85a860f06..b7b8b13d8b 100644 --- a/spring-5/src/main/java/com/baeldung/functional/MyService.java +++ b/spring-5/src/main/java/com/baeldung/functional/MyService.java @@ -2,12 +2,10 @@ package com.baeldung.functional; import java.util.Random; -import org.springframework.stereotype.Component; - public class MyService { - public int getRandomNumber(){ + public int getRandomNumber() { return (new Random().nextInt(10)); } - + } diff --git a/spring-5/src/main/java/com/baeldung/functional/RootServlet.java b/spring-5/src/main/java/com/baeldung/functional/RootServlet.java index 922809e563..c0dd54cb4a 100644 --- a/spring-5/src/main/java/com/baeldung/functional/RootServlet.java +++ b/spring-5/src/main/java/com/baeldung/functional/RootServlet.java @@ -28,10 +28,9 @@ import org.springframework.web.server.WebHandler; public class RootServlet extends ServletHttpHandlerAdapter { public RootServlet() { - this(WebHttpHandlerBuilder - .webHandler((WebHandler) toHttpHandler(routingFunction())) - .prependFilter(new IndexRewriteFilter()) - .build()); + this(WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction())) + .prependFilter(new IndexRewriteFilter()) + .build()); } RootServlet(HttpHandler httpHandler) { @@ -44,44 +43,36 @@ public class RootServlet extends ServletHttpHandlerAdapter { private static RouterFunction routingFunction() { - return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))) - .andRoute(POST("/login"), serverRequest -> serverRequest - .body(toFormData()) + return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), serverRequest -> serverRequest.body(toFormData()) .map(MultiValueMap::toSingleValueMap) .map(formData -> { System.out.println("form data: " + formData.toString()); if ("baeldung".equals(formData.get("user")) && "you_know_what_to_do".equals(formData.get("token"))) { - return ok() - .body(Mono.just("welcome back!"), String.class) - .block(); + return ok().body(Mono.just("welcome back!"), String.class) + .block(); } - return ServerResponse - .badRequest() - .build() - .block(); + return ServerResponse.badRequest() + .build() + .block(); })) - .andRoute(POST("/upload"), serverRequest -> serverRequest - .body(toDataBuffers()) - .collectList() - .map(dataBuffers -> { - AtomicLong atomicLong = new AtomicLong(0); - dataBuffers.forEach(d -> atomicLong.addAndGet(d - .asByteBuffer() - .array().length)); - System.out.println("data length:" + atomicLong.get()); - return ok() - .body(fromObject(atomicLong.toString())) - .block(); - })) - .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) - .andNest(path("/actor"), route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest - .bodyToMono(Actor.class) - .doOnNext(actors::add) - .then(ok().build()))) - .filter((request, next) -> { - System.out.println("Before handler invocation: " + request.path()); - return next.handle(request); - }); + .andRoute(POST("/upload"), serverRequest -> serverRequest.body(toDataBuffers()) + .collectList() + .map(dataBuffers -> { + AtomicLong atomicLong = new AtomicLong(0); + dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer() + .array().length)); + System.out.println("data length:" + atomicLong.get()); + return ok().body(fromObject(atomicLong.toString())) + .block(); + })) + .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) + .andNest(path("/actor"), route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class) + .doOnNext(actors::add) + .then(ok().build()))) + .filter((request, next) -> { + System.out.println("Before handler invocation: " + request.path()); + return next.handle(request); + }); } diff --git a/spring-5/src/main/java/com/baeldung/jsonb/Person.java b/spring-5/src/main/java/com/baeldung/jsonb/Person.java new file mode 100644 index 0000000000..99ebd54f0b --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/jsonb/Person.java @@ -0,0 +1,139 @@ +package com.baeldung.jsonb; + +import java.math.BigDecimal; +import java.time.LocalDate; + +import javax.json.bind.annotation.JsonbDateFormat; +import javax.json.bind.annotation.JsonbNumberFormat; +import javax.json.bind.annotation.JsonbProperty; +import javax.json.bind.annotation.JsonbTransient; + +public class Person { + + @JsonbProperty("person-name") + private String name; + @JsonbProperty(nillable = true) + private String email; + @JsonbTransient + private int age; + @JsonbDateFormat("dd-MM-yyyy") + private LocalDate registeredDate; + private BigDecimal salary; + + public Person() { + } + + public Person(String name, String email, int age, LocalDate registeredDate, BigDecimal salary) { + super(); + this.name = name; + this.email = email; + this.age = age; + this.registeredDate = registeredDate; + this.salary = salary; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @JsonbNumberFormat(locale = "en_US", value = "#0.0") + public BigDecimal getSalary() { + return salary; + } + + public void setSalary(BigDecimal salary) { + this.salary = salary; + } + + public LocalDate getRegisteredDate() { + return registeredDate; + } + + public void setRegisteredDate(LocalDate registeredDate) { + this.registeredDate = registeredDate; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Person [name="); + builder.append(name); + builder.append(", email="); + builder.append(email); + builder.append(", age="); + builder.append(age); + builder.append(", registeredDate="); + builder.append(registeredDate); + builder.append(", salary="); + builder.append(salary); + builder.append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + age; + result = prime * result + ((email == null) ? 0 : email.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((registeredDate == null) ? 0 : registeredDate.hashCode()); + result = prime * result + ((salary == null) ? 0 : salary.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; + Person other = (Person) obj; + if (age != other.age) + return false; + if (email == null) { + if (other.email != null) + return false; + } else if (!email.equals(other.email)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (registeredDate == null) { + if (other.registeredDate != null) + return false; + } else if (!registeredDate.equals(other.registeredDate)) + return false; + if (salary == null) { + if (other.salary != null) + return false; + } else if (!salary.equals(other.salary)) + return false; + return true; + } + +} diff --git a/spring-5/src/main/java/com/baeldung/jsonb/PersonController.java b/spring-5/src/main/java/com/baeldung/jsonb/PersonController.java new file mode 100644 index 0000000000..75fcd1e2cc --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/jsonb/PersonController.java @@ -0,0 +1,58 @@ +package com.baeldung.jsonb; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.annotation.PostConstruct; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +@RestController("/person") +public class PersonController { + + List personRepository; + + @PostConstruct + public void init() { + // @formatter:off + personRepository = new ArrayList<>(Arrays.asList( + new Person("Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), + new Person("Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)), + new Person("Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), + new Person("Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)), + new Person("Mark", "mark@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1200)), + new Person("Julia", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)))); + // @formatter:on + + } + + @GetMapping("/person/{id}") + @ResponseBody + public Person findById(@PathVariable final int id) { + return personRepository.get(id); + } + + @PostMapping("/person") + @ResponseStatus(HttpStatus.OK) + @ResponseBody + public boolean insertPerson(@RequestBody final Person person) { + return personRepository.add(person); + } + + @GetMapping("/person") + @ResponseBody + public List findAll() { + return personRepository; + } + +} diff --git a/spring-5/src/main/java/com/baeldung/jsonb/Spring5Application.java b/spring-5/src/main/java/com/baeldung/jsonb/Spring5Application.java new file mode 100644 index 0000000000..00fce06834 --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/jsonb/Spring5Application.java @@ -0,0 +1,30 @@ +package com.baeldung.jsonb; + +import java.util.ArrayList; +import java.util.Collection; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.http.HttpMessageConverters; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.JsonbHttpMessageConverter; + +@SpringBootApplication +@ComponentScan(basePackages = { "com.baeldung.jsonb" }) +public class Spring5Application { + + public static void main(String[] args) { + SpringApplication.run(Spring5Application.class, args); + } + + @Bean + public HttpMessageConverters customConverters() { + Collection> messageConverters = new ArrayList<>(); + JsonbHttpMessageConverter jsonbHttpMessageConverter = new JsonbHttpMessageConverter(); + messageConverters.add(jsonbHttpMessageConverter); + return new HttpMessageConverters(true, messageConverters); + } + +} diff --git a/spring-5/src/main/java/com/baeldung/jupiter/ParameterAutowireUtils.java b/spring-5/src/main/java/com/baeldung/jupiter/ParameterAutowireUtils.java index 068c6af381..d1a4cc8b29 100644 --- a/spring-5/src/main/java/com/baeldung/jupiter/ParameterAutowireUtils.java +++ b/spring-5/src/main/java/com/baeldung/jupiter/ParameterAutowireUtils.java @@ -27,16 +27,14 @@ abstract class ParameterAutowireUtils { public static Object resolveDependency(Parameter parameter, Class containingClass, ApplicationContext applicationContext) { - boolean required = findMergedAnnotation(parameter, Autowired.class) - .map(Autowired::required) - .orElse(true); + boolean required = findMergedAnnotation(parameter, Autowired.class).map(Autowired::required) + .orElse(true); MethodParameter methodParameter = (parameter.getDeclaringExecutable() instanceof Method ? MethodParameterFactory.createSynthesizingMethodParameter(parameter) : MethodParameterFactory.createMethodParameter(parameter)); DependencyDescriptor descriptor = new DependencyDescriptor(methodParameter, required); descriptor.setContainingClass(containingClass); - return applicationContext - .getAutowireCapableBeanFactory() - .resolveDependency(descriptor, null); + return applicationContext.getAutowireCapableBeanFactory() + .resolveDependency(descriptor, null); } private static Optional findMergedAnnotation(AnnotatedElement element, Class annotationType) { diff --git a/spring-5/src/main/java/com/baeldung/jupiter/SpringExtension.java b/spring-5/src/main/java/com/baeldung/jupiter/SpringExtension.java index 08fa0c4768..0eb7c861f1 100644 --- a/spring-5/src/main/java/com/baeldung/jupiter/SpringExtension.java +++ b/spring-5/src/main/java/com/baeldung/jupiter/SpringExtension.java @@ -26,11 +26,9 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes try { getTestContextManager(context).afterTestClass(); } finally { - context - .getStore(namespace) - .remove(context - .getTestClass() - .get()); + context.getStore(namespace) + .remove(context.getTestClass() + .get()); } } @@ -42,21 +40,18 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes @Override public void beforeEach(TestExtensionContext context) throws Exception { Object testInstance = context.getTestInstance(); - Method testMethod = context - .getTestMethod() - .get(); + Method testMethod = context.getTestMethod() + .get(); getTestContextManager(context).beforeTestMethod(testInstance, testMethod); } @Override public void afterEach(TestExtensionContext context) throws Exception { Object testInstance = context.getTestInstance(); - Method testMethod = context - .getTestMethod() - .get(); - Throwable testException = context - .getTestException() - .orElse(null); + Method testMethod = context.getTestMethod() + .get(); + Throwable testException = context.getTestException() + .orElse(null); getTestContextManager(context).afterTestMethod(testInstance, testMethod, testException); } @@ -70,24 +65,21 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes @Override public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) { Parameter parameter = parameterContext.getParameter(); - Class testClass = extensionContext - .getTestClass() - .get(); + Class testClass = extensionContext.getTestClass() + .get(); ApplicationContext applicationContext = getApplicationContext(extensionContext); return ParameterAutowireUtils.resolveDependency(parameter, testClass, applicationContext); } private ApplicationContext getApplicationContext(ExtensionContext context) { - return getTestContextManager(context) - .getTestContext() - .getApplicationContext(); + return getTestContextManager(context).getTestContext() + .getApplicationContext(); } private TestContextManager getTestContextManager(ExtensionContext context) { Assert.notNull(context, "ExtensionContext must not be null"); - Class testClass = context - .getTestClass() - .get(); + Class testClass = context.getTestClass() + .get(); ExtensionContext.Store store = context.getStore(namespace); return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class); } diff --git a/spring-5/src/main/java/com/baeldung/jupiter/SpringJUnit5Config.java b/spring-5/src/main/java/com/baeldung/jupiter/SpringJUnit5Config.java index e8b9cc500f..8f02d71d49 100644 --- a/spring-5/src/main/java/com/baeldung/jupiter/SpringJUnit5Config.java +++ b/spring-5/src/main/java/com/baeldung/jupiter/SpringJUnit5Config.java @@ -26,8 +26,7 @@ public @interface SpringJUnit5Config { String[] locations() default {}; @AliasFor(annotation = ContextConfiguration.class) - Class>[] initializers() default {}; + Class>[] initializers() default {}; @AliasFor(annotation = ContextConfiguration.class) boolean inheritLocations() default true; diff --git a/spring-5/src/main/java/com/baeldung/persistence/DataSetupBean.java b/spring-5/src/main/java/com/baeldung/persistence/DataSetupBean.java index 7936a2b7af..9f5d9ff6c2 100644 --- a/spring-5/src/main/java/com/baeldung/persistence/DataSetupBean.java +++ b/spring-5/src/main/java/com/baeldung/persistence/DataSetupBean.java @@ -20,7 +20,8 @@ public class DataSetupBean implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { - IntStream.range(1, 20).forEach(i -> repo.save(new Foo(randomAlphabetic(8)))); + IntStream.range(1, 20) + .forEach(i -> repo.save(new Foo(randomAlphabetic(8)))); } } diff --git a/spring-5/src/main/java/com/baeldung/web/FooController.java b/spring-5/src/main/java/com/baeldung/web/FooController.java index 0e7c94bd8f..925f2b49f4 100644 --- a/spring-5/src/main/java/com/baeldung/web/FooController.java +++ b/spring-5/src/main/java/com/baeldung/web/FooController.java @@ -23,7 +23,8 @@ public class FooController { @ResponseBody @Validated public Foo findById(@PathVariable @Min(0) final long id) { - return repo.findById(id).orElse(null); + return repo.findById(id) + .orElse(null); } @GetMapping @@ -36,7 +37,8 @@ public class FooController { @ResponseBody @Validated public List findPaginated(@RequestParam("page") @Min(0) final int page, @Max(100) @RequestParam("size") final int size) { - return repo.findAll(PageRequest.of(page, size)).getContent(); + return repo.findAll(PageRequest.of(page, size)) + .getContent(); } // API - write diff --git a/spring-5/src/main/java/com/baeldung/web/reactive/Task.java b/spring-5/src/main/java/com/baeldung/web/reactive/Task.java index 84193d9354..725fd931e1 100644 --- a/spring-5/src/main/java/com/baeldung/web/reactive/Task.java +++ b/spring-5/src/main/java/com/baeldung/web/reactive/Task.java @@ -23,9 +23,6 @@ public class Task { @Override public String toString() { - return "Task{" + - "name='" + name + '\'' + - ", id=" + id + - '}'; + return "Task{" + "name='" + name + '\'' + ", id=" + id + '}'; } } diff --git a/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java b/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java index 3a2e1b1a75..7bab288bab 100644 --- a/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java +++ b/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java @@ -33,17 +33,17 @@ public class WebClientController { WebClient.UriSpec request2 = createWebClientWithServerURLAndDefaultValues().post(); // request body specifications - WebClient.RequestBodySpec uri1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST).uri("/resource"); - WebClient.RequestBodySpec uri2 = createWebClientWithServerURLAndDefaultValues().post().uri(URI.create("/resource")); + WebClient.RequestBodySpec uri1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST) + .uri("/resource"); + WebClient.RequestBodySpec uri2 = createWebClientWithServerURLAndDefaultValues().post() + .uri(URI.create("/resource")); // request header specification WebClient.RequestHeadersSpec requestSpec1 = uri1.body(BodyInserters.fromPublisher(Mono.just("data"), String.class)); WebClient.RequestHeadersSpec requestSpec2 = uri2.body(BodyInserters.fromObject("data")); // inserters - BodyInserter, ReactiveHttpOutputMessage> inserter1 = BodyInserters - .fromPublisher(Subscriber::onComplete, String.class); - + BodyInserter, ReactiveHttpOutputMessage> inserter1 = BodyInserters.fromPublisher(Subscriber::onComplete, String.class); LinkedMultiValueMap map = new LinkedMultiValueMap<>(); map.add("key1", "value1"); @@ -53,14 +53,13 @@ public class WebClientController { BodyInserter inserter3 = BodyInserters.fromObject("body"); // responses - WebClient.ResponseSpec response1 = uri1 - .body(inserter3) - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) - .acceptCharset(Charset.forName("UTF-8")) - .ifNoneMatch("*") - .ifModifiedSince(ZonedDateTime.now()) - .retrieve(); + WebClient.ResponseSpec response1 = uri1.body(inserter3) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) + .acceptCharset(Charset.forName("UTF-8")) + .ifNoneMatch("*") + .ifModifiedSince(ZonedDateTime.now()) + .retrieve(); WebClient.ResponseSpec response2 = requestSpec2.retrieve(); } @@ -74,13 +73,12 @@ public class WebClientController { } private WebClient createWebClientWithServerURLAndDefaultValues() { - return WebClient - .builder() - .baseUrl("http://localhost:8081") - .defaultCookie("cookieKey", "cookieValue") - .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080")) - .build(); + return WebClient.builder() + .baseUrl("http://localhost:8081") + .defaultCookie("cookieKey", "cookieValue") + .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080")) + .build(); } } diff --git a/spring-5/src/test/java/com/baeldung/ParallelIntegrationTest.java b/spring-5/src/test/java/com/baeldung/ParallelIntegrationTest.java index cbb7a2867b..1ce96de4ef 100644 --- a/spring-5/src/test/java/com/baeldung/ParallelIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/ParallelIntegrationTest.java @@ -9,14 +9,14 @@ public class ParallelIntegrationTest { @Test public void runTests() { - final Class[] classes = {Example1IntegrationTest.class, Example2IntegrationTest.class}; + final Class[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class }; JUnitCore.runClasses(new Computer(), classes); } @Test public void runTestsInParallel() { - final Class[] classes = {Example1IntegrationTest.class, Example2IntegrationTest.class}; + final Class[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class }; JUnitCore.runClasses(new ParallelComputer(true, true), classes); } diff --git a/spring-5/src/test/java/com/baeldung/Spring5JUnit4ConcurrentIntegrationTest.java b/spring-5/src/test/java/com/baeldung/Spring5JUnit4ConcurrentIntegrationTest.java index a155de20fa..7e494465b2 100644 --- a/spring-5/src/test/java/com/baeldung/Spring5JUnit4ConcurrentIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/Spring5JUnit4ConcurrentIntegrationTest.java @@ -50,5 +50,3 @@ public class Spring5JUnit4ConcurrentIntegrationTest implements ApplicationContex } } - - diff --git a/spring-5/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java index 6f39f11b00..a7b951b930 100644 --- a/spring-5/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java @@ -23,10 +23,9 @@ public class FunctionalWebApplicationIntegrationTest { @BeforeClass public static void setup() throws Exception { server = new FunctionalWebApplication().start(); - client = WebTestClient - .bindToServer() - .baseUrl("http://localhost:" + server.getPort()) - .build(); + client = WebTestClient.bindToServer() + .baseUrl("http://localhost:" + server.getPort()) + .build(); } @AfterClass @@ -36,26 +35,24 @@ public class FunctionalWebApplicationIntegrationTest { @Test public void givenRouter_whenGetTest_thenGotHelloWorld() throws Exception { - client - .get() - .uri("/test") - .exchange() - .expectStatus() - .isOk() - .expectBody(String.class) - .isEqualTo("helloworld"); + client.get() + .uri("/test") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("helloworld"); } @Test public void givenIndexFilter_whenRequestRoot_thenRewrittenToTest() throws Exception { - client - .get() - .uri("/") - .exchange() - .expectStatus() - .isOk() - .expectBody(String.class) - .isEqualTo("helloworld"); + client.get() + .uri("/") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("helloworld"); } @Test @@ -64,16 +61,15 @@ public class FunctionalWebApplicationIntegrationTest { formData.add("user", "baeldung"); formData.add("token", "you_know_what_to_do"); - client - .post() - .uri("/login") - .contentType(MediaType.APPLICATION_FORM_URLENCODED) - .body(BodyInserters.fromFormData(formData)) - .exchange() - .expectStatus() - .isOk() - .expectBody(String.class) - .isEqualTo("welcome back!"); + client.post() + .uri("/login") + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .body(BodyInserters.fromFormData(formData)) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("welcome back!"); } @Test @@ -82,70 +78,64 @@ public class FunctionalWebApplicationIntegrationTest { formData.add("user", "baeldung"); formData.add("token", "try_again"); - client - .post() - .uri("/login") - .contentType(MediaType.APPLICATION_FORM_URLENCODED) - .body(BodyInserters.fromFormData(formData)) - .exchange() - .expectStatus() - .isBadRequest(); + client.post() + .uri("/login") + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .body(BodyInserters.fromFormData(formData)) + .exchange() + .expectStatus() + .isBadRequest(); } @Test public void givenUploadForm_whenRequestWithMultipartData_thenSuccess() throws Exception { Resource resource = new ClassPathResource("/baeldung-weekly.png"); - client - .post() - .uri("/upload") - .contentType(MediaType.MULTIPART_FORM_DATA) - .body(fromResource(resource)) - .exchange() - .expectStatus() - .isOk() - .expectBody(String.class) - .isEqualTo(String.valueOf(resource.contentLength())); + client.post() + .uri("/upload") + .contentType(MediaType.MULTIPART_FORM_DATA) + .body(fromResource(resource)) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo(String.valueOf(resource.contentLength())); } @Test public void givenActors_whenAddActor_thenAdded() throws Exception { - client - .get() - .uri("/actor") - .exchange() - .expectStatus() - .isOk() - .expectBodyList(Actor.class) - .hasSize(2); + client.get() + .uri("/actor") + .exchange() + .expectStatus() + .isOk() + .expectBodyList(Actor.class) + .hasSize(2); - client - .post() - .uri("/actor") - .body(fromObject(new Actor("Clint", "Eastwood"))) - .exchange() - .expectStatus() - .isOk(); + client.post() + .uri("/actor") + .body(fromObject(new Actor("Clint", "Eastwood"))) + .exchange() + .expectStatus() + .isOk(); - client - .get() - .uri("/actor") - .exchange() - .expectStatus() - .isOk() - .expectBodyList(Actor.class) - .hasSize(3); + client.get() + .uri("/actor") + .exchange() + .expectStatus() + .isOk() + .expectBodyList(Actor.class) + .hasSize(3); } @Test public void givenResources_whenAccess_thenGot() throws Exception { - client - .get() - .uri("/files/hello.txt") - .exchange() - .expectStatus() - .isOk() - .expectBody(String.class) - .isEqualTo("hello"); + client.get() + .uri("/files/hello.txt") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("hello"); } } diff --git a/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java new file mode 100644 index 0000000000..a31a16d610 --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java @@ -0,0 +1,44 @@ +package com.baeldung.jsonb; + +import static org.junit.Assert.assertTrue; + +import java.math.BigDecimal; +import java.time.LocalDate; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class JsonbIntegrationTest { + @Value("${security.user.name}") + private String username; + @Value("${security.user.password}") + private String password; + + @Autowired + private TestRestTemplate template; + + @Test + public void givenId_whenUriIsPerson_thenGetPerson() { + ResponseEntity response = template.withBasicAuth(username, password) + .getForEntity("/person/1", Person.class); + Person person = response.getBody(); + assertTrue(person.equals(new Person("Jhon", "jhon1@test.com", 0, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500.0)))); + } + + @Test + public void whenSendPostAPerson_thenGetOkStatus() { + ResponseEntity response = template.withBasicAuth(username, password) + .postForEntity("/person", "{\"birthDate\":\"07-09-2017\",\"email\":\"jhon1@test.com\",\"person-name\":\"Jhon\"}", Boolean.class); + boolean value = response.getBody(); + assertTrue(true == value); + } + +} diff --git a/spring-5/src/test/java/com/baeldung/jsonb/JsonbTest.java b/spring-5/src/test/java/com/baeldung/jsonb/JsonbTest.java new file mode 100644 index 0000000000..7133999551 --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/jsonb/JsonbTest.java @@ -0,0 +1,38 @@ +package com.baeldung.jsonb; + +import static org.junit.Assert.assertTrue; + +import java.math.BigDecimal; +import java.time.LocalDate; + +import javax.json.bind.Jsonb; +import javax.json.bind.JsonbBuilder; + +import org.junit.Before; +import org.junit.Test; + +public class JsonbTest { + + private Jsonb jsonb; + + @Before + public void setup() { + jsonb = JsonbBuilder.create(); + } + + @Test + public void givenPersonObject_whenSerializeWithJsonb_thenGetPersonJson() { + Person person = new Person("Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); + String jsonPerson = jsonb.toJson(person); + assertTrue("{\"email\":\"jhon@test.com\",\"person-name\":\"Jhon\",\"registeredDate\":\"07-09-2019\",\"salary\":\"1000.0\"}".equals(jsonPerson)); + } + + @Test + public void givenPersonJson_whenDeserializeWithJsonb_thenGetPersonObject() { + Person person = new Person("Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0)); + String jsonPerson = "{\"email\":\"jhon@test.com\",\"person-name\":\"Jhon\",\"registeredDate\":\"07-09-2019\",\"salary\":\"1000.0\"}"; + assertTrue(jsonb.fromJson(jsonPerson, Person.class) + .equals(person)); + } + +} diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ParallelIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ParallelIntegrationTest.java index fb6bb27684..55b0fcf267 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ParallelIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ParallelIntegrationTest.java @@ -11,18 +11,14 @@ class Spring5JUnit5ParallelIntegrationTest { @Test void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingParallel() { - final Class[] classes = { - Example1IntegrationTest.class, Example2IntegrationTest.class - }; + final Class[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class }; JUnitCore.runClasses(new ParallelComputer(true, true), classes); } @Test void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingLinear() { - final Class[] classes = { - Example1IntegrationTest.class, Example2IntegrationTest.class - }; + final Class[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class }; JUnitCore.runClasses(new Computer(), classes); } diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5Java8NewFeaturesIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5Java8NewFeaturesIntegrationTest.java index 2c3a71fb3e..f58bf9f3cd 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5Java8NewFeaturesIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5Java8NewFeaturesIntegrationTest.java @@ -16,18 +16,16 @@ class Spring5Java8NewFeaturesIntegrationTest { } public class StringUtils { - FunctionalInterfaceExample - functionLambdaString = s -> Pattern.compile(" +").splitAsStream(s) - .map(word -> new StringBuilder(word).reverse()) - .collect(Collectors.joining(" ")); + FunctionalInterfaceExample functionLambdaString = s -> Pattern.compile(" +") + .splitAsStream(s) + .map(word -> new StringBuilder(word).reverse()) + .collect(Collectors.joining(" ")); } @Test - void givenStringUtil_whenSupplierCall_thenFunctionalInterfaceReverseString() - throws Exception { + void givenStringUtil_whenSupplierCall_thenFunctionalInterfaceReverseString() throws Exception { Supplier stringUtilsSupplier = StringUtils::new; - assertEquals(stringUtilsSupplier.get().functionLambdaString - .reverseString("hello"), "olleh"); + assertEquals(stringUtilsSupplier.get().functionLambdaString.reverseString("hello"), "olleh"); } } diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5ReactiveServerClientIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5ReactiveServerClientIntegrationTest.java index 5c289c3e34..bbd852d625 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5ReactiveServerClientIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5ReactiveServerClientIntegrationTest.java @@ -25,20 +25,15 @@ public class Spring5ReactiveServerClientIntegrationTest { @BeforeAll public static void setUp() throws Exception { HttpServer server = HttpServer.create("localhost", 8080); - RouterFunction route = RouterFunctions - .route(POST("/task/process"), request -> ServerResponse - .ok() - .body(request - .bodyToFlux(Task.class) - .map(ll -> new Task("TaskName", 1)), Task.class)) - .and(RouterFunctions.route(GET("/task"), request -> ServerResponse - .ok() - .body(Mono.just("server is alive"), String.class))); + RouterFunction route = RouterFunctions.route(POST("/task/process"), request -> ServerResponse.ok() + .body(request.bodyToFlux(Task.class) + .map(ll -> new Task("TaskName", 1)), Task.class)) + .and(RouterFunctions.route(GET("/task"), request -> ServerResponse.ok() + .body(Mono.just("server is alive"), String.class))); HttpHandler httpHandler = RouterFunctions.toHttpHandler(route); ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler); - nettyContext = server - .newHandler(adapter) - .block(); + nettyContext = server.newHandler(adapter) + .block(); } @AfterAll @@ -46,55 +41,54 @@ public class Spring5ReactiveServerClientIntegrationTest { nettyContext.dispose(); } -// @Test -// public void givenCheckTask_whenServerHandle_thenServerResponseALiveString() throws Exception { -// WebClient client = WebClient.create("http://localhost:8080"); -// Mono result = client -// .get() -// .uri("/task") -// .exchange() -// .then(response -> response.bodyToMono(String.class)); -// -// assertThat(result.block()).isInstanceOf(String.class); -// } + // @Test + // public void givenCheckTask_whenServerHandle_thenServerResponseALiveString() throws Exception { + // WebClient client = WebClient.create("http://localhost:8080"); + // Mono result = client + // .get() + // .uri("/task") + // .exchange() + // .then(response -> response.bodyToMono(String.class)); + // + // assertThat(result.block()).isInstanceOf(String.class); + // } -// @Test -// public void givenThreeTasks_whenServerHandleTheTasks_thenServerResponseATask() throws Exception { -// URI uri = URI.create("http://localhost:8080/task/process"); -// ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector()); -// ClientRequest request = ClientRequest -// .method(HttpMethod.POST, uri) -// .body(BodyInserters.fromPublisher(getLatLngs(), Task.class)) -// .build(); -// -// Flux taskResponse = exchange -// .exchange(request) -// .flatMap(response -> response.bodyToFlux(Task.class)); -// -// assertThat(taskResponse.blockFirst()).isInstanceOf(Task.class); -// } + // @Test + // public void givenThreeTasks_whenServerHandleTheTasks_thenServerResponseATask() throws Exception { + // URI uri = URI.create("http://localhost:8080/task/process"); + // ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector()); + // ClientRequest request = ClientRequest + // .method(HttpMethod.POST, uri) + // .body(BodyInserters.fromPublisher(getLatLngs(), Task.class)) + // .build(); + // + // Flux taskResponse = exchange + // .exchange(request) + // .flatMap(response -> response.bodyToFlux(Task.class)); + // + // assertThat(taskResponse.blockFirst()).isInstanceOf(Task.class); + // } -// @Test -// public void givenCheckTask_whenServerHandle_thenOragicServerResponseALiveString() throws Exception { -// URI uri = URI.create("http://localhost:8080/task"); -// ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector()); -// ClientRequest request = ClientRequest -// .method(HttpMethod.GET, uri) -// .body(BodyInserters.fromPublisher(getLatLngs(), Task.class)) -// .build(); -// -// Flux taskResponse = exchange -// .exchange(request) -// .flatMap(response -> response.bodyToFlux(String.class)); -// -// assertThat(taskResponse.blockFirst()).isInstanceOf(String.class); -// } + // @Test + // public void givenCheckTask_whenServerHandle_thenOragicServerResponseALiveString() throws Exception { + // URI uri = URI.create("http://localhost:8080/task"); + // ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector()); + // ClientRequest request = ClientRequest + // .method(HttpMethod.GET, uri) + // .body(BodyInserters.fromPublisher(getLatLngs(), Task.class)) + // .build(); + // + // Flux taskResponse = exchange + // .exchange(request) + // .flatMap(response -> response.bodyToFlux(String.class)); + // + // assertThat(taskResponse.blockFirst()).isInstanceOf(String.class); + // } private static Flux getLatLngs() { - return Flux - .range(0, 3) - .zipWith(Flux.interval(Duration.ofSeconds(1))) - .map(x -> new Task("taskname", 1)) - .doOnNext(ll -> System.out.println("Produced: {}" + ll)); + return Flux.range(0, 3) + .zipWith(Flux.interval(Duration.ofSeconds(1))) + .map(x -> new Task("taskname", 1)) + .doOnNext(ll -> System.out.println("Produced: {}" + ll)); } } diff --git a/spring-5/src/test/java/com/baeldung/web/PathPatternsUsingHandlerMethodIntegrationTest.java b/spring-5/src/test/java/com/baeldung/web/PathPatternsUsingHandlerMethodIntegrationTest.java index 90e3e7c445..c2ed8ff071 100644 --- a/spring-5/src/test/java/com/baeldung/web/PathPatternsUsingHandlerMethodIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/web/PathPatternsUsingHandlerMethodIntegrationTest.java @@ -17,85 +17,85 @@ public class PathPatternsUsingHandlerMethodIntegrationTest { @BeforeClass public static void setUp() { client = WebTestClient.bindToController(new PathPatternController()) - .build(); + .build(); } @Test public void givenHandlerMethod_whenMultipleURIVariablePattern_then200() { client.get() - .uri("/spring5/ab/cd") - .exchange() - .expectStatus() - .is2xxSuccessful() - .expectBody() - .equals("/ab/cd"); + .uri("/spring5/ab/cd") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .equals("/ab/cd"); } @Test public void givenHandlerMethod_whenURLWithWildcardTakingZeroOrMoreChar_then200() { client.get() - .uri("/spring5/userid") - .exchange() - .expectStatus() - .is2xxSuccessful() - .expectBody() - .equals("/spring5/*id"); + .uri("/spring5/userid") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .equals("/spring5/*id"); } @Test public void givenHandlerMethod_whenURLWithWildcardTakingExactlyOneChar_then200() { client.get() - .uri("/string5") - .exchange() - .expectStatus() - .is2xxSuccessful() - .expectBody() - .equals("/s?ring5"); + .uri("/string5") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .equals("/s?ring5"); } @Test public void givenHandlerMethod_whenURLWithWildcardTakingZeroOrMorePathSegments_then200() { client.get() - .uri("/resources/baeldung") - .exchange() - .expectStatus() - .is2xxSuccessful() - .expectBody() - .equals("/resources/**"); + .uri("/resources/baeldung") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .equals("/resources/**"); } @Test public void givenHandlerMethod_whenURLWithRegexInPathVariable_thenExpectedOutput() { client.get() - .uri("/abc") - .exchange() - .expectStatus() - .is2xxSuccessful() - .expectBody() - .equals("abc"); + .uri("/abc") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .equals("abc"); client.get() - .uri("/123") - .exchange() - .expectStatus() - .is4xxClientError(); + .uri("/123") + .exchange() + .expectStatus() + .is4xxClientError(); } @Test public void givenHandlerMethod_whenURLWithMultiplePathVariablesInSameSegment_then200() { client.get() - .uri("/baeldung_tutorial") - .exchange() - .expectStatus() - .is2xxSuccessful() - .expectBody() - .equals("Two variables are var1=baeldung and var2=tutorial"); + .uri("/baeldung_tutorial") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .equals("Two variables are var1=baeldung and var2=tutorial"); } } diff --git a/spring-5/src/test/java/com/baeldung/web/client/WebTestClientTest.java b/spring-5/src/test/java/com/baeldung/web/client/WebTestClientTest.java index 4127f22c01..b05f903b4b 100644 --- a/spring-5/src/test/java/com/baeldung/web/client/WebTestClientTest.java +++ b/spring-5/src/test/java/com/baeldung/web/client/WebTestClientTest.java @@ -21,38 +21,40 @@ public class WebTestClientTest { @LocalServerPort private int port; - private final RouterFunction ROUTER_FUNCTION = RouterFunctions.route( - RequestPredicates.GET("/resource"), - request -> ServerResponse.ok().build() - ); + private final RouterFunction ROUTER_FUNCTION = RouterFunctions.route(RequestPredicates.GET("/resource"), request -> ServerResponse.ok() + .build()); private final WebHandler WEB_HANDLER = exchange -> Mono.empty(); @Test public void testWebTestClientWithServerWebHandler() { - WebTestClient.bindToWebHandler(WEB_HANDLER).build(); + WebTestClient.bindToWebHandler(WEB_HANDLER) + .build(); } @Test public void testWebTestClientWithRouterFunction() { - WebTestClient - .bindToRouterFunction(ROUTER_FUNCTION) - .build().get().uri("/resource") - .exchange() - .expectStatus().isOk() - .expectBody().isEmpty(); + WebTestClient.bindToRouterFunction(ROUTER_FUNCTION) + .build() + .get() + .uri("/resource") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .isEmpty(); } @Test public void testWebTestClientWithServerURL() { - WebTestClient - .bindToServer() - .baseUrl("http://localhost:" + port) - .build() - .get() - .uri("/resource") - .exchange() - .expectStatus().is4xxClientError() - .expectBody(); + WebTestClient.bindToServer() + .baseUrl("http://localhost:" + port) + .build() + .get() + .uri("/resource") + .exchange() + .expectStatus() + .is4xxClientError() + .expectBody(); } } diff --git a/spring-activiti/README.md b/spring-activiti/README.md index fc6eea7f87..3580e29a52 100644 --- a/spring-activiti/README.md +++ b/spring-activiti/README.md @@ -1,3 +1,5 @@ ### Relevant articles - [A Guide to Activiti with Java](http://www.baeldung.com/java-activiti) +- [Introduction to Activiti with Spring](http://www.baeldung.com/spring-activiti) + diff --git a/spring-all/README.md b/spring-all/README.md index 29be01c79e..36bf7da778 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -9,7 +9,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant articles: - [Guide to Spring @Autowired](http://www.baeldung.com/spring-autowire) -- [Properties with Spring](http://www.baeldung.com/2012/02/06/properties-with-spring) - checkout the `org.baeldung.properties` package for all scenarios of properties injection and usage +- [Properties with Spring](http://www.baeldung.com/properties-with-spring) - checkout the `org.baeldung.properties` package for all scenarios of properties injection and usage - [Spring Profiles](http://www.baeldung.com/spring-profiles) - [A Spring Custom Annotation for a Better DAO](http://www.baeldung.com/spring-annotation-bean-pre-processor) - [What's New in Spring 4.3?](http://www.baeldung.com/whats-new-in-spring-4-3/) diff --git a/spring-all/src/main/java/org/baeldung/controller/controller/PassParametersController.java b/spring-all/src/main/java/org/baeldung/controller/controller/PassParametersController.java new file mode 100644 index 0000000000..54047cedf3 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/controller/controller/PassParametersController.java @@ -0,0 +1,38 @@ +package org.baeldung.controller.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +/** + * In this controller, Model, ModelMap and ModelAndView are shown as examples. + * They are all used to pass parameters to JSP pages. + * 04/09/2017 + * + * @author Ahmet Cetin + */ +@Controller +public class PassParametersController { + @RequestMapping(value = "/showViewPage", method = RequestMethod.GET) + public String passParametersWithModel(Model model) { + model.addAttribute("message", "Baeldung"); + return "viewPage"; + } + + @RequestMapping(value = "/printViewPage", method = RequestMethod.GET) + public String passParametersWithModelMap(ModelMap map) { + map.addAttribute("welcomeMessage", "welcome"); + map.addAttribute("message", "Baeldung"); + return "viewPage"; + } + + @RequestMapping(value = "/goToViewPage", method = RequestMethod.GET) + public ModelAndView passParametersWithModelAndView() { + ModelAndView modelAndView = new ModelAndView("viewPage"); + modelAndView.addObject("message", "Baeldung"); + return modelAndView; + } +} \ No newline at end of file diff --git a/spring-all/src/main/webapp/WEB-INF/view/viewPage.jsp b/spring-all/src/main/webapp/WEB-INF/view/viewPage.jsp new file mode 100644 index 0000000000..ca638b33f5 --- /dev/null +++ b/spring-all/src/main/webapp/WEB-INF/view/viewPage.jsp @@ -0,0 +1,11 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + Title + + +
+ Web Application. Passed parameter : ${message} +
+ + diff --git a/spring-all/src/test/java/org/baeldung/controller/PassParametersControllerTest.java b/spring-all/src/test/java/org/baeldung/controller/PassParametersControllerTest.java new file mode 100644 index 0000000000..76ac14f292 --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/controller/PassParametersControllerTest.java @@ -0,0 +1,69 @@ +package org.baeldung.controller; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.ModelAndView; + +/** + * This is the test class for {@link org.baeldung.controller.controller.PassParametersController} class. + * 09/09/2017 + * + * @author Ahmet Cetin + */ +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration({"classpath:test-mvc.xml"}) +public class PassParametersControllerTest { + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext wac; + + @Before + public void setUp() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + } + + @Test + public void testPassParametersWithModel() throws Exception { + ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/showViewPage")).andReturn().getModelAndView(); + + //Validate view + Assert.assertEquals(mv.getViewName(), "viewPage"); + + //Validate attribute + Assert.assertEquals(mv.getModelMap().get("message").toString(), "Baeldung"); + } + + @Test + public void testPassParametersWithModelMap() throws Exception { + ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/printViewPage")).andReturn().getModelAndView(); + + //Validate view + Assert.assertEquals(mv.getViewName(), "viewPage"); + + //Validate attribute + Assert.assertEquals(mv.getModelMap().get("message").toString(), "Baeldung"); + } + + @Test + public void testPassParametersWithModelAndView() throws Exception { + ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/goToViewPage")).andReturn().getModelAndView(); + + //Validate view + Assert.assertEquals(mv.getViewName(), "viewPage"); + + //Validate attribute + Assert.assertEquals(mv.getModelMap().get("message").toString(), "Baeldung"); + } +} diff --git a/spring-batch/README.md b/spring-batch/README.md index 953e652cea..5f226e7fd7 100644 --- a/spring-batch/README.md +++ b/spring-batch/README.md @@ -5,3 +5,4 @@ ### Relevant Articles: - [Introduction to Spring Batch](http://www.baeldung.com/introduction-to-spring-batch) +- [Spring Batch using Partitioner](https://github.com/eugenp/tutorials/tree/master/spring-batch) diff --git a/spring-boot-bootstrap/README.md b/spring-boot-bootstrap/README.md index 75a2b35be7..ec6905bf6a 100644 --- a/spring-boot-bootstrap/README.md +++ b/spring-boot-bootstrap/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: - [Bootstrap a Simple Application using Spring Boot](http://www.baeldung.com/spring-boot-start) +- [Spring Boot Dependency Management with a Custom Parent](http://www.baeldung.com/spring-boot-dependency-management-custom-parent) diff --git a/spring-boot-property-exp/README.md b/spring-boot-property-exp/README.md index 8a598e7a05..70cf6bdfac 100644 --- a/spring-boot-property-exp/README.md +++ b/spring-boot-property-exp/README.md @@ -1,5 +1,5 @@ ## The Module Holds Sources for the Following Articles - - [Automatic Property Expansion with Spring Boot](http://www.baeldung.com/property-expansion-spring-boot) + - [Automatic Property Expansion with Spring Boot](http://www.baeldung.com/spring-boot-auto-property-expansion) ### Module property-exp-default-config This module contains both a standard Maven Spring Boot build and the Gradle build which is Maven compatible. @@ -15,4 +15,4 @@ ### Module property-exp-custom-config This project is not using the standard Spring Boot parent and is configured manually. Run the following command: - `mvn exec:java` \ No newline at end of file + `mvn exec:java` diff --git a/spring-boot/README.MD b/spring-boot/README.MD index e837c88804..5d7eb11954 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -26,4 +26,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [How to Get All Spring-Managed Beans?](http://www.baeldung.com/spring-show-all-beans) - [A Java Client for a WebSockets API](http://www.baeldung.com/websockets-api-java-spring-client) - [Spring Boot and Togglz Aspect](http://www.baeldung.com/spring-togglz) +- [Getting Started with GraphQL and Spring Boot](http://www.baeldung.com/spring-graphql) diff --git a/spring-ldap/README.md b/spring-ldap/README.md index f77572d982..e2517b9d4b 100644 --- a/spring-ldap/README.md +++ b/spring-ldap/README.md @@ -4,6 +4,7 @@ - [Spring LDAP Overview](http://www.baeldung.com/spring-ldap) - [Spring LDAP Example Project](http://www.baeldung.com/spring-ldap-overview/) +- [Guide to Spring Data LDAP](http://www.baeldung.com/spring-data-ldap) diff --git a/spring-ldap/pom.xml b/spring-ldap/pom.xml index 05baf8c66d..2f806e89f8 100644 --- a/spring-ldap/pom.xml +++ b/spring-ldap/pom.xml @@ -3,7 +3,6 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-ldap 0.1-SNAPSHOT jar diff --git a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryIntegrationTest.java similarity index 95% rename from spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java rename to spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryIntegrationTest.java index 9f38af9263..a7c0380867 100644 --- a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java +++ b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryIntegrationTest.java @@ -1,67 +1,67 @@ -package com.baeldung.ldap.client; - -import com.baeldung.ldap.data.service.UserService; -import com.baeldung.ldap.javaconfig.TestConfig; -import org.hamcrest.Matchers; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -@RunWith(SpringJUnit4ClassRunner.class) -@ActiveProfiles("testlive") -@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) -public class LdapDataRepositoryTest { - - private static final String USER2 = "TEST02"; - private static final String USER3 = "TEST03"; - private static final String USER4 = "TEST04"; - - private static final String USER2_PWD = "TEST02"; - private static final String USER3_PWD = "TEST03"; - private static final String USER4_PWD = "TEST04"; - - private static final String SEARCH_STRING = "TEST*"; - - @Autowired - private UserService userService; - - @Test - public void givenLdapClient_whenCorrectCredentials_thenSuccessfulLogin() { - Boolean isValid = userService.authenticate(USER3, USER3_PWD); - assertEquals(true, isValid); - } - - @Test - public void givenLdapClient_whenIncorrectCredentials_thenFailedLogin() { - Boolean isValid = userService.authenticate(USER3, USER2_PWD); - assertEquals(false, isValid); - } - - @Test - public void givenLdapClient_whenCorrectSearchFilter_thenEntriesReturned() { - List userList = userService.search(SEARCH_STRING); - assertThat(userList, Matchers.containsInAnyOrder(USER2, USER3)); - } - - @Test - public void givenLdapClientNotExists_whenDataProvided_thenNewUserCreated() { - userService.create(USER4, USER4_PWD); - userService.authenticate(USER4, USER4_PWD); - } - - @Test - public void givenLdapClientExists_whenDataProvided_thenExistingUserModified() { - userService.modify(USER2, USER3_PWD); - userService.authenticate(USER2, USER3_PWD); - } - -} +package com.baeldung.ldap.client; + +import com.baeldung.ldap.data.service.UserService; +import com.baeldung.ldap.javaconfig.TestConfig; +import org.hamcrest.Matchers; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@ActiveProfiles("testlive") +@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) +public class LdapDataRepositoryIntegrationTest { + + private static final String USER2 = "TEST02"; + private static final String USER3 = "TEST03"; + private static final String USER4 = "TEST04"; + + private static final String USER2_PWD = "TEST02"; + private static final String USER3_PWD = "TEST03"; + private static final String USER4_PWD = "TEST04"; + + private static final String SEARCH_STRING = "TEST*"; + + @Autowired + private UserService userService; + + @Test + public void givenLdapClient_whenCorrectCredentials_thenSuccessfulLogin() { + Boolean isValid = userService.authenticate(USER3, USER3_PWD); + assertEquals(true, isValid); + } + + @Test + public void givenLdapClient_whenIncorrectCredentials_thenFailedLogin() { + Boolean isValid = userService.authenticate(USER3, USER2_PWD); + assertEquals(false, isValid); + } + + @Test + public void givenLdapClient_whenCorrectSearchFilter_thenEntriesReturned() { + List userList = userService.search(SEARCH_STRING); + assertThat(userList, Matchers.containsInAnyOrder(USER2, USER3)); + } + + @Test + public void givenLdapClientNotExists_whenDataProvided_thenNewUserCreated() { + userService.create(USER4, USER4_PWD); + userService.authenticate(USER4, USER4_PWD); + } + + @Test + public void givenLdapClientExists_whenDataProvided_thenExistingUserModified() { + userService.modify(USER2, USER3_PWD); + userService.authenticate(USER2, USER3_PWD); + } + +} diff --git a/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java b/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java index addd1fa088..8cdf89d08a 100644 --- a/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java +++ b/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java @@ -1,5 +1,6 @@ package com.baeldung.springmustache; +import com.samskivert.mustache.Mustache; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.mustache.MustacheEnvironmentCollector; @@ -7,8 +8,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.core.env.Environment; -import com.samskivert.mustache.Mustache; - @SpringBootApplication @ComponentScan(basePackages = {"com.baeldung"}) public class SpringMustacheApplication { @@ -23,11 +22,10 @@ public class SpringMustacheApplication { MustacheEnvironmentCollector collector = new MustacheEnvironmentCollector(); collector.setEnvironment(environment); - Mustache.Compiler compiler = Mustache.compiler() + return Mustache.compiler() .defaultValue("Some Default Value") .withLoader(templateLoader) .withCollector(collector); - return compiler; } } diff --git a/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java b/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java index b24625e7d5..5fc34c9f07 100644 --- a/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java +++ b/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java @@ -1,31 +1,26 @@ package com.baeldung.springmustache.controller; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; -import java.util.stream.IntStream; - +import com.baeldung.springmustache.model.Article; import org.fluttercode.datafactory.impl.DataFactory; -import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.ModelAndView; -import com.baeldung.springmustache.model.Article; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.IntStream; @Controller public class ArticleController { - @RequestMapping("/article") + @GetMapping("/article") public ModelAndView displayArticle(Map model) { - List
articles = new LinkedList<>(); - IntStream.range(0, 10) - .forEach(count -> { - articles.add(generateArticle("Article Title " + count)); - }); + List
articles = IntStream.range(0, 10) + .mapToObj(i -> generateArticle("Article Title " + i)) + .collect(Collectors.toList()); Map modelMap = new HashMap<>(); modelMap.put("articles", articles); diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/BeanA.java b/spring-mvc-java/src/main/java/com/baeldung/web/BeanA.java index 79fac724f7..60da29f354 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/BeanA.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/BeanA.java @@ -12,5 +12,4 @@ public class BeanA { public BeanA() { super(); } - } diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/BeanB.java b/spring-mvc-java/src/main/java/com/baeldung/web/BeanB.java index 05c9560a0c..9e713d59ab 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/BeanB.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/BeanB.java @@ -8,5 +8,4 @@ public class BeanB { public BeanB() { super(); } - } diff --git a/spring-mvc-kotlin/pom.xml b/spring-mvc-kotlin/pom.xml index 264cf49817..2d1dac5e29 100644 --- a/spring-mvc-kotlin/pom.xml +++ b/spring-mvc-kotlin/pom.xml @@ -45,6 +45,12 @@ thymeleaf-spring4 3.0.7.RELEASE + + org.springframework + spring-test + 4.3.10.RELEASE + test + @@ -55,7 +61,12 @@ kotlin-maven-plugin org.jetbrains.kotlin 1.1.4 - + + + spring + + 1.8 + compile @@ -64,7 +75,6 @@ compile - test-compile test-compile @@ -73,6 +83,13 @@ + + + org.jetbrains.kotlin + kotlin-maven-allopen + 1.1.4-3 + + diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/allopen/SimpleConfiguration.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/allopen/SimpleConfiguration.kt new file mode 100644 index 0000000000..5d0a3e13bf --- /dev/null +++ b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/allopen/SimpleConfiguration.kt @@ -0,0 +1,7 @@ +package com.baeldung.kotlin.allopen + +import org.springframework.context.annotation.Configuration + +@Configuration +class SimpleConfiguration { +} \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebConfig.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebConfig.kt index ec1c4e9511..23aadf282a 100644 --- a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebConfig.kt +++ b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebConfig.kt @@ -12,13 +12,9 @@ import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver import org.thymeleaf.spring4.view.ThymeleafViewResolver import org.thymeleaf.templatemode.TemplateMode - - - - @EnableWebMvc @Configuration -open class ApplicationWebConfig: WebMvcConfigurerAdapter(), ApplicationContextAware { +open class ApplicationWebConfig : WebMvcConfigurerAdapter(), ApplicationContextAware { private var applicationContext: ApplicationContext? = null @@ -34,27 +30,23 @@ open class ApplicationWebConfig: WebMvcConfigurerAdapter(), ApplicationContextAw @Bean open fun templateResolver(): SpringResourceTemplateResolver { - val templateResolver = SpringResourceTemplateResolver() - templateResolver.prefix = "/WEB-INF/view/" - templateResolver.suffix = ".html" - templateResolver.templateMode = TemplateMode.HTML - templateResolver.setApplicationContext(this.applicationContext); - return templateResolver + return SpringResourceTemplateResolver() + .apply { prefix = "/WEB-INF/view/" } + .apply { suffix = ".html"} + .apply { templateMode = TemplateMode.HTML } + .apply { setApplicationContext(applicationContext) } } @Bean open fun templateEngine(): SpringTemplateEngine { - val templateEngine = SpringTemplateEngine() - templateEngine.setTemplateResolver(templateResolver()) - return templateEngine + return SpringTemplateEngine() + .apply { setTemplateResolver(templateResolver()) } } @Bean open fun viewResolver(): ThymeleafViewResolver { - val viewResolver = ThymeleafViewResolver() - viewResolver.templateEngine = templateEngine() - viewResolver.order = 1 - return viewResolver + return ThymeleafViewResolver() + .apply { templateEngine = templateEngine() } + .apply { order = 1 } } - } \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebInitializer.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebInitializer.kt index a4d1614271..4c1a35823c 100644 --- a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebInitializer.kt +++ b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebInitializer.kt @@ -1,9 +1,8 @@ package com.baeldung.kotlin.mvc -import com.baeldung.kotlin.mvc.ApplicationWebConfig import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer -class ApplicationWebInitializer: AbstractAnnotationConfigDispatcherServletInitializer() { +class ApplicationWebInitializer : AbstractAnnotationConfigDispatcherServletInitializer() { override fun getRootConfigClasses(): Array>? { return null diff --git a/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/allopen/SimpleConfigurationTest.kt b/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/allopen/SimpleConfigurationTest.kt new file mode 100644 index 0000000000..65a60c7157 --- /dev/null +++ b/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/allopen/SimpleConfigurationTest.kt @@ -0,0 +1,19 @@ +package com.baeldung.kotlin.allopen + +import org.junit.Test +import org.junit.runner.RunWith +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner +import org.springframework.test.context.support.AnnotationConfigContextLoader + +@RunWith(SpringJUnit4ClassRunner::class) +@ContextConfiguration( + loader = AnnotationConfigContextLoader::class, + classes = arrayOf(SimpleConfiguration::class)) +class SimpleConfigurationTest { + + @Test + fun contextLoads() { + } + +} \ No newline at end of file diff --git a/spring-mvc-simple/README.md b/spring-mvc-simple/README.md index ffb02c846a..197a22cbac 100644 --- a/spring-mvc-simple/README.md +++ b/spring-mvc-simple/README.md @@ -1,3 +1,4 @@ ## Relevant articles: - [HandlerAdapters in Spring MVC](http://www.baeldung.com/spring-mvc-handler-adapters) +- [Template Engines for Spring](http://www.baeldung.com/spring-template-engines) diff --git a/spring-rest-angular/README.md b/spring-rest-angular/README.md new file mode 100644 index 0000000000..3c1b418d95 --- /dev/null +++ b/spring-rest-angular/README.md @@ -0,0 +1,4 @@ +## Spring REST Angular Example Project + +### Relevant Articles: + diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml index 06741bfd0c..3fc429f626 100644 --- a/spring-rest-angular/pom.xml +++ b/spring-rest-angular/pom.xml @@ -1,11 +1,10 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 spring-rest-angular spring-rest-angular - com.baeldung 1.0 war @@ -95,6 +94,7 @@ **/*IntegrationTest.java + **/*UnitTest.java @@ -113,6 +113,7 @@ 19.0 3.5 + org.baeldung.web.main.Application diff --git a/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java b/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java index 48c985fb9d..4d65c02fff 100644 --- a/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java +++ b/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java @@ -1,10 +1,5 @@ package org.baeldung.web.service; -import static io.restassured.RestAssured.given; -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsCollectionContaining.hasItems; -import static org.hamcrest.core.IsEqual.equalTo; - import org.apache.commons.lang3.RandomStringUtils; import org.baeldung.web.main.Application; import org.junit.Test; @@ -13,6 +8,11 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; +import static io.restassured.RestAssured.given; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsCollectionContaining.hasItems; +import static org.hamcrest.core.IsEqual.equalTo; + @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) public class StudentServiceIntegrationTest { @@ -21,7 +21,8 @@ public class StudentServiceIntegrationTest { @Test public void givenRequestForStudents_whenPageIsOne_expectContainsNames() { - given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("content.name", hasItems("Bryan", "Ben")); + given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat() + .body("content.name", hasItems("Bryan", "Ben")); } @Test @@ -58,5 +59,4 @@ public class StudentServiceIntegrationTest { public void givenResourcesExist_whenFirstPageIsRetrieved_thenPageContainsResources() { given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("first", equalTo(true)); } - } diff --git a/spring-rest/README.md b/spring-rest/README.md index 2cea315188..7c0ba325b7 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -16,3 +16,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [HTTP PUT vs HTTP PATCH in a REST API](http://www.baeldung.com/http-put-patch-difference-spring) - [Exploring the Spring Boot TestRestTemplate](http://www.baeldung.com/spring-boot-testresttemplate) - [Spring – Log Incoming Requests](http://www.baeldung.com/spring-http-logging) +- [RequestBody and ResponseBody Annotations](http://www.baeldung.com/requestbody-and-responsebody-annotations) diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 6065d7e529..06747ffd41 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -199,7 +199,6 @@ cargo-maven2-plugin ${cargo-maven2-plugin.version} - true tomcat8x embedded @@ -240,6 +239,7 @@ **/*IntegrationTest.java + **/*UnitTest.java diff --git a/spring-rest/src/main/java/com/baeldung/controllers/ExamplePostController.java b/spring-rest/src/main/java/com/baeldung/controllers/ExamplePostController.java new file mode 100644 index 0000000000..93f96756b4 --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/controllers/ExamplePostController.java @@ -0,0 +1,38 @@ +package com.baeldung.controllers; + +import com.baeldung.services.ExampleService; +import com.baeldung.transfer.ResponseTransfer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import com.baeldung.transfer.LoginForm; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping("/post") +public class ExamplePostController { + + private static Logger log = LoggerFactory.getLogger(ExamplePostController.class); + + @Autowired ExampleService exampleService; + + @PostMapping("/request") + public ResponseEntity postController(@RequestBody LoginForm loginForm) { + log.debug("POST received - serializing LoginForm: " + loginForm.getPassword() + " " + loginForm.getUsername()); + exampleService.fakeAuthenticate(loginForm); + return ResponseEntity.ok(HttpStatus.OK); + } + + @PostMapping("/response") + @ResponseBody + public ResponseTransfer postResponseController(@RequestBody LoginForm loginForm) { + log.debug("POST received - serializing LoginForm: " + loginForm.getPassword() + " " + loginForm.getUsername()); + return new ResponseTransfer("Thanks For Posting!!!"); + } +} \ No newline at end of file diff --git a/spring-rest/src/main/java/com/baeldung/controllers/ViewController.java b/spring-rest/src/main/java/com/baeldung/controllers/ViewController.java new file mode 100644 index 0000000000..8eab0ce6da --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/controllers/ViewController.java @@ -0,0 +1,14 @@ +package com.baeldung.controllers; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class ViewController { + + @GetMapping("/") + public String welcome() { + return "index"; + } + +} diff --git a/spring-rest/src/main/java/com/baeldung/services/ExampleService.java b/spring-rest/src/main/java/com/baeldung/services/ExampleService.java new file mode 100644 index 0000000000..48d98b41db --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/services/ExampleService.java @@ -0,0 +1,12 @@ +package com.baeldung.services; + +import com.baeldung.transfer.LoginForm; +import org.springframework.stereotype.Service; + +@Service +public class ExampleService { + + public boolean fakeAuthenticate(LoginForm lf) { + return true; + } +} \ No newline at end of file diff --git a/spring-rest/src/main/java/com/baeldung/transfer/LoginForm.java b/spring-rest/src/main/java/com/baeldung/transfer/LoginForm.java new file mode 100644 index 0000000000..19c9b0a349 --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/transfer/LoginForm.java @@ -0,0 +1,25 @@ +package com.baeldung.transfer; + +public class LoginForm { + private String username; + private String password; + + public LoginForm() { + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} \ No newline at end of file diff --git a/spring-rest/src/main/java/com/baeldung/transfer/ResponseTransfer.java b/spring-rest/src/main/java/com/baeldung/transfer/ResponseTransfer.java new file mode 100644 index 0000000000..d4fb282c1b --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/transfer/ResponseTransfer.java @@ -0,0 +1,18 @@ +package com.baeldung.transfer; + +public class ResponseTransfer { + + private String text; + + public ResponseTransfer(String text) { + this.setText(text); + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } +} \ No newline at end of file diff --git a/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerRequestUnitTest.java b/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerRequestUnitTest.java new file mode 100644 index 0000000000..c20f968704 --- /dev/null +++ b/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerRequestUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.controllers; + +import com.baeldung.services.ExampleService; +import com.baeldung.transfer.LoginForm; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.baeldung.config.MainApplication; + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = MainApplication.class) +public class ExamplePostControllerRequestUnitTest { + + MockMvc mockMvc; + @Mock private ExampleService exampleService; + @InjectMocks private ExamplePostController exampleController; + private final String jsonBody = "{\"username\": \"username\", \"password\": \"password\"}"; + private LoginForm lf = new LoginForm(); + + @Before + public void preTest() { + MockitoAnnotations.initMocks(this); + mockMvc = MockMvcBuilders + .standaloneSetup(exampleController) + .build(); + lf.setPassword("password"); + lf.setUsername("username"); + } + + @Test + public void requestBodyTest() { + try { + when(exampleService.fakeAuthenticate(lf)).thenReturn(true); + mockMvc + .perform(post("/post/request") + .content(jsonBody) + .contentType("application/json")) + .andDo(print()) + .andExpect(status().isOk()); + } catch (Exception e) { + System.out.println("Exception: " + e); + } + } +} \ No newline at end of file diff --git a/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerResponseUnitTest.java b/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerResponseUnitTest.java new file mode 100644 index 0000000000..3d09622c47 --- /dev/null +++ b/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerResponseUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.controllers; + +import com.baeldung.services.ExampleService; +import com.baeldung.transfer.LoginForm; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import org.baeldung.config.MainApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = MainApplication.class) +public class ExamplePostControllerResponseUnitTest { + + MockMvc mockMvc; + @Mock private ExampleService exampleService; + @InjectMocks private ExamplePostController exampleController; + private final String jsonBody = "{\"username\": \"username\", \"password\": \"password\"}"; + private LoginForm lf = new LoginForm(); + + @Before + public void preTest() { + MockitoAnnotations.initMocks(this); + mockMvc = MockMvcBuilders + .standaloneSetup(exampleController) + .build(); + lf.setPassword("password"); + lf.setUsername("username"); + } + + @Test + public void requestBodyTest() { + try { + when(exampleService.fakeAuthenticate(lf)).thenReturn(true); + mockMvc + .perform(post("/post/response") + .content(jsonBody) + .contentType("application/json")) + .andDo(print()) + .andExpect(status().isOk()) + .andExpect(content().json("{\"text\":\"Thanks For Posting!!!\"}")); + } catch (Exception e) { + System.out.println("Exception: " + e); + } + } +} \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java new file mode 100644 index 0000000000..d7195ac358 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java @@ -0,0 +1,38 @@ +package org.baeldung.rolesauthorities; + +import org.baeldung.rolesauthorities.model.User; +import org.baeldung.rolesauthorities.persistence.UserRepository; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.userdetails.UserDetailsService; + +public class CustomAuthenticationProvider extends DaoAuthenticationProvider { + + private final UserRepository userRepository; + @SuppressWarnings("unused") + private UserDetailsService userDetailsService; + + public CustomAuthenticationProvider(UserRepository userRepository, UserDetailsService userDetailsService){ + super(); + this.setUserDetailsService(userDetailsService); + this.userRepository = userRepository; + } + + @Override + public Authentication authenticate(Authentication auth) throws AuthenticationException { + final User user = userRepository.findByEmail(auth.getName()); + if ((user == null)) { + throw new BadCredentialsException("Invalid username or password"); + } + final Authentication result = super.authenticate(auth); + return new UsernamePasswordAuthenticationToken(user, result.getCredentials(), result.getAuthorities()); + } + + @Override + public boolean supports(Class authentication) { + return authentication.equals(UsernamePasswordAuthenticationToken.class); + } +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java new file mode 100644 index 0000000000..b0dc0b7537 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java @@ -0,0 +1,26 @@ +package org.baeldung.rolesauthorities; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; +import org.springframework.stereotype.Component; + +@Component("myLogoutSuccessHandler") +public class MyLogoutSuccessHandler implements LogoutSuccessHandler { + + @Override + public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { + final HttpSession session = request.getSession(); + if (session != null) { + session.removeAttribute("user"); + } + + response.sendRedirect("/"); + } +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java new file mode 100644 index 0000000000..f38b867a75 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java @@ -0,0 +1,61 @@ +package org.baeldung.rolesauthorities; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; + +import org.baeldung.rolesauthorities.model.Role; +import org.baeldung.rolesauthorities.model.User; +import org.baeldung.rolesauthorities.persistence.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service("userDetailsService") +@Transactional +public class MyUserDetailsService implements UserDetailsService { + + @Autowired + private UserRepository userRepository; + + public MyUserDetailsService() { + super(); + } + + // API + + @Override + public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { + + try { + User user = userRepository.findByEmail(email); + if (user == null) { + throw new UsernameNotFoundException("No user found with username: " + email); + } + org.springframework.security.core.userdetails.User userDetails = new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), user.isEnabled(), true, true, true, getAuthorities(user.getRoles())); + return userDetails; + } catch (final Exception e) { + throw new RuntimeException(e); + } + } + + // UTIL + + private final Collection getAuthorities(Collection roles) { + List authorities = new ArrayList(); + for (Role role: roles) { + authorities.add(new SimpleGrantedAuthority(role.getName())); + authorities.addAll(role.getPrivileges() + .stream() + .map(p -> new SimpleGrantedAuthority(p.getName())) + .collect(Collectors.toList())); + } + return authorities; + } +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java new file mode 100644 index 0000000000..1c55c145b3 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java @@ -0,0 +1,17 @@ +package org.baeldung.rolesauthorities; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableAutoConfiguration +@ComponentScan("org.baeldung.rolesauthorities") +public class RolesAuthoritiesApplication extends SpringBootServletInitializer { + public static void main(String[] args) { + System.setProperty("spring.profiles.default", "rolesauthorities"); + SpringApplication.run(RolesAuthoritiesApplication.class, args); + } +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java new file mode 100644 index 0000000000..d2edfed749 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java @@ -0,0 +1,47 @@ +package org.baeldung.rolesauthorities.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +@EnableWebMvc +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + // + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } + + @Override + public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("forward:/home"); + registry.addViewController("/protectedbynothing").setViewName("rolesauthorities/protectedbynothing"); + registry.addViewController("/protectedbyrole").setViewName("rolesauthorities/protectedbyrole"); + registry.addViewController("/protectedbyauthority").setViewName("rolesauthorities/protectedbyauthority"); + registry.addViewController("/login").setViewName("rolesauthorities/login"); + registry.addViewController("/home").setViewName("rolesauthorities/home"); + registry.addViewController("/logout"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } +} \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java new file mode 100644 index 0000000000..7624dd7d39 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java @@ -0,0 +1,90 @@ +package org.baeldung.rolesauthorities.config; + +import org.baeldung.rolesauthorities.CustomAuthenticationProvider; +import org.baeldung.rolesauthorities.persistence.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; + +@Configuration +@ComponentScan(basePackages = { "org.baeldung.rolesauthorities" }) +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private UserRepository userRepository; + + @Autowired + private UserDetailsService userDetailsService; + + @Autowired + private LogoutSuccessHandler myLogoutSuccessHandler; + + public SecurityConfig() { + super(); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.authenticationProvider(authProvider()); + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring() + .antMatchers("/resources/**"); + } + + + @Override + protected void configure(HttpSecurity http) throws Exception { + + // @formatter:off + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/login*", "/logout*", "/protectedbynothing*", "/home*").permitAll() + .antMatchers("/protectedbyrole").hasRole("USER") + .antMatchers("/protectedbyauthority").hasAuthority("READ_PRIVILEGE") + .and() + .formLogin() + .loginPage("/login") + .failureUrl("/login?error=true") + .permitAll() + .and() + .logout() + .logoutSuccessHandler(myLogoutSuccessHandler) + .invalidateHttpSession(false) + .logoutSuccessUrl("/logout.html?logSucc=true") + .deleteCookies("JSESSIONID") + .permitAll(); + // @formatter:on + } + + // beans + + @Bean + public DaoAuthenticationProvider authProvider() { + final CustomAuthenticationProvider authProvider + = new CustomAuthenticationProvider(userRepository, userDetailsService); + authProvider.setPasswordEncoder(encoder()); + return authProvider; + } + + @Bean + public PasswordEncoder encoder() { + return new BCryptPasswordEncoder(11); + } + +} \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java new file mode 100644 index 0000000000..ab2cd08610 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java @@ -0,0 +1,89 @@ +package org.baeldung.rolesauthorities.model; + +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +@Entity +public class Privilege { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String name; + + @ManyToMany(mappedBy = "privileges") + private Collection roles; + + public Privilege() { + super(); + } + + public Privilege(String name) { + super(); + this.name = name; + } + + // + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Collection getRoles() { + return roles; + } + + public void setRoles(Collection roles) { + this.roles = roles; + } + + @Override + public int hashCode() { + 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; + Privilege other = (Privilege) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Privilege [name=").append(name).append("]").append("[id=").append(id).append("]"); + return builder.toString(); + } +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Role.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Role.java new file mode 100644 index 0000000000..ac33e32fcf --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Role.java @@ -0,0 +1,104 @@ +package org.baeldung.rolesauthorities.model; + +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; + +@Entity +public class Role { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @ManyToMany(mappedBy = "roles") + private Collection users; + + @ManyToMany + @JoinTable(name = "roles_privileges", joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "privilege_id", referencedColumnName = "id")) + private Collection privileges; + + private String name; + + public Role() { + super(); + } + + public Role(String name) { + super(); + this.name = name; + } + + // + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Collection getUsers() { + return users; + } + + public void setUsers(Collection users) { + this.users = users; + } + + public Collection getPrivileges() { + return privileges; + } + + public void setPrivileges(Collection privileges) { + this.privileges = privileges; + } + + @Override + public int hashCode() { + 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; + } + Role role = (Role) obj; + if (!role.equals(role.name)) { + return false; + } + return true; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Role [name=").append(name).append("]").append("[id=").append(id).append("]"); + return builder.toString(); + } +} \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/User.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/User.java new file mode 100644 index 0000000000..dc1096541d --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/User.java @@ -0,0 +1,147 @@ +package org.baeldung.rolesauthorities.model; + +import java.util.Collection; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.Table; + + +@Entity +@Table(name = "user_account") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String firstName; + + private String lastName; + + private String email; + + @Column(length = 60) + private String password; + + private boolean enabled; + + private boolean isUsing2FA; + + // + + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) + private Collection roles; + + public User() { + super(); + this.enabled = false; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String username) { + this.email = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Collection getRoles() { + return roles; + } + + public void setRoles(Collection roles) { + this.roles = roles; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public boolean isUsing2FA() { + return isUsing2FA; + } + + public void setUsing2FA(boolean isUsing2FA) { + this.isUsing2FA = isUsing2FA; + } + + @Override + public int hashCode() { + int prime = 31; + int result = 1; + result = (prime * result) + ((email == null) ? 0 : email.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; + } + User user = (User) obj; + if (!email.equals(user.email)) { + return false; + } + return true; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("User [id=").append(id).append(", firstName=") + .append(firstName).append(", lastName=").append(lastName).append(", email=").append(email).append(", password=").append(password).append(", enabled=").append(enabled).append(", roles=").append(roles).append("]"); + return builder.toString(); + } + +} \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java new file mode 100644 index 0000000000..2c508cbd20 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java @@ -0,0 +1,9 @@ +package org.baeldung.rolesauthorities.persistence; + +import org.baeldung.rolesauthorities.model.User; + +public interface IUserService { + + User findUserByEmail(String email); + +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PersistenceJPAConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PersistenceJPAConfig.java new file mode 100644 index 0000000000..a993e41a83 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PersistenceJPAConfig.java @@ -0,0 +1,77 @@ +package org.baeldung.rolesauthorities.persistence; + +import java.util.Properties; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence.properties" }) +@ComponentScan({ "org.baeldung.rolesauthorities.persistence" }) +@EnableJpaRepositories(basePackages = "org.baeldung.rolesauthorities.persistence") +public class PersistenceJPAConfig { + + @Autowired + private Environment env; + + public PersistenceJPAConfig() { + super(); + } + + // + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[] { "org.baeldung.rolesauthorities" }); + HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + return em; + } + + @Bean + public DataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); + dataSource.setUrl(env.getProperty("jdbc.url")); + dataSource.setUsername(env.getProperty("jdbc.user")); + dataSource.setPassword(env.getProperty("jdbc.pass")); + return dataSource; + } + + @Bean + public JpaTransactionManager transactionManager() { + JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + protected Properties additionalProperties() { + Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + return hibernateProperties; + } + +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java new file mode 100644 index 0000000000..05d5f2b870 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java @@ -0,0 +1,12 @@ +package org.baeldung.rolesauthorities.persistence; + +import org.baeldung.rolesauthorities.model.Privilege; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PrivilegeRepository extends JpaRepository { + + Privilege findByName(String name); + + void delete(Privilege privilege); + +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java new file mode 100644 index 0000000000..25e3b3a1f6 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java @@ -0,0 +1,12 @@ +package org.baeldung.rolesauthorities.persistence; + +import org.baeldung.rolesauthorities.model.Role; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface RoleRepository extends JpaRepository { + + Role findByName(String name); + + void delete(Role role); + +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java new file mode 100644 index 0000000000..46dad4f06d --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java @@ -0,0 +1,97 @@ +package org.baeldung.rolesauthorities.persistence; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import org.baeldung.rolesauthorities.model.Privilege; +import org.baeldung.rolesauthorities.model.Role; +import org.baeldung.rolesauthorities.model.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationListener; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + + +@Component +public class SetupDataLoader implements ApplicationListener { + + private boolean alreadySetup = false; + + @Autowired + private UserRepository userRepository; + + @Autowired + private RoleRepository roleRepository; + + @Autowired + private PrivilegeRepository privilegeRepository; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Override + @Transactional + public void onApplicationEvent(ContextRefreshedEvent event) { + if (alreadySetup) { + return; + } + + // == create initial privileges + Privilege readPrivilege = createPrivilegeIfNotFound("READ_PRIVILEGE"); + Privilege writePrivilege = createPrivilegeIfNotFound("WRITE_PRIVILEGE"); + + // == create initial roles + List adminPrivileges = Arrays.asList(readPrivilege, writePrivilege); + createRoleIfNotFound("ROLE_ADMIN", adminPrivileges); + List rolePrivileges = new ArrayList<>(); + createRoleIfNotFound("ROLE_USER", rolePrivileges); + + Role adminRole = roleRepository.findByName("ROLE_ADMIN"); + User user = new User(); + user.setFirstName("Admin"); + user.setLastName("Admin"); + user.setEmail("admin@test.com"); + user.setPassword(passwordEncoder.encode("admin")); + user.setRoles(Arrays.asList(adminRole)); + user.setEnabled(true); + userRepository.save(user); + + Role basicRole = roleRepository.findByName("ROLE_USER"); + User basicUser = new User(); + basicUser.setFirstName("User"); + basicUser.setLastName("User"); + basicUser.setEmail("user@test.com"); + basicUser.setPassword(passwordEncoder.encode("user")); + basicUser.setRoles(Arrays.asList(basicRole)); + basicUser.setEnabled(true); + userRepository.save(basicUser); + + alreadySetup = true; + } + + @Transactional + private Privilege createPrivilegeIfNotFound(String name) { + Privilege privilege = privilegeRepository.findByName(name); + if (privilege == null) { + privilege = new Privilege(name); + privilegeRepository.save(privilege); + } + return privilege; + } + + @Transactional + private Role createRoleIfNotFound(String name, Collection privileges) { + Role role = roleRepository.findByName(name); + if (role == null) { + role = new Role(name); + role.setPrivileges(privileges); + roleRepository.save(role); + } + return role; + } + +} \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java new file mode 100644 index 0000000000..bca2953153 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java @@ -0,0 +1,12 @@ +package org.baeldung.rolesauthorities.persistence; + +import org.baeldung.rolesauthorities.model.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { + + User findByEmail(String email); + + void delete(User user); + +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java new file mode 100644 index 0000000000..3b16c78898 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java @@ -0,0 +1,19 @@ +package org.baeldung.rolesauthorities.persistence; + +import javax.transaction.Transactional; + +import org.baeldung.rolesauthorities.model.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +@Transactional +public class UserService implements IUserService { + + @Autowired + private UserRepository repository; + + public User findUserByEmail(String email) { + return repository.findByEmail(email); + } +} \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/application-rolesauthorities.properties b/spring-security-mvc-boot/src/main/resources/application-rolesauthorities.properties new file mode 100644 index 0000000000..030c79c542 --- /dev/null +++ b/spring-security-mvc-boot/src/main/resources/application-rolesauthorities.properties @@ -0,0 +1,10 @@ +server.port=8082 +server.context-path=/ +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.url=jdbc:h2:mem:security_permission;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE +spring.datasource.username=sa +spring.datasource.password= +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.database=H2 +spring.jpa.show-sql=false +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/persistence.properties b/spring-security-mvc-boot/src/main/resources/persistence.properties new file mode 100644 index 0000000000..b2255cd479 --- /dev/null +++ b/spring-security-mvc-boot/src/main/resources/persistence.properties @@ -0,0 +1,11 @@ +####### H2 +#################### DataSource Configuration ########################## +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:registration_02;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE +jdbc.user=sa +jdbc.pass= +init-db=false +#################### Hibernate Configuration ########################## +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/home.html b/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/home.html new file mode 100644 index 0000000000..a302721570 --- /dev/null +++ b/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/home.html @@ -0,0 +1,25 @@ + + + + + +Role vs Granted Authority Example + + + + + + + + \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/login.html b/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/login.html new file mode 100644 index 0000000000..eacde18459 --- /dev/null +++ b/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/login.html @@ -0,0 +1,57 @@ + + + + +Login + + + + + + +
+
+

Login

+

+ +
+ + + + +

+ + + +

+ + +
+
+
+ + + \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyauthority.html b/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyauthority.html new file mode 100644 index 0000000000..c62a111ebc --- /dev/null +++ b/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyauthority.html @@ -0,0 +1,24 @@ + + + + +Protected By Authority + + + +
+

Protected By Authority

+
+ + + + diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbynothing.html b/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbynothing.html new file mode 100644 index 0000000000..a6cd0666db --- /dev/null +++ b/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbynothing.html @@ -0,0 +1,21 @@ + + + + +Protected By Nothing + + + +
+

Protected By Nothing

+
+ + + + diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyrole.html b/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyrole.html new file mode 100644 index 0000000000..f4bac55b55 --- /dev/null +++ b/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyrole.html @@ -0,0 +1,24 @@ + + + + +Protected By Role + + + +
+

Protected By Role

+
+ + + + diff --git a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SecurityConfig.java b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SecurityConfig.java index 7006619d35..d7b57d1829 100644 --- a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SecurityConfig.java +++ b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SecurityConfig.java @@ -88,8 +88,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { .authorizeRequests() .antMatchers("/", "/index", "/authenticate") .permitAll() - .antMatchers("/secured/**/**", - "/secured/success", "/secured/socket", "/secured/success") + .antMatchers("/secured/**/**", "/secured/socket", "/secured/success") .authenticated() .anyRequest().authenticated() .and() diff --git a/spring-security-rest-basic-auth/README.md b/spring-security-rest-basic-auth/README.md index 43ab08b8ca..f92fcfe36b 100644 --- a/spring-security-rest-basic-auth/README.md +++ b/spring-security-rest-basic-auth/README.md @@ -6,8 +6,8 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: -- [RestTemplate with Basic Authentication in Spring](http://www.baeldung.com/2012/04/16/how-to-use-resttemplate-with-basic-authentication-in-spring-3-1) +- [RestTemplate with Basic Authentication in Spring](http://www.baeldung.com/how-to-use-resttemplate-with-basic-authentication-in-spring) - [HttpClient Timeout](http://www.baeldung.com/httpclient-timeout) - [HttpClient with SSL](http://www.baeldung.com/httpclient-ssl) - [Writing a Custom Filter in Spring Security](http://www.baeldung.com/spring-security-custom-filter) -- [Spring Security Basic Authentication](http://www.baeldung.com/spring-security-basic-authentication) \ No newline at end of file +- [Spring Security Basic Authentication](http://www.baeldung.com/spring-security-basic-authentication) diff --git a/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java index c0ad5eb690..a222224c59 100644 --- a/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java @@ -2,12 +2,10 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import org.springframework.web.context.request.RequestContextListener; -@EnableOAuth2Sso @SpringBootApplication public class UiApplication extends SpringBootServletInitializer { diff --git a/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java index 5dbe9ada34..f9119e20f5 100644 --- a/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java +++ b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java @@ -1,9 +1,11 @@ package org.baeldung.config; +import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +@EnableOAuth2Sso @Configuration public class UiSecurityConfig extends WebSecurityConfigurerAdapter { diff --git a/spring-swagger-codegen/pom.xml b/spring-swagger-codegen/pom.xml new file mode 100644 index 0000000000..79e244d2db --- /dev/null +++ b/spring-swagger-codegen/pom.xml @@ -0,0 +1,12 @@ + + 4.0.0 + com.baeldung + spring-swagger-codegen + 0.0.1-SNAPSHOT + pom + + spring-swagger-codegen-api-client + spring-swagger-codegen-app + + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/.gitignore b/spring-swagger-codegen/spring-swagger-codegen-api-client/.gitignore new file mode 100644 index 0000000000..a530464afa --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/.gitignore @@ -0,0 +1,21 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# build files +**/target +target +.gradle +build diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/.swagger-codegen-ignore b/spring-swagger-codegen/spring-swagger-codegen-api-client/.swagger-codegen-ignore new file mode 100644 index 0000000000..c5fa491b4c --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/.swagger-codegen/VERSION b/spring-swagger-codegen/spring-swagger-codegen-api-client/.swagger-codegen/VERSION new file mode 100644 index 0000000000..6b4d157738 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.2.3 \ No newline at end of file diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/.travis.yml b/spring-swagger-codegen/spring-swagger-codegen-api-client/.travis.yml new file mode 100644 index 0000000000..70cb81a67c --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/.travis.yml @@ -0,0 +1,17 @@ +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +language: java +jdk: + - oraclejdk8 + - oraclejdk7 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + - mvn test + # uncomment below to test using gradle + # - gradle test + # uncomment below to test using sbt + # - sbt test diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/README.md b/spring-swagger-codegen/spring-swagger-codegen-api-client/README.md new file mode 100644 index 0000000000..b1b7a63a9c --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/README.md @@ -0,0 +1,155 @@ +# spring-swagger-codegen-api-client + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn deploy +``` + +Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + com.baeldung + spring-swagger-codegen-api-client + 0.0.1-SNAPSHOT + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "com.baeldung:spring-swagger-codegen-api-client:0.0.1-SNAPSHOT" +``` + +### Others + +At first generate the JAR by executing: + + mvn package + +Then manually install the following JARs: + +* target/spring-swagger-codegen-api-client-0.0.1-SNAPSHOT.jar +* target/lib/*.jar + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java + +import com.baeldung.petstore.client.invoker.*; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.model.*; +import com.baeldung.petstore.client.api.PetApi; + +import java.io.File; +import java.util.*; + +public class PetApiExample { + + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(); + Pet body = new Pet(); // Pet | Pet object that needs to be added to the store + try { + apiInstance.addPet(body); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + +## Documentation for Models + + - [Category](docs/Category.md) + - [ModelApiResponse](docs/ModelApiResponse.md) + - [Order](docs/Order.md) + - [Pet](docs/Pet.md) + - [Tag](docs/Tag.md) + - [User](docs/User.md) + + +## Documentation for Authorization + +Authentication schemes defined for the API: +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. + +## Author + +apiteam@swagger.io + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/build.gradle b/spring-swagger-codegen/spring-swagger-codegen-api-client/build.gradle new file mode 100644 index 0000000000..36716a3436 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/build.gradle @@ -0,0 +1,114 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'com.baeldung' +version = '0.0.1-SNAPSHOT' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.5.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 23 + buildToolsVersion '23.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'spring-swagger-codegen-api-client' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.15" + jackson_version = "2.8.9" + spring_web_version = "4.3.9.RELEASE" + jodatime_version = "2.9.9" + junit_version = "4.12" +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "org.springframework:spring-web:$spring_web_version" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" + compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version" + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" + compile "joda-time:joda-time:$jodatime_version" + testCompile "junit:junit:$junit_version" +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/build.sbt b/spring-swagger-codegen/spring-swagger-codegen-api-client/build.sbt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/Category.md b/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/Category.md new file mode 100644 index 0000000000..e2df080327 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/Category.md @@ -0,0 +1,11 @@ + +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/ModelApiResponse.md b/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/ModelApiResponse.md new file mode 100644 index 0000000000..3eec8686cc --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/ModelApiResponse.md @@ -0,0 +1,12 @@ + +# ModelApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **Integer** | | [optional] +**type** | **String** | | [optional] +**message** | **String** | | [optional] + + + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/Order.md b/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/Order.md new file mode 100644 index 0000000000..a1089f5384 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/Order.md @@ -0,0 +1,24 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | [**DateTime**](DateTime.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +PLACED | "placed" +APPROVED | "approved" +DELIVERED | "delivered" + + + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/Pet.md b/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/Pet.md new file mode 100644 index 0000000000..5b63109ef9 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/Pet.md @@ -0,0 +1,24 @@ + +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **List<String>** | | +**tags** | [**List<Tag>**](Tag.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +AVAILABLE | "available" +PENDING | "pending" +SOLD | "sold" + + + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/PetApi.md b/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/PetApi.md new file mode 100644 index 0000000000..c81b8d014c --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/PetApi.md @@ -0,0 +1,448 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> addPet(body) + +Add a new pet to the store + + + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiClient; +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.invoker.Configuration; +//import com.baeldung.petstore.client.invoker.auth.*; +//import com.baeldung.petstore.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + apiInstance.addPet(body); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **deletePet** +> deletePet(petId, apiKey) + +Deletes a pet + + + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiClient; +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.invoker.Configuration; +//import com.baeldung.petstore.client.invoker.auth.*; +//import com.baeldung.petstore.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | Pet id to delete +String apiKey = "apiKey_example"; // String | +try { + apiInstance.deletePet(petId, apiKey); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByStatus** +> List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiClient; +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.invoker.Configuration; +//import com.baeldung.petstore.client.invoker.auth.*; +//import com.baeldung.petstore.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +List status = Arrays.asList("status_example"); // List | Status values that need to be considered for filter +try { + List result = apiInstance.findPetsByStatus(status); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByStatus"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByTags** +> List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiClient; +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.invoker.Configuration; +//import com.baeldung.petstore.client.invoker.auth.*; +//import com.baeldung.petstore.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +List tags = Arrays.asList("tags_example"); // List | Tags to filter by +try { + List result = apiInstance.findPetsByTags(tags); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByTags"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List<String>**](String.md)| Tags to filter by | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiClient; +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.invoker.Configuration; +//import com.baeldung.petstore.client.invoker.auth.*; +//import com.baeldung.petstore.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key +ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); +api_key.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key.setApiKeyPrefix("Token"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet to return +try { + Pet result = apiInstance.getPetById(petId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#getPetById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updatePet** +> updatePet(body) + +Update an existing pet + + + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiClient; +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.invoker.Configuration; +//import com.baeldung.petstore.client.invoker.auth.*; +//import com.baeldung.petstore.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + apiInstance.updatePet(body); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **updatePetWithForm** +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + + + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiClient; +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.invoker.Configuration; +//import com.baeldung.petstore.client.invoker.auth.*; +//import com.baeldung.petstore.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet that needs to be updated +String name = "name_example"; // String | Updated name of the pet +String status = "status_example"; // String | Updated status of the pet +try { + apiInstance.updatePetWithForm(petId, name, status); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | [optional] + **status** | **String**| Updated status of the pet | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: application/xml, application/json + + +# **uploadFile** +> ModelApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + + + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiClient; +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.invoker.Configuration; +//import com.baeldung.petstore.client.invoker.auth.*; +//import com.baeldung.petstore.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet to update +String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server +File file = new File("/path/to/file.txt"); // File | file to upload +try { + ModelApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFile"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to update | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + **file** | **File**| file to upload | [optional] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/StoreApi.md b/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/StoreApi.md new file mode 100644 index 0000000000..7beaa75b86 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/StoreApi.md @@ -0,0 +1,197 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Long orderId = 789L; // Long | ID of the order that needs to be deleted +try { + apiInstance.deleteOrder(orderId); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#deleteOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getInventory** +> Map<String, Integer> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiClient; +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.invoker.Configuration; +//import com.baeldung.petstore.client.invoker.auth.*; +//import com.baeldung.petstore.client.api.StoreApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key +ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); +api_key.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key.setApiKeyPrefix("Token"); + +StoreApi apiInstance = new StoreApi(); +try { + Map result = apiInstance.getInventory(); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getInventory"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Map<String, Integer>**](Map.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Long orderId = 789L; // Long | ID of pet that needs to be fetched +try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + + + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Order body = new Order(); // Order | order placed for purchasing the pet +try { + Order result = apiInstance.placeOrder(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/Tag.md b/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/Tag.md new file mode 100644 index 0000000000..de6814b55d --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/Tag.md @@ -0,0 +1,11 @@ + +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/User.md b/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/User.md new file mode 100644 index 0000000000..8b6753dd28 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/User.md @@ -0,0 +1,17 @@ + +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Integer** | User Status | [optional] + + + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/UserApi.md b/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/UserApi.md new file mode 100644 index 0000000000..bc5733b201 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/docs/UserApi.md @@ -0,0 +1,370 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> createUser(body) + +Create user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +User body = new User(); // User | Created user object +try { + apiInstance.createUser(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + apiInstance.createUsersWithArrayInput(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **createUsersWithListInput** +> createUsersWithListInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + apiInstance.createUsersWithListInput(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithListInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **deleteUser** +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be deleted +try { + apiInstance.deleteUser(username); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#deleteUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + + + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. +try { + User result = apiInstance.getUserByName(username); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#getUserByName"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **loginUser** +> String loginUser(username, password) + +Logs user into the system + + + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The user name for login +String password = "password_example"; // String | The password for login in clear text +try { + String result = apiInstance.loginUser(username, password); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#loginUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | + **password** | **String**| The password for login in clear text | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + + + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +try { + apiInstance.logoutUser(); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#logoutUser"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updateUser** +> updateUser(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import com.baeldung.petstore.client.invoker.ApiException; +//import com.baeldung.petstore.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | name that need to be updated +User body = new User(); // User | Updated user object +try { + apiInstance.updateUser(username, body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#updateUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be updated | + **body** | [**User**](User.md)| Updated user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/git_push.sh b/spring-swagger-codegen/spring-swagger-codegen-api-client/git_push.sh new file mode 100644 index 0000000000..ed374619b1 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/gradle.properties b/spring-swagger-codegen/spring-swagger-codegen-api-client/gradle.properties new file mode 100644 index 0000000000..05644f0754 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/gradle/wrapper/gradle-wrapper.jar b/spring-swagger-codegen/spring-swagger-codegen-api-client/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..2c6137b878 Binary files /dev/null and b/spring-swagger-codegen/spring-swagger-codegen-api-client/gradle/wrapper/gradle-wrapper.jar differ diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/gradle/wrapper/gradle-wrapper.properties b/spring-swagger-codegen/spring-swagger-codegen-api-client/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..b7a3647395 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/gradlew b/spring-swagger-codegen/spring-swagger-codegen-api-client/gradlew new file mode 100644 index 0000000000..9d82f78915 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/gradlew.bat b/spring-swagger-codegen/spring-swagger-codegen-api-client/gradlew.bat new file mode 100644 index 0000000000..5f192121eb --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml new file mode 100644 index 0000000000..fb25a888fd --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml @@ -0,0 +1,243 @@ + + 4.0.0 + com.baeldung + spring-swagger-codegen-api-client + jar + spring-swagger-codegen-api-client + 0.0.1-SNAPSHOT + https://github.com/swagger-api/swagger-codegen + Swagger Java + + scm:git:git@github.com:swagger-api/swagger-codegen.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + + + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + + + + Swagger + apiteam@swagger.io + Swagger + http://swagger.io + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.10 + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.1 + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + + org.springframework + spring-web + ${spring-web-version} + + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson-version} + + + joda-time + joda-time + ${jodatime-version} + + + + + junit + junit + ${junit-version} + test + + + + UTF-8 + 1.5.15 + 4.3.9.RELEASE + 2.8.9 + 2.9.9 + 1.0.0 + 4.12 + + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/settings.gradle b/spring-swagger-codegen/spring-swagger-codegen-api-client/settings.gradle new file mode 100644 index 0000000000..3687afd41a --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "spring-swagger-codegen-api-client" \ No newline at end of file diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/AndroidManifest.xml b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..cd581f9f78 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/api/PetApi.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/api/PetApi.java new file mode 100644 index 0000000000..04f37b4235 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/api/PetApi.java @@ -0,0 +1,367 @@ +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.invoker.ApiClient; + +import java.io.File; +import com.baeldung.petstore.client.model.ModelApiResponse; +import com.baeldung.petstore.client.model.Pet; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.util.UriComponentsBuilder; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; + +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-29T12:04:37.072+02:00") +@Component("com.baeldung.petstore.client.api.PetApi") +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(new ApiClient()); + } + + @Autowired + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Add a new pet to the store + * + *

405 - Invalid input + * @param body Pet object that needs to be added to the store + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void addPet(Pet body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling addPet"); + } + + String path = UriComponentsBuilder.fromPath("/pet").build().toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/xml", "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json", "application/xml" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Deletes a pet + * + *

400 - Invalid ID supplied + *

404 - Pet not found + * @param petId Pet id to delete + * @param apiKey The apiKey parameter + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deletePet(Long petId, String apiKey) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling deletePet"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + String path = UriComponentsBuilder.fromPath("/pet/{petId}").buildAndExpand(uriVariables).toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + if (apiKey != null) + headerParams.add("api_key", apiClient.parameterToString(apiKey)); + + final String[] accepts = { + "application/xml", "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + *

200 - successful operation + *

400 - Invalid status value + * @param status Status values that need to be considered for filter + * @return List<Pet> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public List findPetsByStatus(List status) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'status' when calling findPetsByStatus"); + } + + String path = UriComponentsBuilder.fromPath("/pet/findByStatus").build().toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase()), "status", status)); + + final String[] accepts = { + "application/xml", "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Finds Pets by tags + * Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + *

200 - successful operation + *

400 - Invalid tag value + * @param tags Tags to filter by + * @return List<Pet> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public List findPetsByTags(List tags) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'tags' when calling findPetsByTags"); + } + + String path = UriComponentsBuilder.fromPath("/pet/findByTags").build().toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase()), "tags", tags)); + + final String[] accepts = { + "application/xml", "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Find pet by ID + * Returns a single pet + *

200 - successful operation + *

400 - Invalid ID supplied + *

404 - Pet not found + * @param petId ID of pet to return + * @return Pet + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Pet getPetById(Long petId) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling getPetById"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + String path = UriComponentsBuilder.fromPath("/pet/{petId}").buildAndExpand(uriVariables).toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/xml", "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "api_key" }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Update an existing pet + * + *

400 - Invalid ID supplied + *

404 - Pet not found + *

405 - Validation exception + * @param body Pet object that needs to be added to the store + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void updatePet(Pet body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling updatePet"); + } + + String path = UriComponentsBuilder.fromPath("/pet").build().toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/xml", "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json", "application/xml" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Updates a pet in the store with form data + * + *

405 - Invalid input + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void updatePetWithForm(Long petId, String name, String status) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling updatePetWithForm"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + String path = UriComponentsBuilder.fromPath("/pet/{petId}").buildAndExpand(uriVariables).toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + if (name != null) + formParams.add("name", name); + if (status != null) + formParams.add("status", status); + + final String[] accepts = { + "application/xml", "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/x-www-form-urlencoded" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } + /** + * uploads an image + * + *

200 - successful operation + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @return ModelApiResponse + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling uploadFile"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + String path = UriComponentsBuilder.fromPath("/pet/{petId}/uploadImage").buildAndExpand(uriVariables).toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + if (additionalMetadata != null) + formParams.add("additionalMetadata", additionalMetadata); + if (file != null) + formParams.add("file", new FileSystemResource(file)); + + final String[] accepts = { + "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "multipart/form-data" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/api/StoreApi.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/api/StoreApi.java new file mode 100644 index 0000000000..040830f334 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/api/StoreApi.java @@ -0,0 +1,187 @@ +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.invoker.ApiClient; + +import com.baeldung.petstore.client.model.Order; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.util.UriComponentsBuilder; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; + +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-29T12:04:37.072+02:00") +@Component("com.baeldung.petstore.client.api.StoreApi") +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(new ApiClient()); + } + + @Autowired + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + *

400 - Invalid ID supplied + *

404 - Order not found + * @param orderId ID of the order that needs to be deleted + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteOrder(Long orderId) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'orderId' when calling deleteOrder"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("orderId", orderId); + String path = UriComponentsBuilder.fromPath("/store/order/{orderId}").buildAndExpand(uriVariables).toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/xml", "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + *

200 - successful operation + * @return Map<String, Integer> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Map getInventory() throws RestClientException { + Object postBody = null; + + String path = UriComponentsBuilder.fromPath("/store/inventory").build().toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "api_key" }; + + ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + *

200 - successful operation + *

400 - Invalid ID supplied + *

404 - Order not found + * @param orderId ID of pet that needs to be fetched + * @return Order + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Order getOrderById(Long orderId) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'orderId' when calling getOrderById"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("orderId", orderId); + String path = UriComponentsBuilder.fromPath("/store/order/{orderId}").buildAndExpand(uriVariables).toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/xml", "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Place an order for a pet + * + *

200 - successful operation + *

400 - Invalid Order + * @param body order placed for purchasing the pet + * @return Order + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Order placeOrder(Order body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling placeOrder"); + } + + String path = UriComponentsBuilder.fromPath("/store/order").build().toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/xml", "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/api/UserApi.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/api/UserApi.java new file mode 100644 index 0000000000..2b14bc7a4e --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/api/UserApi.java @@ -0,0 +1,337 @@ +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.invoker.ApiClient; + +import com.baeldung.petstore.client.model.User; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.util.UriComponentsBuilder; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; + +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-29T12:04:37.072+02:00") +@Component("com.baeldung.petstore.client.api.UserApi") +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(new ApiClient()); + } + + @Autowired + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create user + * This can only be done by the logged in user. + *

0 - successful operation + * @param body Created user object + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void createUser(User body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUser"); + } + + String path = UriComponentsBuilder.fromPath("/user").build().toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/xml", "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Creates list of users with given input array + * + *

0 - successful operation + * @param body List of user object + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void createUsersWithArrayInput(List body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUsersWithArrayInput"); + } + + String path = UriComponentsBuilder.fromPath("/user/createWithArray").build().toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/xml", "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Creates list of users with given input array + * + *

0 - successful operation + * @param body List of user object + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void createUsersWithListInput(List body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUsersWithListInput"); + } + + String path = UriComponentsBuilder.fromPath("/user/createWithList").build().toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/xml", "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Delete user + * This can only be done by the logged in user. + *

400 - Invalid username supplied + *

404 - User not found + * @param username The name that needs to be deleted + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteUser(String username) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling deleteUser"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("username", username); + String path = UriComponentsBuilder.fromPath("/user/{username}").buildAndExpand(uriVariables).toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/xml", "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Get user by user name + * + *

200 - successful operation + *

400 - Invalid username supplied + *

404 - User not found + * @param username The name that needs to be fetched. Use user1 for testing. + * @return User + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public User getUserByName(String username) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling getUserByName"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("username", username); + String path = UriComponentsBuilder.fromPath("/user/{username}").buildAndExpand(uriVariables).toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/xml", "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Logs user into the system + * + *

200 - successful operation + *

400 - Invalid username/password supplied + * @param username The user name for login + * @param password The password for login in clear text + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String loginUser(String username, String password) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling loginUser"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'password' when calling loginUser"); + } + + String path = UriComponentsBuilder.fromPath("/user/login").build().toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "username", username)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "password", password)); + + final String[] accepts = { + "application/xml", "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Logs out current logged in user session + * + *

0 - successful operation + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void logoutUser() throws RestClientException { + Object postBody = null; + + String path = UriComponentsBuilder.fromPath("/user/logout").build().toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/xml", "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Updated user + * This can only be done by the logged in user. + *

400 - Invalid user supplied + *

404 - User not found + * @param username name that need to be updated + * @param body Updated user object + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void updateUser(String username, User body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling updateUser"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling updateUser"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("username", username); + String path = UriComponentsBuilder.fromPath("/user/{username}").buildAndExpand(uriVariables).toUriString(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/xml", "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/ApiClient.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/ApiClient.java new file mode 100644 index 0000000000..dd47a39496 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/ApiClient.java @@ -0,0 +1,626 @@ +package com.baeldung.petstore.client.invoker; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpRequest; +import org.springframework.http.HttpStatus; +import org.springframework.http.InvalidMediaTypeException; +import org.springframework.http.MediaType; +import org.springframework.http.RequestEntity; +import org.springframework.http.RequestEntity.BodyBuilder; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.BufferingClientHttpRequestFactory; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.text.DateFormat; +import java.text.ParseException; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.TimeZone; + +import com.baeldung.petstore.client.invoker.auth.Authentication; +import com.baeldung.petstore.client.invoker.auth.HttpBasicAuth; +import com.baeldung.petstore.client.invoker.auth.ApiKeyAuth; +import com.baeldung.petstore.client.invoker.auth.OAuth; + +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-29T12:04:37.072+02:00") +@Component("com.baeldung.petstore.client.invoker.ApiClient") +public class ApiClient { + public enum CollectionFormat { + CSV(","), TSV("\t"), SSV(" "), PIPES("|"), MULTI(null); + + private final String separator; + private CollectionFormat(String separator) { + this.separator = separator; + } + + private String collectionToString(Collection collection) { + return StringUtils.collectionToDelimitedString(collection, separator); + } + } + + private boolean debugging = false; + + private HttpHeaders defaultHeaders = new HttpHeaders(); + + private String basePath = "http://petstore.swagger.io/v2"; + + private RestTemplate restTemplate; + + private Map authentications; + + private HttpStatus statusCode; + private MultiValueMap responseHeaders; + + private DateFormat dateFormat; + + public ApiClient() { + this.restTemplate = buildRestTemplate(); + init(); + } + + @Autowired + public ApiClient(RestTemplate restTemplate) { + this.restTemplate = restTemplate; + init(); + } + + protected void init() { + // Use RFC3339 format for date and datetime. + // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + this.dateFormat = new RFC3339DateFormat(); + + // Use UTC as the default time zone. + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + + // Set default User-Agent. + setUserAgent("Java-SDK"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Get the current base path + * @return String the base path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set the base path, which should include the host + * @param basePath the base path + * @return ApiClient this client + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Gets the status code of the previous request + * @return HttpStatus the status code + */ + public HttpStatus getStatusCode() { + return statusCode; + } + + /** + * Gets the response headers of the previous request + * @return MultiValueMap a map of response headers + */ + public MultiValueMap getResponseHeaders() { + return responseHeaders; + } + + /** + * Get authentications (key: authentication name, value: authentication). + * @return Map the currently configured authentication types + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * @param username the username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * @param password the password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * @param apiKey the API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * @param apiKeyPrefix the API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + * @param accessToken the access token + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * @param userAgent the user agent string + * @return ApiClient this client + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param name The header's name + * @param value The header's value + * @return ApiClient this client + */ + public ApiClient addDefaultHeader(String name, String value) { + defaultHeaders.add(name, value); + return this; + } + + public void setDebugging(boolean debugging) { + List currentInterceptors = this.restTemplate.getInterceptors(); + if(debugging) { + if (currentInterceptors == null) { + currentInterceptors = new ArrayList(); + } + ClientHttpRequestInterceptor interceptor = new ApiClientHttpRequestInterceptor(); + currentInterceptors.add(interceptor); + this.restTemplate.setInterceptors(currentInterceptors); + } else { + if (currentInterceptors != null && !currentInterceptors.isEmpty()) { + Iterator iter = currentInterceptors.iterator(); + while (iter.hasNext()) { + ClientHttpRequestInterceptor interceptor = iter.next(); + if (interceptor instanceof ApiClientHttpRequestInterceptor) { + iter.remove(); + } + } + this.restTemplate.setInterceptors(currentInterceptors); + } + } + this.debugging = debugging; + } + + /** + * Check that whether debugging is enabled for this API client. + * @return boolean true if this client is enabled for debugging, false otherwise + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Get the date format used to parse/format date parameters. + * @return DateFormat format + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Set the date format used to parse/format date parameters. + * @param dateFormat Date format + * @return API client + */ + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + return this; + } + + /** + * Parse the given string into Date object. + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given parameter object into string. + * @param param the object to convert + * @return String the parameter represented as a String + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate( (Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection) param) { + if(b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Converts a parameter to a {@link MultiValueMap} for use in REST requests + * @param collectionFormat The format to convert to + * @param name The name of the parameter + * @param value The parameter's value + * @return a Map containing the String value(s) of the input parameter + */ + public MultiValueMap parameterToMultiValueMap(CollectionFormat collectionFormat, String name, Object value) { + final MultiValueMap params = new LinkedMultiValueMap(); + + if (name == null || name.isEmpty() || value == null) { + return params; + } + + if(collectionFormat == null) { + collectionFormat = CollectionFormat.CSV; + } + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(name, parameterToString(value)); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + if (collectionFormat.equals(CollectionFormat.MULTI)) { + for (Object item : valueCollection) { + params.add(name, parameterToString(item)); + } + return params; + } + + List values = new ArrayList(); + for(Object o : valueCollection) { + values.add(parameterToString(o)); + } + params.add(name, collectionFormat.collectionToString(values)); + + return params; + } + + /** + * Check if the given {@code String} is a JSON MIME. + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents JSON, false otherwise + */ + public boolean isJsonMime(String mediaType) { + try { + return isJsonMime(MediaType.parseMediaType(mediaType)); + } catch (InvalidMediaTypeException e) { + } + return false; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents JSON, false otherwise + */ + public boolean isJsonMime(MediaType mediaType) { + return mediaType != null && (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType) || mediaType.getSubtype().matches("^.*\\+json[;]?\\s*$")); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return List The list of MediaTypes to use for the Accept header + */ + public List selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + MediaType mediaType = MediaType.parseMediaType(accept); + if (isJsonMime(mediaType)) { + return Collections.singletonList(mediaType); + } + } + return MediaType.parseMediaTypes(StringUtils.arrayToCommaDelimitedString(accepts)); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return MediaType The Content-Type header to use. If the given array is empty, JSON will be used. + */ + public MediaType selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return MediaType.APPLICATION_JSON; + } + for (String contentType : contentTypes) { + MediaType mediaType = MediaType.parseMediaType(contentType); + if (isJsonMime(mediaType)) { + return mediaType; + } + } + return MediaType.parseMediaType(contentTypes[0]); + } + + /** + * Select the body to use for the request + * @param obj the body object + * @param formParams the form parameters + * @param contentType the content type of the request + * @return Object the selected body + */ + protected Object selectBody(Object obj, MultiValueMap formParams, MediaType contentType) { + boolean isForm = MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType) || MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType); + return isForm ? formParams : obj; + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param the return type to use + * @param path The sub-path of the HTTP URL + * @param method The request method + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @return The response body in chosen type + */ + public T invokeAPI(String path, HttpMethod method, MultiValueMap queryParams, Object body, HttpHeaders headerParams, MultiValueMap formParams, List accept, MediaType contentType, String[] authNames, ParameterizedTypeReference returnType) throws RestClientException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(basePath).path(path); + if (queryParams != null) { + builder.queryParams(queryParams); + } + + final BodyBuilder requestBuilder = RequestEntity.method(method, builder.build().toUri()); + if(accept != null) { + requestBuilder.accept(accept.toArray(new MediaType[accept.size()])); + } + if(contentType != null) { + requestBuilder.contentType(contentType); + } + + addHeadersToRequest(headerParams, requestBuilder); + addHeadersToRequest(defaultHeaders, requestBuilder); + + RequestEntity requestEntity = requestBuilder.body(selectBody(body, formParams, contentType)); + + ResponseEntity responseEntity = restTemplate.exchange(requestEntity, returnType); + + statusCode = responseEntity.getStatusCode(); + responseHeaders = responseEntity.getHeaders(); + + if (responseEntity.getStatusCode() == HttpStatus.NO_CONTENT) { + return null; + } else if (responseEntity.getStatusCode().is2xxSuccessful()) { + if (returnType == null) { + return null; + } + return responseEntity.getBody(); + } else { + // The error handler built into the RestTemplate should handle 400 and 500 series errors. + throw new RestClientException("API returned " + statusCode + " and it wasn't handled by the RestTemplate error handler"); + } + } + + /** + * Add headers to the request that is being built + * @param headers The headers to add + * @param requestBuilder The current request + */ + protected void addHeadersToRequest(HttpHeaders headers, BodyBuilder requestBuilder) { + for (Entry> entry : headers.entrySet()) { + List values = entry.getValue(); + for(String value : values) { + if (value != null) { + requestBuilder.header(entry.getKey(), value); + } + } + } + } + + /** + * Build the RestTemplate used to make HTTP requests. + * @return RestTemplate + */ + protected RestTemplate buildRestTemplate() { + RestTemplate restTemplate = new RestTemplate(); + // This allows us to read the response more than once - Necessary for debugging. + restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(restTemplate.getRequestFactory())); + return restTemplate; + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams The query parameters + * @param headerParams The header parameters + */ + private void updateParamsForAuth(String[] authNames, MultiValueMap queryParams, HttpHeaders headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) { + throw new RestClientException("Authentication undefined: " + authName); + } + auth.applyToParams(queryParams, headerParams); + } + } + + private class ApiClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { + private final Log log = LogFactory.getLog(ApiClientHttpRequestInterceptor.class); + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + logRequest(request, body); + ClientHttpResponse response = execution.execute(request, body); + logResponse(response); + return response; + } + + private void logRequest(HttpRequest request, byte[] body) throws UnsupportedEncodingException { + log.info("URI: " + request.getURI()); + log.info("HTTP Method: " + request.getMethod()); + log.info("HTTP Headers: " + headersToString(request.getHeaders())); + log.info("Request Body: " + new String(body, StandardCharsets.UTF_8)); + } + + private void logResponse(ClientHttpResponse response) throws IOException { + log.info("HTTP Status Code: " + response.getRawStatusCode()); + log.info("Status Text: " + response.getStatusText()); + log.info("HTTP Headers: " + headersToString(response.getHeaders())); + log.info("Response Body: " + bodyToString(response.getBody())); + } + + private String headersToString(HttpHeaders headers) { + StringBuilder builder = new StringBuilder(); + for(Entry> entry : headers.entrySet()) { + builder.append(entry.getKey()).append("=["); + for(String value : entry.getValue()) { + builder.append(value).append(","); + } + builder.setLength(builder.length() - 1); // Get rid of trailing comma + builder.append("],"); + } + builder.setLength(builder.length() - 1); // Get rid of trailing comma + return builder.toString(); + } + + private String bodyToString(InputStream body) throws IOException { + StringBuilder builder = new StringBuilder(); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8)); + String line = bufferedReader.readLine(); + while (line != null) { + builder.append(line).append(System.lineSeparator()); + line = bufferedReader.readLine(); + } + bufferedReader.close(); + return builder.toString(); + } + } +} \ No newline at end of file diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/RFC3339DateFormat.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/RFC3339DateFormat.java new file mode 100644 index 0000000000..b33d21a899 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/RFC3339DateFormat.java @@ -0,0 +1,32 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +package com.baeldung.petstore.client.invoker; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/ApiKeyAuth.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/ApiKeyAuth.java new file mode 100644 index 0000000000..35cb5e28d3 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/ApiKeyAuth.java @@ -0,0 +1,60 @@ +package com.baeldung.petstore.client.invoker.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-29T12:04:37.072+02:00") +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams) { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if (location.equals("query")) { + queryParams.add(paramName, value); + } else if (location.equals("header")) { + headerParams.add(paramName, value); + } + } +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/Authentication.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/Authentication.java new file mode 100644 index 0000000000..59188957a5 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/Authentication.java @@ -0,0 +1,13 @@ +package com.baeldung.petstore.client.invoker.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +public interface Authentication { + /** + * Apply authentication settings to header and / or query parameters. + * @param queryParams The query parameters for the request + * @param headerParams The header parameters for the request + */ + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams); +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBasicAuth.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBasicAuth.java new file mode 100644 index 0000000000..16c88a4bc6 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBasicAuth.java @@ -0,0 +1,39 @@ +package com.baeldung.petstore.client.invoker.auth; + +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.Base64Utils; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-29T12:04:37.072+02:00") +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams) { + if (username == null && password == null) { + return; + } + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + headerParams.add(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString(str.getBytes(StandardCharsets.UTF_8))); + } +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuth.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuth.java new file mode 100644 index 0000000000..d458b33ae6 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuth.java @@ -0,0 +1,24 @@ +package com.baeldung.petstore.client.invoker.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-29T12:04:37.072+02:00") +public class OAuth implements Authentication { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams) { + if (accessToken != null) { + headerParams.add(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken); + } + } +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuthFlow.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuthFlow.java new file mode 100644 index 0000000000..235e0b7f55 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuthFlow.java @@ -0,0 +1,5 @@ +package com.baeldung.petstore.client.invoker.auth; + +public enum OAuthFlow { + accessCode, implicit, password, application +} \ No newline at end of file diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/model/Category.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/model/Category.java new file mode 100644 index 0000000000..8f93b599c9 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/model/Category.java @@ -0,0 +1,113 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Category + */ +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-29T12:04:37.072+02:00") +public class Category { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Category name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/model/ModelApiResponse.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/model/ModelApiResponse.java new file mode 100644 index 0000000000..f968b3bbac --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/model/ModelApiResponse.java @@ -0,0 +1,136 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * ModelApiResponse + */ +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-29T12:04:37.072+02:00") +public class ModelApiResponse { + @JsonProperty("code") + private Integer code = null; + + @JsonProperty("type") + private String type = null; + + @JsonProperty("message") + private String message = null; + + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + **/ + @ApiModelProperty(value = "") + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + **/ + @ApiModelProperty(value = "") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + **/ + @ApiModelProperty(value = "") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/model/Order.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/model/Order.java new file mode 100644 index 0000000000..a585f42910 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/model/Order.java @@ -0,0 +1,243 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.joda.time.DateTime; + +/** + * Order + */ +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-29T12:04:37.072+02:00") +public class Order { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("petId") + private Long petId = null; + + @JsonProperty("quantity") + private Integer quantity = null; + + @JsonProperty("shipDate") + private DateTime shipDate = null; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + @JsonProperty("complete") + private Boolean complete = false; + + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + **/ + @ApiModelProperty(value = "") + public Long getPetId() { + return petId; + } + + public void setPetId(Long petId) { + this.petId = petId; + } + + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + @ApiModelProperty(value = "") + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + public Order shipDate(DateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @ApiModelProperty(value = "") + public DateTime getShipDate() { + return shipDate; + } + + public void setShipDate(DateTime shipDate) { + this.shipDate = shipDate; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Order Status + * @return status + **/ + @ApiModelProperty(value = "Order Status") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + **/ + @ApiModelProperty(value = "") + public Boolean getComplete() { + return complete; + } + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/model/Pet.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/model/Pet.java new file mode 100644 index 0000000000..34905d8611 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/model/Pet.java @@ -0,0 +1,259 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import java.util.Objects; +import com.baeldung.petstore.client.model.Category; +import com.baeldung.petstore.client.model.Tag; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; + +/** + * Pet + */ +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-29T12:04:37.072+02:00") +public class Pet { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("category") + private Category category = null; + + @JsonProperty("name") + private String name = null; + + @JsonProperty("photoUrls") + private List photoUrls = new ArrayList(); + + @JsonProperty("tags") + private List tags = null; + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + **/ + @ApiModelProperty(value = "") + public Category getCategory() { + return category; + } + + public void setCategory(Category category) { + this.category = category; + } + + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "doggie", required = true, value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @ApiModelProperty(required = true, value = "") + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/model/Tag.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/model/Tag.java new file mode 100644 index 0000000000..42fc205b28 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/model/Tag.java @@ -0,0 +1,113 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Tag + */ +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-29T12:04:37.072+02:00") +public class Tag { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Tag name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/model/User.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/model/User.java new file mode 100644 index 0000000000..41049e8638 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/model/User.java @@ -0,0 +1,251 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * User + */ +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-29T12:04:37.072+02:00") +public class User { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("username") + private String username = null; + + @JsonProperty("firstName") + private String firstName = null; + + @JsonProperty("lastName") + private String lastName = null; + + @JsonProperty("email") + private String email = null; + + @JsonProperty("password") + private String password = null; + + @JsonProperty("phone") + private String phone = null; + + @JsonProperty("userStatus") + private Integer userStatus = null; + + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get username + * @return username + **/ + @ApiModelProperty(value = "") + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + @ApiModelProperty(value = "") + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + @ApiModelProperty(value = "") + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get email + * @return email + **/ + @ApiModelProperty(value = "") + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(value = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + **/ + @ApiModelProperty(value = "") + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + /** + * User Status + * @return userStatus + **/ + @ApiModelProperty(value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java new file mode 100644 index 0000000000..0b94027df0 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java @@ -0,0 +1,169 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.api; + +import java.io.File; +import com.baeldung.petstore.client.model.ModelApiResponse; +import com.baeldung.petstore.client.model.Pet; +import org.junit.Test; +import org.junit.Ignore; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for PetApi + */ +@Ignore +public class PetApiTest { + + private final PetApi api = new PetApi(); + + + /** + * Add a new pet to the store + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void addPetTest() { + Pet body = null; + api.addPet(body); + + // TODO: test validations + } + + /** + * Deletes a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deletePetTest() { + Long petId = null; + String apiKey = null; + api.deletePet(petId, apiKey); + + // TODO: test validations + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByStatusTest() { + List status = null; + List response = api.findPetsByStatus(status); + + // TODO: test validations + } + + /** + * Finds Pets by tags + * + * Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByTagsTest() { + List tags = null; + List response = api.findPetsByTags(tags); + + // TODO: test validations + } + + /** + * Find pet by ID + * + * Returns a single pet + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getPetByIdTest() { + Long petId = null; + Pet response = api.getPetById(petId); + + // TODO: test validations + } + + /** + * Update an existing pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetTest() { + Pet body = null; + api.updatePet(body); + + // TODO: test validations + } + + /** + * Updates a pet in the store with form data + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetWithFormTest() { + Long petId = null; + String name = null; + String status = null; + api.updatePetWithForm(petId, name, status); + + // TODO: test validations + } + + /** + * uploads an image + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void uploadFileTest() { + Long petId = null; + String additionalMetadata = null; + File file = null; + ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + + // TODO: test validations + } + +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java new file mode 100644 index 0000000000..ce332bee0d --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java @@ -0,0 +1,97 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.model.Order; +import org.junit.Test; +import org.junit.Ignore; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for StoreApi + */ +@Ignore +public class StoreApiTest { + + private final StoreApi api = new StoreApi(); + + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteOrderTest() { + Long orderId = null; + api.deleteOrder(orderId); + + // TODO: test validations + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getInventoryTest() { + Map response = api.getInventory(); + + // TODO: test validations + } + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getOrderByIdTest() { + Long orderId = null; + Order response = api.getOrderById(orderId); + + // TODO: test validations + } + + /** + * Place an order for a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void placeOrderTest() { + Order body = null; + Order response = api.placeOrder(body); + + // TODO: test validations + } + +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiTest.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiTest.java new file mode 100644 index 0000000000..59e7a39679 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiTest.java @@ -0,0 +1,163 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.model.User; +import org.junit.Test; +import org.junit.Ignore; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for UserApi + */ +@Ignore +public class UserApiTest { + + private final UserApi api = new UserApi(); + + + /** + * Create user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUserTest() { + User body = null; + api.createUser(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithArrayInputTest() { + List body = null; + api.createUsersWithArrayInput(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithListInputTest() { + List body = null; + api.createUsersWithListInput(body); + + // TODO: test validations + } + + /** + * Delete user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteUserTest() { + String username = null; + api.deleteUser(username); + + // TODO: test validations + } + + /** + * Get user by user name + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getUserByNameTest() { + String username = null; + User response = api.getUserByName(username); + + // TODO: test validations + } + + /** + * Logs user into the system + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void loginUserTest() { + String username = null; + String password = null; + String response = api.loginUser(username, password); + + // TODO: test validations + } + + /** + * Logs out current logged in user session + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void logoutUserTest() { + api.logoutUser(); + + // TODO: test validations + } + + /** + * Updated user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updateUserTest() { + String username = null; + User body = null; + api.updateUser(username, body); + + // TODO: test validations + } + +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml new file mode 100644 index 0000000000..f42fc5c2e2 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml @@ -0,0 +1,41 @@ + + 4.0.0 + + com.baeldung + spring-swagger-codegen-app + 0.0.1-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.5.6.RELEASE + + + + + com.baeldung + spring-swagger-codegen-api-client + 0.0.1-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-web + + + + + 1.8 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/src/main/java/com/baeldung/petstore/app/DefaultPetService.java b/spring-swagger-codegen/spring-swagger-codegen-app/src/main/java/com/baeldung/petstore/app/DefaultPetService.java new file mode 100644 index 0000000000..72c011d6f5 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-app/src/main/java/com/baeldung/petstore/app/DefaultPetService.java @@ -0,0 +1,30 @@ +package com.baeldung.petstore.app; + +import java.util.Arrays; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.baeldung.petstore.client.api.PetApi; +import com.baeldung.petstore.client.model.Pet; + +@Service +public class DefaultPetService implements PetService { + + @Autowired + private PetApi petApi; + + public List findAvailablePets() { + return petApi.findPetsByStatus(Arrays.asList("available")); + } + + public List findPendingPets() { + return petApi.findPetsByStatus(Arrays.asList("pending")); + } + + public List findSoldPets() { + return petApi.findPetsByStatus(Arrays.asList("sold")); + } + +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/src/main/java/com/baeldung/petstore/app/PetController.java b/spring-swagger-codegen/spring-swagger-codegen-app/src/main/java/com/baeldung/petstore/app/PetController.java new file mode 100644 index 0000000000..d5105e2f78 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-app/src/main/java/com/baeldung/petstore/app/PetController.java @@ -0,0 +1,26 @@ +package com.baeldung.petstore.app; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +public class PetController { + + @Autowired + private PetService petService; + + + @RequestMapping("/pets") + @ResponseBody + public String listAvailablePets() { + StringBuilder sb = new StringBuilder("

Available pets:

"); + sb.append("
    "); + petService.findAvailablePets() + .forEach( p -> sb.append("
  • " + p.getName() + "
  • ")); + sb.append("
"); + return sb.toString(); + } + +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/src/main/java/com/baeldung/petstore/app/PetService.java b/spring-swagger-codegen/spring-swagger-codegen-app/src/main/java/com/baeldung/petstore/app/PetService.java new file mode 100644 index 0000000000..257183d81f --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-app/src/main/java/com/baeldung/petstore/app/PetService.java @@ -0,0 +1,27 @@ +package com.baeldung.petstore.app; + +import java.util.List; + +import com.baeldung.petstore.client.model.Pet; + +public interface PetService { + + /** + * Find available pets + * @return List of available pets + */ + List findAvailablePets(); + + /** + * Find Pending pets + * @return List of pending pets + */ + List findPendingPets(); + + /** + * Find sold pets + * @return List of sold pets + */ + List findSoldPets(); + +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/src/main/java/com/baeldung/petstore/app/PetStoreApplication.java b/spring-swagger-codegen/spring-swagger-codegen-app/src/main/java/com/baeldung/petstore/app/PetStoreApplication.java new file mode 100644 index 0000000000..d8abeaddaa --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-app/src/main/java/com/baeldung/petstore/app/PetStoreApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.petstore.app; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Import; + +@SpringBootApplication +@Import(PetStoreIntegrationConfig.class) +public class PetStoreApplication { + + public static void main(String[] args) throws Exception { + SpringApplication.run(PetStoreApplication.class, args); + } + +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/src/main/java/com/baeldung/petstore/app/PetStoreIntegrationConfig.java b/spring-swagger-codegen/spring-swagger-codegen-app/src/main/java/com/baeldung/petstore/app/PetStoreIntegrationConfig.java new file mode 100644 index 0000000000..a70be4120f --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-app/src/main/java/com/baeldung/petstore/app/PetStoreIntegrationConfig.java @@ -0,0 +1,23 @@ +package com.baeldung.petstore.app; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.petstore.client.api.PetApi; +import com.baeldung.petstore.client.invoker.ApiClient; + +@Configuration +public class PetStoreIntegrationConfig { + + @Bean + public PetApi petpi() { + return new PetApi(apiClient()); + } + + @Bean + public ApiClient apiClient() { + ApiClient apiClient = new ApiClient(); + return apiClient; + } + +} diff --git a/testing/README.md b/testing/README.md index a691737e4f..3171b67b60 100644 --- a/testing/README.md +++ b/testing/README.md @@ -13,3 +13,5 @@ - [Testing with JGoTesting](http://www.baeldung.com/jgotesting) - [Introduction to JUnitParams](http://www.baeldung.com/junit-params) - [Cucumber Java 8 Support](http://www.baeldung.com/cucumber-java-8-support) +- [Introduction to Lambda Behave](http://www.baeldung.com/lambda-behave) + diff --git a/testing/pom.xml b/testing/pom.xml index 72ec2b2f0c..8f5c6ddb3d 100644 --- a/testing/pom.xml +++ b/testing/pom.xml @@ -86,6 +86,12 @@ jgotesting ${jgotesting.version} test + + + org.jukito + jukito + 1.5 + test diff --git a/testing/src/main/java/com/baeldung/introductionjukito/Calculator.java b/testing/src/main/java/com/baeldung/introductionjukito/Calculator.java new file mode 100644 index 0000000000..fd75e1bd9e --- /dev/null +++ b/testing/src/main/java/com/baeldung/introductionjukito/Calculator.java @@ -0,0 +1,7 @@ +package com.baeldung.introductionjukito; + +public interface Calculator { + + public double add(double a, double b); + +} diff --git a/testing/src/main/java/com/baeldung/introductionjukito/ScientificCalculator.java b/testing/src/main/java/com/baeldung/introductionjukito/ScientificCalculator.java new file mode 100644 index 0000000000..2501569afc --- /dev/null +++ b/testing/src/main/java/com/baeldung/introductionjukito/ScientificCalculator.java @@ -0,0 +1,5 @@ +package com.baeldung.introductionjukito; + +public class ScientificCalculator extends SimpleCalculator { + +} diff --git a/testing/src/main/java/com/baeldung/introductionjukito/SimpleCalculator.java b/testing/src/main/java/com/baeldung/introductionjukito/SimpleCalculator.java new file mode 100644 index 0000000000..933baa3cd0 --- /dev/null +++ b/testing/src/main/java/com/baeldung/introductionjukito/SimpleCalculator.java @@ -0,0 +1,10 @@ +package com.baeldung.introductionjukito; + +public class SimpleCalculator implements Calculator { + + @Override + public double add(double a, double b) { + return a+b; + } + +} diff --git a/testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java b/testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java new file mode 100644 index 0000000000..313e1d2938 --- /dev/null +++ b/testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java @@ -0,0 +1,62 @@ +package com.baeldung.introductionjukito; + +import org.jukito.All; +import org.jukito.JukitoModule; +import org.jukito.JukitoRunner; +import org.junit.Test; +import org.junit.runner.RunWith; +import static org.junit.Assert.*; + +@RunWith(JukitoRunner.class) +public class CalculatorTest { + + public static class Module extends JukitoModule { + + @Override + protected void configureTest() { + bindMany(Calculator.class, SimpleCalculator.class, + ScientificCalculator.class); + bindManyInstances(AdditionTest.class, new AdditionTest(1, 1, 2), + new AdditionTest(10, 10, 20), + new AdditionTest(18, 24, 42)); + bindManyNamedInstances(Integer.class, "even", 2, 4, 6); + bindManyNamedInstances(Integer.class, "odd", 1, 3, 5); + } + } + + public static class AdditionTest { + + int a; + int b; + int expected; + + public AdditionTest(int a, int b, int expected) { + this.a = a; + this.b = b; + this.expected = expected; + } + } + + @Test + public void givenTwoNumbers_WhenAdd_ThenSumBoth(@All Calculator calc) { + double result = calc.add(1, 1); + assertEquals(2, result, .1); + } + + @Test + public void givenTwoNumbers_WhenAdd_ThenSumBoth(@All Calculator calc, + @All AdditionTest addTest) { + double result = calc.add(addTest.a, addTest.b); + assertEquals(addTest.expected, result, .1); + } + + @Test + public void givenEvenNumbers_whenPrint_thenOutput(@All("even") Integer i) { + System.out.println("even " + i); + } + + @Test + public void givenOddNumbers_whenPrint_thenOutput(@All("odd") Integer i) { + System.out.println("odd " + i); + } +} diff --git a/undertow/README.md b/undertow/README.md new file mode 100644 index 0000000000..8bfb4832e2 --- /dev/null +++ b/undertow/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to JBoss Undertow](http://www.baeldung.com/jboss-undertow) diff --git a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java index cfc789a837..b4e7628e84 100644 --- a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java @@ -2,8 +2,9 @@ package com.baeldung.vavr.collections; import io.vavr.Tuple; import io.vavr.Tuple2; -import io.vavr.collection.Array; -import io.vavr.collection.CharSeq; +import io.vavr.collection.*; +import io.vavr.collection.BitSet; +import io.vavr.collection.HashMap; import io.vavr.collection.HashSet; import io.vavr.collection.Iterator; import io.vavr.collection.List; @@ -12,13 +13,12 @@ import io.vavr.collection.Queue; import io.vavr.collection.Set; import io.vavr.collection.SortedMap; import io.vavr.collection.SortedSet; -import io.vavr.collection.Stream; import io.vavr.collection.TreeMap; import io.vavr.collection.TreeSet; import io.vavr.collection.Vector; import org.junit.Test; -import java.util.Comparator; +import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -124,6 +124,9 @@ public class CollectionAPIUnitTest { Queue tailQueue = result._2; assertFalse(tailQueue.contains(secondQueue.get(0))); + + Queue> queue1 = queue.combinations(2); + assertEquals(queue1.get(2).toCharSeq(), CharSeq.of("23")); } @Test @@ -153,17 +156,23 @@ public class CollectionAPIUnitTest { @Test public void givenArray_whenQueried_thenCorrect() { + + Array rArray = Array.range(1, 5); + assertFalse(rArray.contains(5)); + + Array rArray2 = Array.rangeClosed(1, 5); + assertTrue(rArray2.contains(5)); + + Array rArray3 = Array.rangeClosedBy(1,6,2); + assertEquals(rArray3.size(), 3); + Array intArray = Array.of(1, 2, 3); Array newArray = intArray.removeAt(1); - - assertEquals(3, intArray.size()); assertEquals(2, newArray.size()); assertEquals(3, newArray.get(1).intValue()); Array array2 = intArray.replace(1, 5); assertEquals(array2.get(0).intValue(), 5); - - } @Test @@ -199,6 +208,15 @@ public class CollectionAPIUnitTest { assertEquals(3, set.size()); assertEquals(4, newSet.size()); assertTrue(newSet.contains("Yellow")); + + HashSet set0 = HashSet.rangeClosed(1,5); + HashSet set1 = HashSet.rangeClosed(3, 6); + + assertEquals(set0.union(set1), HashSet.rangeClosed(1,6)); + assertEquals(set0.diff(set1), HashSet.rangeClosed(1,2)); + assertEquals(set0.intersect(set1), HashSet.rangeClosed(3,5)); + + } @Test @@ -222,13 +240,39 @@ public class CollectionAPIUnitTest { } @Test - public void givenMap_whenIterated_thenCorrect() { + public void giveBitSet_whenApiMethods_thenCorrect() { + + BitSet bitSet = BitSet.of(1,2,3,4,5,6,7,8); + + BitSet bitSet1 = bitSet.takeUntil(i -> i > 4); + assertEquals(bitSet1.size(), 4); + + } + + @Test + public void givenMap_whenMapApi_thenCorrect() { Map> map = List.rangeClosed(0, 10) .groupBy(i -> i % 2); assertEquals(2, map.size()); assertEquals(6, map.get(0).get().size()); assertEquals(5, map.get(1).get().size()); + + Map map1 + = HashMap.of("key1", "val1", "key2", "val2", "key3", "val3"); + + Map fMap + = map1.filterKeys(k -> k.contains("1") || k.contains("2")); + assertFalse(fMap.containsKey("key3")); + + Map fMap2 + = map1.filterValues(v -> v.contains("3")); + assertEquals(fMap2.size(), 1); + assertTrue(fMap2.containsValue("val3")); + + Map map2 = map1.map( + (k, v) -> Tuple.of(k, Integer.valueOf(v.charAt(v.length() - 1) + "") )); + assertEquals(map2.get("key1").get().intValue(), 1); } @Test @@ -238,6 +282,11 @@ public class CollectionAPIUnitTest { assertEquals(1, map.keySet().toJavaArray()[0]); assertEquals("Four", map.get(4).get()); + + TreeMap treeMap2 = + TreeMap.of(Comparator.reverseOrder(), 3,"three", 6, "six", 1, "one"); + assertEquals(treeMap2.keySet().mkString(), "631"); + } @Test diff --git a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionFactoryMethodsUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionFactoryMethodsUnitTest.java new file mode 100644 index 0000000000..60359d6803 --- /dev/null +++ b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionFactoryMethodsUnitTest.java @@ -0,0 +1,107 @@ +package com.baeldung.vavr.collections; + +import static io.vavr.API.Array; +import static io.vavr.API.Failure; +import static io.vavr.API.List; +import static io.vavr.API.None; +import static io.vavr.API.Some; +import static io.vavr.API.Stream; +import static io.vavr.API.Success; +import static io.vavr.API.Tuple; +import static io.vavr.API.Vector; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import io.vavr.Tuple3; +import io.vavr.collection.Array; +import io.vavr.collection.List; +import io.vavr.collection.Stream; +import io.vavr.collection.Vector; +import io.vavr.control.Option; +import io.vavr.control.Try; + +public class CollectionFactoryMethodsUnitTest { + + @Test + public void givenANoneOptionElement_whenCreated_thenCorrect() { + Option none = None(); + assertFalse(none == null); + assertEquals(none, Option.none()); + } + + @Test + public void givenASomeOptionElement_whenCreated_thenCorrect() { + Option some = Some(1); + assertFalse(some == null); + assertTrue(some.contains(1)); + } + + @Test + public void givenATupleElement_whenCreated_thenCorrect() { + Tuple3 tuple = Tuple('a', "chain", 2); + assertTrue(tuple!=null); + assertEquals(tuple._1(), new Character('a')); + assertEquals(tuple._2(), "chain"); + assertEquals(tuple._3().intValue(), 2); + } + + @Test + public void givenASuccessObject_whenEvaluated_thenSuccess() { + Try integer = Success(55); + assertEquals(integer.get().intValue(), 55); + } + @Test + public void givenAFailureObject_whenEvaluated_thenExceptionThrown() { + Try failure = Failure(new Exception("Exception X encapsulated here")); + + try { + Integer i = failure.get();// evaluate a failure raise the exception + System.out.println(i);// not executed + } catch (Exception e) { + assertEquals(e.getMessage(), "Exception X encapsulated here"); + } + } + + @Test + public void givenAList_whenCreated_thenCorrect() { + List list = List(1, 2, 3, 4, 5); + + assertEquals(list.size(), 5); + assertEquals(list.get(0).intValue(), 1); + } + + @Test + public void givenAnEmptyList_whenCreated_thenCorrect() { + List empty = List(); + + assertEquals(empty.size(), 0); + assertEquals(empty, List.empty()); + } + + @Test + public void givenAnArray_whenCreated_thenCorrect() { + Array array = Array(1, 2, 3, 4, 5); + + assertEquals(array.size(), 5); + assertEquals(array.get(0).intValue(), 1); + } + + @Test + public void givenAStream_whenCreated_thenCorrect() { + Stream stream = Stream(1, 2, 3, 4, 5); + + assertEquals(stream.size(), 5); + assertEquals(stream.get(0).intValue(), 1); + } + + @Test + public void givenAVector_whenCreated_thenCorrect() { + Vector vector = Vector(1, 2, 3, 4, 5); + + assertEquals(vector.size(), 5); + assertEquals(vector.get(0).intValue(), 1); + } +} diff --git a/vavr/vavr-validation/src/main/java/com/baeldung/vavrvalidation/application/Application.java b/vavr/vavr-validation/src/main/java/com/baeldung/vavrvalidation/application/Application.java new file mode 100644 index 0000000000..8acc4522af --- /dev/null +++ b/vavr/vavr-validation/src/main/java/com/baeldung/vavrvalidation/application/Application.java @@ -0,0 +1,17 @@ +package com.baeldung.vavrvalidation.application; + +import com.baeldung.vavrvalidation.model.User; +import com.baeldung.vavrvalidation.validator.UserValidator; +import io.vavr.collection.Seq; +import io.vavr.control.Validation; + +public class Application { + + public static void main(String[] args) { + + UserValidator userValidator = new UserValidator(); + Validation, User> validation = userValidator.validateUser("John", "john@domain.com"); + + // process validation results here + } +} diff --git a/vavr/vavr-validation/src/main/java/com/baeldung/vavrvalidation/model/User.java b/vavr/vavr-validation/src/main/java/com/baeldung/vavrvalidation/model/User.java new file mode 100644 index 0000000000..f1477a1ed3 --- /dev/null +++ b/vavr/vavr-validation/src/main/java/com/baeldung/vavrvalidation/model/User.java @@ -0,0 +1,18 @@ +package com.baeldung.vavrvalidation.model; + +public class User { + private String name; + private String email; + + public User(String name, String email) { + this.name = name; + this.email = email; + } + + @Override + public String toString() { + return "User [name=" + name + ", email=" + email + "]"; + } + + // standard setters and getters +} diff --git a/vavr/vavr-validation/src/main/java/com/baeldung/vavrvalidation/validator/UserValidator.java b/vavr/vavr-validation/src/main/java/com/baeldung/vavrvalidation/validator/UserValidator.java new file mode 100644 index 0000000000..1cec006816 --- /dev/null +++ b/vavr/vavr-validation/src/main/java/com/baeldung/vavrvalidation/validator/UserValidator.java @@ -0,0 +1,29 @@ +package com.baeldung.vavrvalidation.validator; + +import com.baeldung.vavrvalidation.model.User; +import io.vavr.collection.CharSeq; +import io.vavr.collection.Seq; +import io.vavr.control.Validation; + +public class UserValidator { + + private static final String NAME_PATTERN = "^[a-zA-Z0-9]+$"; + private static final String NAME_ERROR = "Name contains invalid characters"; + private static final String EMAIL_PATTERN = + "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; + private static final String EMAIL_ERROR = "Email must be a well-formed email address"; + + public Validation, User> validateUser(String name, String email) { + return Validation + .combine(validateField(name, NAME_PATTERN, NAME_ERROR) + ,validateField(email, EMAIL_PATTERN, EMAIL_ERROR)) + .ap(User::new); + } + + private Validation validateField(String field, String pattern, String error) { + return CharSeq.of(field).replaceAll(pattern, "").transform(seq -> seq.isEmpty() + ? Validation.valid(field) + : Validation.invalid(error)); + } +} diff --git a/vavr/vavr-validation/src/test/java/com/baeldung/vavrvalidation/validator/UserValidatorTest.java b/vavr/vavr-validation/src/test/java/com/baeldung/vavrvalidation/validator/UserValidatorTest.java new file mode 100644 index 0000000000..cb9557fa53 --- /dev/null +++ b/vavr/vavr-validation/src/test/java/com/baeldung/vavrvalidation/validator/UserValidatorTest.java @@ -0,0 +1,23 @@ +package com.baeldung.vavrvalidation.validator; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.instanceOf; +import org.junit.Test; +import com.baeldung.vavrvalidation.validator.UserValidator; +import io.vavr.control.Validation.Invalid; +import io.vavr.control.Validation.Valid; + +public class UserValidatorTest { + + @Test + public void givenValidUserParams_whenValidated_thenInstanceOfValid() { + UserValidator userValidator = new UserValidator(); + assertThat(userValidator.validateUser("John", "john@domain.com"), instanceOf(Valid.class)); + } + + @Test + public void givenInvalidUserParams_whenValidated_thenInstanceOfInvalid() { + UserValidator userValidator = new UserValidator(); + assertThat(userValidator.validateUser("John", "no-email"), instanceOf(Invalid.class)); + } +} diff --git a/vavr/vavr-validation/src/test/java/com/baeldung/vavrvalidation/validator/ValidationTest.java b/vavr/vavr-validation/src/test/java/com/baeldung/vavrvalidation/validator/ValidationTest.java new file mode 100644 index 0000000000..c89b43b5e3 --- /dev/null +++ b/vavr/vavr-validation/src/test/java/com/baeldung/vavrvalidation/validator/ValidationTest.java @@ -0,0 +1,68 @@ +package com.baeldung.vavrvalidation.validator; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import com.baeldung.vavrvalidation.model.User; +import io.vavr.collection.Seq; +import io.vavr.control.Either.Right; +import io.vavr.control.Validation.Invalid; +import io.vavr.control.Validation.Valid; + +public class ValidationTest { + + private static UserValidator userValidator; + + @BeforeClass + public static void setUpUserValidatorInstance() { + userValidator = new UserValidator(); + } + + @AfterClass + public static void teardownUserValidatorInstance() { + userValidator = null; + } + + @Test + public void givenInvalidUserParams_whenValidated_thenInvalidInstance() { + assertThat(userValidator.validateUser("John", "no-email"), instanceOf(Invalid.class)); + } + + @Test + public void givenValidUserParams_whenValidated_thenValidInstance() { + assertThat(userValidator.validateUser("John", "john@domain.com"), instanceOf(Valid.class)); + } + + @Test + public void givenInvalidUserParams_whenValidated_thenTrueWithIsInvalidMethod() { + assertTrue(userValidator.validateUser("John", "no-email").isInvalid()); + } + + @Test + public void givenValidUserParams_whenValidated_thenTrueWithIsValidMethod() { + assertTrue(userValidator.validateUser("John", "john@domain.com").isValid()); + } + + @Test + public void givenInValidUserParams_withGetErrorMethod_thenGetErrorMessages() { + assertEquals("Name contains invalid characters, Email must be a well-formed email address", userValidator.validateUser(" ", "no-email") + .getError().intersperse(", ").fold("", String::concat)); + } + + @Test + public void givenValidUserParams_withGetMethod_thenGetUserInstance() { + assertThat(userValidator.validateUser("John", "john@domain.com").get(), instanceOf(User.class)); + } + + @Test + public void givenValidUserParams_withtoEitherMethod_thenRightInstance() { + assertThat(userValidator.validateUser("John", "john@domain.com").toEither(), instanceOf(Right.class)); + } + + @Test + public void givenValidUserParams_withFoldMethodWithListlengthUserHashCode_thenEqualstoParamsLength() { + assertEquals(2, (int) userValidator.validateUser(" ", " ").fold(Seq::length, User::hashCode)); + } +} diff --git a/vertx-and-rxjava/pom.xml b/vertx-and-rxjava/pom.xml new file mode 100644 index 0000000000..9c2c9bfd48 --- /dev/null +++ b/vertx-and-rxjava/pom.xml @@ -0,0 +1,70 @@ + + + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + 4.0.0 + vertx-and-rxjava + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + + + io.vertx + vertx-rx-java2 + 3.5.0.Beta1 + + + io.vertx + vertx-core + 3.5.0.Beta1 + + + io.vertx + vertx-unit + 3.5.0.Beta1 + test + + + junit + junit + 4.12 + test + + + org.slf4j + slf4j-api + 1.7.25 + + + ch.qos.logback + logback-classic + 1.2.3 + + + junit + junit + 4.12 + + + + + \ No newline at end of file diff --git a/vertx-and-rxjava/pom.xml.orig b/vertx-and-rxjava/pom.xml.orig new file mode 100644 index 0000000000..47510e60f7 --- /dev/null +++ b/vertx-and-rxjava/pom.xml.orig @@ -0,0 +1,71 @@ + + + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + 4.0.0 + com.baeldung + vertx-and-rxjava + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + + + io.vertx + vertx-rx-java2 + 3.5.0.Beta1 + + + io.vertx + vertx-core + 3.5.0.Beta1 + + + io.vertx + vertx-unit + 3.5.0.Beta1 + test + + + junit + junit + 4.12 + test + + + org.slf4j + slf4j-api + 1.7.25 + + + ch.qos.logback + logback-classic + 1.2.3 + + + junit + junit + 4.12 + + + + + \ No newline at end of file diff --git a/vertx-and-rxjava/src/test/java/com/baeldung/weather/CityAndDayLength.java b/vertx-and-rxjava/src/test/java/com/baeldung/weather/CityAndDayLength.java new file mode 100644 index 0000000000..f725c8255e --- /dev/null +++ b/vertx-and-rxjava/src/test/java/com/baeldung/weather/CityAndDayLength.java @@ -0,0 +1,19 @@ +package com.baeldung.weather; + +import java.text.MessageFormat; + +class CityAndDayLength { + + private final String city; + private final double dayLengthInHours; + + CityAndDayLength(String city, long dayLengthInSeconds) { + this.city = city; + this.dayLengthInHours = dayLengthInSeconds / (60.0 * 60.0); + } + + @Override + public String toString() { + return MessageFormat.format("In {0} there are {1,number,#0.0} hours of light.", city, dayLengthInHours); + } +} diff --git a/vertx-and-rxjava/src/test/java/com/baeldung/weather/MetaWeatherClient.java b/vertx-and-rxjava/src/test/java/com/baeldung/weather/MetaWeatherClient.java new file mode 100644 index 0000000000..0dc1f8ac95 --- /dev/null +++ b/vertx-and-rxjava/src/test/java/com/baeldung/weather/MetaWeatherClient.java @@ -0,0 +1,45 @@ +package com.baeldung.weather; + +import io.reactivex.Flowable; +import io.vertx.core.http.RequestOptions; +import io.vertx.reactivex.core.http.HttpClient; +import io.vertx.reactivex.core.http.HttpClientRequest; +import io.vertx.reactivex.core.http.HttpClientResponse; + +import static java.lang.String.format; + +class MetaWeatherClient { + + private static RequestOptions metawether = new RequestOptions() + .setHost("www.metaweather.com") + .setPort(443) + .setSsl(true); + + /** + * @return A flowable backed by vertx that automatically sends an HTTP request at soon as the first subscription is received. + */ + private static Flowable autoPerformingReq(HttpClient httpClient, String uri) { + HttpClientRequest req = httpClient.get(new RequestOptions(metawether).setURI(uri)); + return req.toFlowable() + .doOnSubscribe(subscription -> req.end()); + } + + static Flowable searchByCityName(HttpClient httpClient, String cityName) { + HttpClientRequest req = httpClient.get( + new RequestOptions() + .setHost("www.metaweather.com") + .setPort(443) + .setSsl(true) + .setURI(format("/api/location/search/?query=%s", cityName))); + return req + .toFlowable() + .doOnSubscribe(subscription -> req.end()); + } + + static Flowable getDataByPlaceId(HttpClient httpClient, long placeId) { + return autoPerformingReq( + httpClient, + format("/api/location/%s/", placeId)); + } + +} diff --git a/vertx-and-rxjava/src/test/java/com/baeldung/weather/VertxWithRxJavaIntegrationTest.java b/vertx-and-rxjava/src/test/java/com/baeldung/weather/VertxWithRxJavaIntegrationTest.java new file mode 100644 index 0000000000..a2ddbe5007 --- /dev/null +++ b/vertx-and-rxjava/src/test/java/com/baeldung/weather/VertxWithRxJavaIntegrationTest.java @@ -0,0 +1,92 @@ +package com.baeldung.weather; + +import io.reactivex.Flowable; +import io.reactivex.functions.Function; +import io.vertx.core.json.JsonObject; +import io.vertx.reactivex.core.Vertx; +import io.vertx.reactivex.core.buffer.Buffer; +import io.vertx.reactivex.core.file.FileSystem; +import io.vertx.reactivex.core.http.HttpClient; +import io.vertx.reactivex.core.http.HttpClientResponse; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.reactivestreams.Publisher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.time.ZonedDateTime; + +import static com.baeldung.weather.MetaWeatherClient.getDataByPlaceId; +import static com.baeldung.weather.MetaWeatherClient.searchByCityName; + +public class VertxWithRxJavaIntegrationTest { + + private Vertx vertx; + private HttpClient httpClient; + private FileSystem fileSystem; + private static Logger log = LoggerFactory.getLogger(VertxWithRxJavaIntegrationTest.class); + + @Before + public void setUp() { + vertx = Vertx.vertx(); + httpClient = vertx.createHttpClient(); + fileSystem = vertx.fileSystem(); + } + + @After + public void tearDown() { + vertx.close(); + } + + @Test + public void shouldDisplayLightLenghts() throws InterruptedException { + + // read the file that contains one city name per line + fileSystem + .rxReadFile("cities.txt").toFlowable() + .doOnNext(buffer -> log.info("File buffer ---\n{}\n---", buffer)) + .flatMap(buffer -> Flowable.fromArray(buffer.toString().split("\\r?\\n"))) + .doOnNext(city -> log.info("City from file: '{}'", city)) + .filter(city -> !city.startsWith("#")) + .doOnNext(city -> log.info("City that survived filtering: '{}'", city)) + .flatMap(city -> searchByCityName(httpClient, city)) + .flatMap(HttpClientResponse::toFlowable) + .doOnNext(buffer -> log.info("JSON of city detail: '{}'", buffer)) + .map(extractingWoeid()) + .flatMap(cityId -> getDataByPlaceId(httpClient, cityId)) + .flatMap(toBufferFlowable()) + .doOnNext(buffer -> log.info("JSON of place detail: '{}'", buffer)) + .map(Buffer::toJsonObject) + .map(toCityAndDayLength()) + .subscribe(System.out::println, Throwable::printStackTrace); + + Thread.sleep(20000); // enough to give time to complete the execution + } + + private static Function> toBufferFlowable() { + return response -> response + .toObservable() + .reduce( + Buffer.buffer(), + Buffer::appendBuffer).toFlowable(); + } + + private static Function extractingWoeid() { + return cityBuffer -> cityBuffer + .toJsonArray() + .getJsonObject(0) + .getLong("woeid"); + } + + private static Function toCityAndDayLength() { + return json -> { + ZonedDateTime sunRise = ZonedDateTime.parse(json.getString("sun_rise")); + ZonedDateTime sunSet = ZonedDateTime.parse(json.getString("sun_set")); + String cityName = json.getString("title"); + return new CityAndDayLength( + cityName, sunSet.toEpochSecond() - sunRise.toEpochSecond()); + }; + } + +} diff --git a/vertx-and-rxjava/src/test/resources/cities.txt b/vertx-and-rxjava/src/test/resources/cities.txt new file mode 100644 index 0000000000..dbe6e96758 --- /dev/null +++ b/vertx-and-rxjava/src/test/resources/cities.txt @@ -0,0 +1,6 @@ +Milan +Chicago +Cairo +Santiago +Moscow +Auckland \ No newline at end of file diff --git a/vertx-and-rxjava/src/test/resources/logback-test.xml b/vertx-and-rxjava/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..71e05a4e24 --- /dev/null +++ b/vertx-and-rxjava/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + [%thread{32}] %-5level %msg - %logger%n + + + + + + + + \ No newline at end of file