diff --git a/.gitignore b/.gitignore index 51f3d69d9f..180462a32f 100644 --- a/.gitignore +++ b/.gitignore @@ -42,3 +42,23 @@ spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties *.springBeans 20171220-JMeter.csv + +.factorypath +dependency-reduced-pom.xml +*.so +*.dylib +*.dll + +xml/src/test/resources/example_dom4j_new.xml +xml/src/test/resources/example_dom4j_updated.xml +xml/src/test/resources/example_jaxb_new.xml +core-java-io/hard_link.txt +core-java-io/target_link.txt +core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF +ethereum/logs/ +jmeter/src/main/resources/*-JMeter.csv + +**/node_modules/ +**/dist +**/tmp +**/out-tsc diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 9c5cdb8f2d..0000000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "testgitrepo"] - path = testgitrepo - url = /home/prd/Development/projects/idea/tutorials/spring-boot/src/main/resources/testgitrepo/ diff --git a/.travis.yml b/.travis.yml index 4df8a96f6d..5e2d690b4e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,7 +4,7 @@ before_install: - echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc install: skip -script: travis_wait 60 mvn -q install +script: travis_wait 60 mvn -q install -Pdefault sudo: required diff --git a/JGit/pom.xml b/JGit/pom.xml index 4feb31b758..176d55d321 100644 --- a/JGit/pom.xml +++ b/JGit/pom.xml @@ -1,11 +1,13 @@ - + 4.0.0 com.baeldung - JGitSnippets + JGit 1.0-SNAPSHOT jar http://maven.apache.org + JGit com.baeldung @@ -45,7 +47,6 @@ - UTF-8 4.5.0.201609210915-r diff --git a/JGit/src/main/resources/logback.xml b/JGit/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/JGit/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index 1d916c8409..d20968b455 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ The "REST with Spring" Classes ============================== -After 5 months of work, here's the Master Class of REST With Spring:
+Here's the Master Class of REST With Spring (price changes permanently next Friday):
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)** And here's the Master Class of Learn Spring Security:
@@ -19,7 +19,7 @@ In additional to Spring, the following technologies are in focus: `core Java`, ` Building the project ==================== -To do the full build, do: `mvn install -Dgib.enabled=false` +To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false` Working with the code in Eclipse diff --git a/Twitter4J/pom.xml b/Twitter4J/pom.xml index 0b581a5d43..80236a2cd4 100644 --- a/Twitter4J/pom.xml +++ b/Twitter4J/pom.xml @@ -1,6 +1,7 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 + com.mabsisa Twitter4J jar @@ -14,17 +15,11 @@ 1.0.0-SNAPSHOT
- - UTF-8 - UTF-8 - 1.8 - - org.twitter4j twitter4j-stream - 4.0.6 + ${twitter4j-stream.version} @@ -49,4 +44,8 @@ + + 4.0.6 + +
diff --git a/Twitter4J/src/main/resources/logback.xml b/Twitter4J/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/Twitter4J/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/activejdbc/pom.xml b/activejdbc/pom.xml index f6e21edeb1..0c8047f10b 100644 --- a/activejdbc/pom.xml +++ b/activejdbc/pom.xml @@ -1,5 +1,5 @@ + 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 activejdbc @@ -15,12 +15,6 @@ - - junit - junit - ${junit.version} - test - org.javalite activejdbc @@ -133,10 +127,8 @@ - UTF-8 1.4.13 development.test,development - 1.7.9 5.1.34 diff --git a/activejdbc/src/main/resources/logback.xml b/activejdbc/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/activejdbc/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/akka-streams/pom.xml b/akka-streams/pom.xml index 3142e4e68a..a885753ce2 100644 --- a/akka-streams/pom.xml +++ b/akka-streams/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 akka-streams akka-streams diff --git a/akka-streams/src/main/resources/logback.xml b/akka-streams/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/akka-streams/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/algorithms/README.md b/algorithms/README.md index 50cdfbbd4f..47ddd7028a 100644 --- a/algorithms/README.md +++ b/algorithms/README.md @@ -5,7 +5,6 @@ - [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization) - [Validating Input With Finite Automata in Java](http://www.baeldung.com/java-finite-automata) - [Introduction to Jenetics Library](http://www.baeldung.com/jenetics) -- [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) @@ -21,4 +20,7 @@ - [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku) - [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words) - [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations) -- [Find All Pairs of Numbers in an Array That Add Up to a Given Sum](http://www.baeldung.com/java-algorithm-number-pairs-sum) +- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic) +- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity) +- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element) +- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation) diff --git a/algorithms/pom.xml b/algorithms/pom.xml index fdc8931f04..eda87d6c75 100644 --- a/algorithms/pom.xml +++ b/algorithms/pom.xml @@ -1,5 +1,5 @@ + 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 algorithms @@ -79,7 +79,6 @@ - 1.5.0 1.16.12 3.6.1 1.0.1 diff --git a/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java b/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java index c82883425d..ce04d26db3 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java @@ -6,7 +6,6 @@ import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing; import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization; import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; import com.baeldung.algorithms.slope_one.SlopeOne; -import com.baeldung.algorithms.pairsaddupnumber.FindPairs; public class RunAlgorithm { @@ -39,12 +38,6 @@ public class RunAlgorithm { case 5: System.out.println("Please run the DijkstraAlgorithmTest."); break; - case 6: - final FindPairs findPairs = new FindPairs(); - final int[] input = {1, 4, 3, 2, 1, 4, 4, 3, 3}; - final int sum = 6; - findPairs.execute(input, sum); - break; default: System.out.println("Unknown option"); break; diff --git a/algorithms/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java b/algorithms/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java new file mode 100644 index 0000000000..0c8eb86a38 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java @@ -0,0 +1,38 @@ +package com.baeldung.algorithms.distancebetweenpoints; + +import java.awt.geom.Point2D; + +public class DistanceBetweenPointsService { + + public double calculateDistanceBetweenPoints( + double x1, + double y1, + double x2, + double y2) { + + return Math.sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1)); + } + + public double calculateDistanceBetweenPointsWithHypot( + double x1, + double y1, + double x2, + double y2) { + + double ac = Math.abs(y2 - y1); + double cb = Math.abs(x2 - x1); + + return Math.hypot(ac, cb); + } + + public double calculateDistanceBetweenPointsWithPoint2D( + double x1, + double y1, + double x2, + double y2) { + + return Point2D.distance(x1, y1, x2, y2); + + } + +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java b/algorithms/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java new file mode 100644 index 0000000000..35d6c8b424 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java @@ -0,0 +1,21 @@ +package com.baeldung.algorithms.linesintersection; + +import java.awt.Point; +import java.util.Optional; + +public class LinesIntersectionService { + + public Optional calculateIntersectionPoint(double m1, double b1, double m2, double b2) { + + if (m1 == m2) { + return Optional.empty(); + } + + double x = (b2 - b1) / (m1 - m2); + double y = m1 * x + b1; + + Point point = new Point(); + point.setLocation(x, y); + return Optional.of(point); + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/MonteCarloTreeSearch.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/MonteCarloTreeSearch.java index f428df45d3..a4918f674d 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/MonteCarloTreeSearch.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/MonteCarloTreeSearch.java @@ -10,7 +10,7 @@ public class MonteCarloTreeSearch { private static final int WIN_SCORE = 10; private int level; - private int oponent; + private int opponent; public MonteCarloTreeSearch() { this.level = 3; @@ -32,11 +32,11 @@ public class MonteCarloTreeSearch { long start = System.currentTimeMillis(); long end = start + 60 * getMillisForCurrentLevel(); - oponent = 3 - playerNo; + opponent = 3 - playerNo; Tree tree = new Tree(); Node rootNode = tree.getRoot(); rootNode.getState().setBoard(board); - rootNode.getState().setPlayerNo(oponent); + rootNode.getState().setPlayerNo(opponent); while (System.currentTimeMillis() < end) { // Phase 1 - Selection @@ -93,7 +93,7 @@ public class MonteCarloTreeSearch { State tempState = tempNode.getState(); int boardStatus = tempState.getBoard().checkStatus(); - if (boardStatus == oponent) { + if (boardStatus == opponent) { tempNode.getParent().getState().setWinScore(Integer.MIN_VALUE); return boardStatus; } diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java index d855f775a8..5d4b265500 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java @@ -87,7 +87,7 @@ public class State { void randomPlay() { List availablePositions = this.board.getEmptyPositions(); int totalPossibilities = availablePositions.size(); - int selectRandom = (int) (Math.random() * ((totalPossibilities - 1) + 1)); + int selectRandom = (int) (Math.random() * totalPossibilities); this.board.performMove(this.playerNo, availablePositions.get(selectRandom)); } diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java index 8b47fa0fdf..5ca2d626f1 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java @@ -148,7 +148,7 @@ public class Board { System.out.println("Game Draw"); break; case IN_PROGRESS: - System.out.println("Game In rogress"); + System.out.println("Game In Progress"); break; } } diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java index 20f9e992b5..0ad6510e50 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java @@ -65,7 +65,7 @@ public class Node { public Node getRandomChildNode() { int noOfPossibleMoves = this.childArray.size(); - int selectRandom = (int) (Math.random() * ((noOfPossibleMoves - 1) + 1)); + int selectRandom = (int) (Math.random() * noOfPossibleMoves); return this.childArray.get(selectRandom); } diff --git a/algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/MiddleElementLookup.java b/algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/MiddleElementLookup.java new file mode 100644 index 0000000000..7e25e0456b --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/MiddleElementLookup.java @@ -0,0 +1,88 @@ +package com.baeldung.algorithms.middleelementlookup; + +import java.util.LinkedList; +import java.util.Optional; + +public class MiddleElementLookup { + + public static Optional findMiddleElementLinkedList(LinkedList linkedList) { + if (linkedList == null || linkedList.isEmpty()) { + return Optional.empty(); + } + + return Optional.ofNullable(linkedList.get((linkedList.size() - 1) / 2)); + } + + public static Optional findMiddleElementFromHead(Node head) { + if (head == null) { + return Optional.empty(); + } + + // calculate the size of the list + Node current = head; + int size = 1; + while (current.hasNext()) { + current = current.next(); + size++; + } + + // iterate till the middle element + current = head; + for (int i = 0; i < (size - 1) / 2; i++) { + current = current.next(); + } + + return Optional.ofNullable(current.data()); + } + + public static Optional findMiddleElementFromHead1PassRecursively(Node head) { + if (head == null) { + return Optional.empty(); + } + + MiddleAuxRecursion middleAux = new MiddleAuxRecursion(); + findMiddleRecursively(head, middleAux); + return Optional.ofNullable(middleAux.middle.data()); + } + + private static void findMiddleRecursively(Node node, MiddleAuxRecursion middleAux) { + if (node == null) { + // reached the end + middleAux.length = middleAux.length / 2; + return; + } + middleAux.length++; + findMiddleRecursively(node.next(), middleAux); + + if (middleAux.length == 0) { + // found the middle + middleAux.middle = node; + } + + middleAux.length--; + } + + public static Optional findMiddleElementFromHead1PassIteratively(Node head) { + if (head == null) { + return Optional.empty(); + } + + Node slowPointer = head; + Node fastPointer = head; + + while (fastPointer.hasNext() && fastPointer.next() + .hasNext()) { + fastPointer = fastPointer.next() + .next(); + slowPointer = slowPointer.next(); + } + + return Optional.ofNullable(slowPointer.data()); + } + + private static class MiddleAuxRecursion { + Node middle; + int length = 0; + } + +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/Node.java b/algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/Node.java new file mode 100644 index 0000000000..2a594937e3 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/Node.java @@ -0,0 +1,34 @@ +package com.baeldung.algorithms.middleelementlookup; + +public class Node { + private Node next; + private String data; + + public Node(String data) { + this.data = data; + } + + public String data() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public boolean hasNext() { + return next != null; + } + + public Node next() { + return next; + } + + public void setNext(Node next) { + this.next = next; + } + + public String toString() { + return this.data; + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/prime/PrimeGenerator.java b/algorithms/src/main/java/com/baeldung/algorithms/prime/PrimeGenerator.java deleted file mode 100644 index 48d51a8848..0000000000 --- a/algorithms/src/main/java/com/baeldung/algorithms/prime/PrimeGenerator.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.baeldung.algorithms.prime; - -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -public class PrimeGenerator { - public static List sieveOfEratosthenes(int n) { - final boolean prime[] = new boolean[n + 1]; - Arrays.fill(prime, true); - - for (int p = 2; p * p <= n; p++) { - if (prime[p]) { - for (int i = p * 2; i <= n; i += p) - prime[i] = false; - } - } - - final List primes = new LinkedList<>(); - for (int i = 2; i <= n; i++) { - if (prime[i]) - primes.add(i); - } - return primes; - } - - public static List primeNumbersBruteForce(int max) { - final List primeNumbers = new LinkedList(); - for (int i = 2; i <= max; i++) { - if (isPrimeBruteForce(i)) { - primeNumbers.add(i); - } - } - return primeNumbers; - } - - private static boolean isPrimeBruteForce(int x) { - for (int i = 2; i < x; i++) { - if (x % i == 0) { - return false; - } - } - return true; - } - - public static List primeNumbersTill(int max) { - return IntStream.rangeClosed(2, max) - .filter(x -> isPrime(x)) - .boxed() - .collect(Collectors.toList()); - } - - private static boolean isPrime(int x) { - return IntStream.rangeClosed(2, (int) (Math.sqrt(x))) - .allMatch(n -> x % n != 0); - } -} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Point.java b/algorithms/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Point.java new file mode 100644 index 0000000000..68b1e7c594 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Point.java @@ -0,0 +1,29 @@ +package com.baeldung.algorithms.rectanglesoverlap; + +public class Point { + + private int x; + private int y; + + public Point(int x, int y) { + this.x = x; + this.y = y; + } + + public int getX() { + return x; + } + + public void setX(int x) { + this.x = x; + } + + public int getY() { + return y; + } + + public void setY(int y) { + this.y = y; + } + +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java b/algorithms/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java new file mode 100644 index 0000000000..38f5edec61 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java @@ -0,0 +1,40 @@ +package com.baeldung.algorithms.rectanglesoverlap; + +public class Rectangle { + + private Point bottomLeft; + private Point topRight; + + public Rectangle(Point bottomLeft, Point topRight) { + this.bottomLeft = bottomLeft; + this.topRight = topRight; + } + + public Point getBottomLeft() { + return bottomLeft; + } + + public void setBottomLeft(Point bottomLeft) { + this.bottomLeft = bottomLeft; + } + + public Point getTopRight() { + return topRight; + } + + public void setTopRight(Point topRight) { + this.topRight = topRight; + } + + public boolean isOverlapping(Rectangle other) { + // one rectangle is to the top of the other + if (this.topRight.getY() < other.bottomLeft.getY() || this.bottomLeft.getY() > other.topRight.getY()) { + return false; + } + // one rectangle is to the left of the other + if (this.topRight.getX() < other.bottomLeft.getX() || this.bottomLeft.getX() > other.topRight.getX()) { + return false; + } + return true; + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/romannumerals/RomanArabicConverter.java b/algorithms/src/main/java/com/baeldung/algorithms/romannumerals/RomanArabicConverter.java new file mode 100644 index 0000000000..ab0922ecf4 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/romannumerals/RomanArabicConverter.java @@ -0,0 +1,52 @@ +package com.baeldung.algorithms.romannumerals; + +import java.util.List; + +class RomanArabicConverter { + + public static int romanToArabic(String input) { + String romanNumeral = input.toUpperCase(); + int result = 0; + + List romanNumerals = RomanNumeral.getReverseSortedValues(); + + int i = 0; + + while ((romanNumeral.length() > 0) && (i < romanNumerals.size())) { + RomanNumeral symbol = romanNumerals.get(i); + if (romanNumeral.startsWith(symbol.name())) { + result += symbol.getValue(); + romanNumeral = romanNumeral.substring(symbol.name().length()); + } else { + i++; + } + } + if (romanNumeral.length() > 0) { + throw new IllegalArgumentException(input + " cannot be converted to a Roman Numeral"); + } + + return result; + } + + public static String arabicToRoman(int number) { + if ((number <= 0) || (number > 4000)) { + throw new IllegalArgumentException(number + " is not in range (0,4000]"); + } + + List romanNumerals = RomanNumeral.getReverseSortedValues(); + + int i = 0; + StringBuilder sb = new StringBuilder(); + + while (number > 0 && i < romanNumerals.size()) { + RomanNumeral currentSymbol = romanNumerals.get(i); + if (currentSymbol.getValue() <= number) { + sb.append(currentSymbol.name()); + number -= currentSymbol.getValue(); + } else { + i++; + } + } + return sb.toString(); + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/romannumerals/RomanNumeral.java b/algorithms/src/main/java/com/baeldung/algorithms/romannumerals/RomanNumeral.java new file mode 100644 index 0000000000..219f0b5090 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/romannumerals/RomanNumeral.java @@ -0,0 +1,26 @@ +package com.baeldung.algorithms.romannumerals; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +enum RomanNumeral { + I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000); + + private int value; + + RomanNumeral(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + + public static List getReverseSortedValues() { + return Arrays.stream(values()) + .sorted(Comparator.comparing((RomanNumeral e) -> e.value).reversed()) + .collect(Collectors.toList()); + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java b/algorithms/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java new file mode 100644 index 0000000000..2dd1fdcb75 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java @@ -0,0 +1,35 @@ +package com.baeldung.algorithms.string; + +public class EnglishAlphabetLetters { + + public static boolean checkStringForAllTheLetters(String input) { + boolean[] visited = new boolean[26]; + + int index = 0; + + for (int id = 0; id < input.length(); id++) { + if ('a' <= input.charAt(id) && input.charAt(id) <= 'z') { + index = input.charAt(id) - 'a'; + } else if ('A' <= input.charAt(id) && input.charAt(id) <= 'Z') { + index = input.charAt(id) - 'A'; + } + visited[index] = true; + } + + for (int id = 0; id < 26; id++) { + if (!visited[id]) { + return false; + } + } + return true; + } + + public static boolean checkStringForAllLetterUsingStream(String input) { + long c = input.toLowerCase().chars().filter(ch -> ch >= 'a' && ch <= 'z').distinct().count(); + return c == 26; + } + + public static void main(String[] args) { + checkStringForAllLetterUsingStream("intit"); + } +} \ No newline at end of file diff --git a/algorithms/src/main/resources/logback.xml b/algorithms/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/algorithms/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/algorithms/src/test/java/algorithms/HillClimbingAlgorithmTest.java b/algorithms/src/test/java/algorithms/HillClimbingAlgorithmTest.java deleted file mode 100644 index 666adbb180..0000000000 --- a/algorithms/src/test/java/algorithms/HillClimbingAlgorithmTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package algorithms; - -import com.baeldung.algorithms.hillclimbing.HillClimbing; -import com.baeldung.algorithms.hillclimbing.State; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; -import java.util.Stack; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -public class HillClimbingAlgorithmTest { - private Stack initStack; - private Stack goalStack; - - @Before - public void initStacks() { - String blockArr[] = { "B", "C", "D", "A" }; - String goalBlockArr[] = { "A", "B", "C", "D" }; - initStack = new Stack<>(); - for (String block : blockArr) - initStack.push(block); - goalStack = new Stack<>(); - for (String block : goalBlockArr) - goalStack.push(block); - } - - @Test - public void givenInitAndGoalState_whenGetPathWithHillClimbing_thenPathFound() { - HillClimbing hillClimbing = new HillClimbing(); - - List path; - try { - path = hillClimbing.getRouteWithHillClimbing(initStack, goalStack); - assertNotNull(path); - assertEquals(path.get(path.size() - 1) - .getState() - .get(0), goalStack); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void givenCurrentState_whenFindNextState_thenBetterHeuristics() { - HillClimbing hillClimbing = new HillClimbing(); - List> initList = new ArrayList<>(); - initList.add(initStack); - State currentState = new State(initList); - currentState.setHeuristics(hillClimbing.getHeuristicsValue(initList, goalStack)); - State nextState = hillClimbing.findNextState(currentState, goalStack); - assertTrue(nextState.getHeuristics() > currentState.getHeuristics()); - } -} \ No newline at end of file diff --git a/algorithms/src/test/java/algorithms/StringSearchAlgorithmsTest.java b/algorithms/src/test/java/algorithms/StringSearchAlgorithmsTest.java deleted file mode 100755 index e260cd7e5b..0000000000 --- a/algorithms/src/test/java/algorithms/StringSearchAlgorithmsTest.java +++ /dev/null @@ -1,25 +0,0 @@ -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/binarysearch/BinarySearchTest.java b/algorithms/src/test/java/algorithms/binarysearch/BinarySearchTest.java deleted file mode 100644 index 959f47a275..0000000000 --- a/algorithms/src/test/java/algorithms/binarysearch/BinarySearchTest.java +++ /dev/null @@ -1,43 +0,0 @@ -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 { - - int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; - int key = 6; - int expectedIndexForSearchKey = 7; - int low = 0; - int high = sortedArray.length - 1; - List sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9); - - @Test - public void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() { - BinarySearch binSearch = new BinarySearch(); - Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high)); - } - - @Test - public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() { - BinarySearch binSearch = new BinarySearch(); - Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high)); - } - - @Test - public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() { - BinarySearch binSearch = new BinarySearch(); - Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key)); - } - - @Test - public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() { - BinarySearch binSearch = new BinarySearch(); - Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key)); - } - -} diff --git a/algorithms/src/test/java/algorithms/mcts/MCTSTest.java b/algorithms/src/test/java/algorithms/mcts/MCTSTest.java deleted file mode 100644 index 375f66ab6f..0000000000 --- a/algorithms/src/test/java/algorithms/mcts/MCTSTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package algorithms.mcts; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.List; - -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.algorithms.mcts.montecarlo.MonteCarloTreeSearch; -import com.baeldung.algorithms.mcts.montecarlo.State; -import com.baeldung.algorithms.mcts.montecarlo.UCT; -import com.baeldung.algorithms.mcts.tictactoe.Board; -import com.baeldung.algorithms.mcts.tictactoe.Position; -import com.baeldung.algorithms.mcts.tree.Tree; - -public class MCTSTest { - private Tree gameTree; - private MonteCarloTreeSearch mcts; - - @Before - public void initGameTree() { - gameTree = new Tree(); - mcts = new MonteCarloTreeSearch(); - } - - @Test - public void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() { - double uctValue = 15.79; - assertEquals(UCT.uctValue(600, 300, 20), uctValue, 0.01); - } - - @Test - public void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() { - State initState = gameTree.getRoot().getState(); - List possibleStates = initState.getAllPossibleStates(); - assertTrue(possibleStates.size() > 0); - } - - @Test - public void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() { - Board board = new Board(); - int initAvailablePositions = board.getEmptyPositions().size(); - board.performMove(Board.P1, new Position(1, 1)); - int availablePositions = board.getEmptyPositions().size(); - assertTrue(initAvailablePositions > availablePositions); - } - - @Test - public void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() { - Board board = new Board(); - - int player = Board.P1; - int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE; - for (int i = 0; i < totalMoves; i++) { - board = mcts.findNextMove(board, player); - if (board.checkStatus() != -1) { - break; - } - player = 3 - player; - } - int winStatus = board.checkStatus(); - assertEquals(winStatus, Board.DRAW); - } - - @Test - public void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() { - Board board = new Board(); - MonteCarloTreeSearch mcts1 = new MonteCarloTreeSearch(); - mcts1.setLevel(1); - MonteCarloTreeSearch mcts3 = new MonteCarloTreeSearch(); - mcts3.setLevel(3); - - int player = Board.P1; - int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE; - for (int i = 0; i < totalMoves; i++) { - if (player == Board.P1) - board = mcts3.findNextMove(board, player); - else - board = mcts1.findNextMove(board, player); - - if (board.checkStatus() != -1) { - break; - } - player = 3 - player; - } - int winStatus = board.checkStatus(); - assertTrue(winStatus == Board.DRAW || winStatus == Board.P1); - } - -} diff --git a/algorithms/src/test/java/algorithms/minimax/MinimaxTest.java b/algorithms/src/test/java/algorithms/minimax/MinimaxTest.java deleted file mode 100644 index b29c16386c..0000000000 --- a/algorithms/src/test/java/algorithms/minimax/MinimaxTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package algorithms.minimax; - -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; -import com.baeldung.algorithms.minimax.MiniMax; -import com.baeldung.algorithms.minimax.Tree; - -public class MinimaxTest { - private Tree gameTree; - private MiniMax miniMax; - - @Before - public void initMiniMaxUtility() { - miniMax = new MiniMax(); - } - - @Test - public void givenMiniMax_whenConstructTree_thenNotNullTree() { - assertNull(gameTree); - miniMax.constructTree(6); - gameTree = miniMax.getTree(); - assertNotNull(gameTree); - } - - @Test - public void givenMiniMax_whenCheckWin_thenComputeOptimal() { - miniMax.constructTree(6); - boolean result = miniMax.checkWin(); - assertTrue(result); - miniMax.constructTree(8); - result = miniMax.checkWin(); - assertFalse(result); - } -} diff --git a/algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java similarity index 94% rename from algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java index b0218ae23e..2ac7adc3aa 100644 --- a/algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import org.junit.Assert; import org.junit.Test; diff --git a/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java similarity index 92% rename from algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java index fa8ecdee77..e819da4b36 100644 --- a/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import org.junit.Assert; import org.junit.Test; diff --git a/algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java similarity index 98% rename from algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java index 68386278fc..bbc4d4f398 100644 --- a/algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import org.junit.Test; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java new file mode 100644 index 0000000000..e817d195b3 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java @@ -0,0 +1,58 @@ +package com.baeldung.algorithms; + +import com.baeldung.algorithms.hillclimbing.HillClimbing; +import com.baeldung.algorithms.hillclimbing.State; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class HillClimbingAlgorithmUnitTest { + private Stack initStack; + private Stack goalStack; + + @Before + public void initStacks() { + String blockArr[] = { "B", "C", "D", "A" }; + String goalBlockArr[] = { "A", "B", "C", "D" }; + initStack = new Stack<>(); + for (String block : blockArr) + initStack.push(block); + goalStack = new Stack<>(); + for (String block : goalBlockArr) + goalStack.push(block); + } + + @Test + public void givenInitAndGoalState_whenGetPathWithHillClimbing_thenPathFound() { + HillClimbing hillClimbing = new HillClimbing(); + + List path; + try { + path = hillClimbing.getRouteWithHillClimbing(initStack, goalStack); + assertNotNull(path); + assertEquals(path.get(path.size() - 1) + .getState() + .get(0), goalStack); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void givenCurrentState_whenFindNextState_thenBetterHeuristics() { + HillClimbing hillClimbing = new HillClimbing(); + List> initList = new ArrayList<>(); + initList.add(initStack); + State currentState = new State(initList); + currentState.setHeuristics(hillClimbing.getHeuristicsValue(initList, goalStack)); + State nextState = hillClimbing.findNextState(currentState, goalStack); + assertTrue(nextState.getHeuristics() > currentState.getHeuristics()); + } +} \ No newline at end of file diff --git a/algorithms/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java new file mode 100644 index 0000000000..2cda0ccb36 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java @@ -0,0 +1,118 @@ +package com.baeldung.algorithms; + +import com.baeldung.algorithms.middleelementlookup.MiddleElementLookup; +import com.baeldung.algorithms.middleelementlookup.Node; +import org.junit.Test; + +import java.util.LinkedList; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +public class MiddleElementLookupUnitTest { + + @Test + public void whenFindingMiddleLinkedList_thenMiddleFound() { + assertEquals("3", MiddleElementLookup + .findMiddleElementLinkedList(createLinkedList(5)) + .get()); + assertEquals("2", MiddleElementLookup + .findMiddleElementLinkedList(createLinkedList(4)) + .get()); + } + + @Test + public void whenFindingMiddleFromHead_thenMiddleFound() { + assertEquals("3", MiddleElementLookup + .findMiddleElementFromHead(createNodesList(5)) + .get()); + assertEquals("2", MiddleElementLookup + .findMiddleElementFromHead(createNodesList(4)) + .get()); + } + + @Test + public void whenFindingMiddleFromHead1PassRecursively_thenMiddleFound() { + assertEquals("3", MiddleElementLookup + .findMiddleElementFromHead1PassRecursively(createNodesList(5)) + .get()); + assertEquals("2", MiddleElementLookup + .findMiddleElementFromHead1PassRecursively(createNodesList(4)) + .get()); + } + + @Test + public void whenFindingMiddleFromHead1PassIteratively_thenMiddleFound() { + assertEquals("3", MiddleElementLookup + .findMiddleElementFromHead1PassIteratively(createNodesList(5)) + .get()); + assertEquals("2", MiddleElementLookup + .findMiddleElementFromHead1PassIteratively(createNodesList(4)) + .get()); + } + + @Test + public void whenListEmptyOrNull_thenMiddleNotFound() { + // null list + assertFalse(MiddleElementLookup + .findMiddleElementLinkedList(null) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead(null) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead1PassIteratively(null) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead1PassRecursively(null) + .isPresent()); + + // empty LinkedList + assertFalse(MiddleElementLookup + .findMiddleElementLinkedList(new LinkedList<>()) + .isPresent()); + + // LinkedList with nulls + LinkedList nullsList = new LinkedList<>(); + nullsList.add(null); + nullsList.add(null); + assertFalse(MiddleElementLookup + .findMiddleElementLinkedList(nullsList) + .isPresent()); + + // nodes with null values + assertFalse(MiddleElementLookup + .findMiddleElementFromHead(new Node(null)) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead1PassIteratively(new Node(null)) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead1PassRecursively(new Node(null)) + .isPresent()); + } + + private static LinkedList createLinkedList(int n) { + LinkedList list = new LinkedList<>(); + + for (int i = 1; i <= n; i++) { + list.add(String.valueOf(i)); + } + + return list; + } + + private static Node createNodesList(int n) { + Node head = new Node("1"); + Node current = head; + + for (int i = 2; i <= n; i++) { + Node newNode = new Node(String.valueOf(i)); + current.setNext(newNode); + current = newNode; + } + + return head; + } + +} diff --git a/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java similarity index 98% rename from algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java index 99e962773f..fddccfcd9f 100644 --- a/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import com.baeldung.algorithms.automata.*; import org.junit.Test; diff --git a/algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java similarity index 90% rename from algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java index 6ee129ece9..2ce7d75e43 100644 --- a/algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import org.junit.Assert; import org.junit.Test; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/StringSearchAlgorithmsUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/StringSearchAlgorithmsUnitTest.java new file mode 100755 index 0000000000..dfe015aad2 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/StringSearchAlgorithmsUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.algorithms; + + +import org.junit.Assert; +import org.junit.Test; + +import com.baeldung.algorithms.string.search.StringSearchAlgorithms; + +public class StringSearchAlgorithmsUnitTest { + + + @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/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java b/algorithms/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java new file mode 100644 index 0000000000..1e9188f726 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java @@ -0,0 +1,139 @@ +package com.baeldung.algorithms.analysis; + +import org.junit.Test; + +public class AnalysisRunnerLiveTest { + + int n = 10; + int total = 0; + + @Test + public void whenConstantComplexity_thenConstantRuntime() { + + System.out.println("**** n = " + n + " ****"); + System.out.println(); + + // Constant Time + System.out.println("**** Constant time ****"); + + System.out.println("Hey - your input is: " + n); + System.out.println("Running time not dependent on input size!"); + System.out.println(); + } + + @Test + public void whenLogarithmicComplexity_thenLogarithmicRuntime() { + // Logarithmic Time + System.out.println("**** Logarithmic Time ****"); + for (int i = 1; i < n; i = i * 2) { + // System.out.println("Hey - I'm busy looking at: " + i); + total++; + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenLinearComplexity_thenLinearRuntime() { + // Linear Time + System.out.println("**** Linear Time ****"); + for (int i = 0; i < n; i++) { + // System.out.println("Hey - I'm busy looking at: " + i); + total++; + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + + } + + @Test + public void whenNLogNComplexity_thenNLogNRuntime() { + // N Log N Time + System.out.println("**** nlogn Time ****"); + total = 0; + for ( + + int i = 1; i <= n; i++) { + for (int j = 1; j < n; j = j * 2) { + // System.out.println("Hey - I'm busy looking at: " + i + " and " + j); + total++; + } + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenQuadraticComplexity_thenQuadraticRuntime() { + // Quadratic Time + System.out.println("**** Quadratic Time ****"); + total = 0; + for ( + + int i = 1; i <= n; i++) { + for (int j = 1; j <= n; j++) { + // System.out.println("Hey - I'm busy looking at: " + i + " and " + j); + total++; + } + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenCubicComplexity_thenCubicRuntime() { + // Cubic Time + System.out.println("**** Cubic Time ****"); + total = 0; + for ( + + int i = 1; i <= n; i++) { + for (int j = 1; j <= n; j++) { + for (int k = 1; k <= n; k++) { + // System.out.println("Hey - I'm busy looking at: " + i + " and " + j + " and " + k); + total++; + } + } + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenExponentialComplexity_thenExponentialRuntime() { + // Exponential Time + System.out.println("**** Exponential Time ****"); + total = 0; + for ( + + int i = 1; i <= Math.pow(2, n); i++) { + // System.out.println("Hey - I'm busy looking at: " + i); + total++; + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenFactorialComplexity_thenFactorialRuntime() { + // Factorial Time + System.out.println("**** Factorial Time ****"); + total = 0; + for ( + + int i = 1; i <= + + factorial(n); i++) { + // System.out.println("Hey - I'm busy looking at: " + i); + total++; + } + System.out.println("Total amount of times run: " + total); + } + + static int factorial(int n) { + if (n == 0 || n == 1) + return 1; + else + return n * factorial(n - 1); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java new file mode 100644 index 0000000000..826682d373 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.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 BinarySearchUnitTest { + + int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; + int key = 6; + int expectedIndexForSearchKey = 7; + int low = 0; + int high = sortedArray.length - 1; + List sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9); + + @Test + public void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() { + BinarySearch binSearch = new BinarySearch(); + Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high)); + } + + @Test + public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() { + BinarySearch binSearch = new BinarySearch(); + Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high)); + } + + @Test + public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() { + BinarySearch binSearch = new BinarySearch(); + Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key)); + } + + @Test + public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() { + BinarySearch binSearch = new BinarySearch(); + Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key)); + } + +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortTest.java b/algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortTest.java deleted file mode 100644 index 7774eb3e67..0000000000 --- a/algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.algorithms.bubblesort; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class BubbleSortTest { - - @Test - public void givenIntegerArray_whenSortedWithBubbleSort_thenGetSortedArray() { - Integer[] array = { 2, 1, 4, 6, 3, 5 }; - Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 }; - BubbleSort bubbleSort = new BubbleSort(); - bubbleSort.bubbleSort(array); - assertArrayEquals(array, sortedArray); - } - - @Test - public void givenIntegerArray_whenSortedWithOptimizedBubbleSort_thenGetSortedArray() { - Integer[] array = { 2, 1, 4, 6, 3, 5 }; - Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 }; - BubbleSort bubbleSort = new BubbleSort(); - bubbleSort.optimizedBubbleSort(array); - assertArrayEquals(array, sortedArray); - } -} \ No newline at end of file diff --git a/algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java new file mode 100644 index 0000000000..c7f3f7dc38 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.algorithms.bubblesort; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class BubbleSortUnitTest { + + @Test + public void givenIntegerArray_whenSortedWithBubbleSort_thenGetSortedArray() { + Integer[] array = { 2, 1, 4, 6, 3, 5 }; + Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 }; + BubbleSort bubbleSort = new BubbleSort(); + bubbleSort.bubbleSort(array); + assertArrayEquals(array, sortedArray); + } + + @Test + public void givenIntegerArray_whenSortedWithOptimizedBubbleSort_thenGetSortedArray() { + Integer[] array = { 2, 1, 4, 6, 3, 5 }; + Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 }; + BubbleSort bubbleSort = new BubbleSort(); + bubbleSort.optimizedBubbleSort(array); + assertArrayEquals(array, sortedArray); + } +} \ No newline at end of file diff --git a/algorithms/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java new file mode 100644 index 0000000000..785afdbb2b --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.algorithms.distancebetweenpoints; + +import org.junit.Test; + +import com.baeldung.algorithms.distancebetweenpoints.DistanceBetweenPointsService; + +import static org.junit.Assert.assertEquals; + +public class DistanceBetweenPointsServiceUnitTest { + + private DistanceBetweenPointsService service = new DistanceBetweenPointsService(); + + @Test + public void givenTwoPoints_whenCalculateDistanceByFormula_thenCorrect() { + + double x1 = 3; + double y1 = 4; + double x2 = 7; + double y2 = 1; + + double distance = service.calculateDistanceBetweenPoints(x1, y1, x2, y2); + + assertEquals(distance, 5, 0.001); + + } + + @Test + public void givenTwoPoints_whenCalculateDistanceWithHypot_thenCorrect() { + + double x1 = 3; + double y1 = 4; + double x2 = 7; + double y2 = 1; + + double distance = service.calculateDistanceBetweenPointsWithHypot(x1, y1, x2, y2); + + assertEquals(distance, 5, 0.001); + + } + + @Test + public void givenTwoPoints_whenCalculateDistanceWithPoint2D_thenCorrect() { + + double x1 = 3; + double y1 = 4; + double x2 = 7; + double y2 = 1; + + double distance = service.calculateDistanceBetweenPointsWithPoint2D(x1, y1, x2, y2); + + assertEquals(distance, 5, 0.001); + + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceTest.java b/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceTest.java deleted file mode 100644 index bab2f480a5..0000000000 --- a/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.algorithms.editdistance; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -import static org.junit.Assert.assertEquals; - -@RunWith(Parameterized.class) -public class EditDistanceTest extends EditDistanceDataProvider { - - private String x; - private String y; - private int result; - - public EditDistanceTest(String a, String b, int res) { - super(); - x = a; - y = b; - result = res; - } - - @Test - public void testEditDistance_RecursiveImplementation() { - assertEquals(result, EditDistanceRecursive.calculate(x, y)); - } - - @Test - public void testEditDistance_givenDynamicProgrammingImplementation() { - assertEquals(result, EditDistanceDynamicProgramming.calculate(x, y)); - } -} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java new file mode 100644 index 0000000000..0df4715b80 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.algorithms.editdistance; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import static org.junit.Assert.assertEquals; + +@RunWith(Parameterized.class) +public class EditDistanceUnitTest extends EditDistanceDataProvider { + + private String x; + private String y; + private int result; + + public EditDistanceUnitTest(String a, String b, int res) { + super(); + x = a; + y = b; + result = res; + } + + @Test + public void testEditDistance_RecursiveImplementation() { + assertEquals(result, EditDistanceRecursive.calculate(x, y)); + } + + @Test + public void testEditDistance_givenDynamicProgrammingImplementation() { + assertEquals(result, EditDistanceDynamicProgramming.calculate(x, y)); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java new file mode 100644 index 0000000000..22371107f3 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.algorithms.linesintersection; + +import java.awt.Point; +import java.util.Optional; + +import org.junit.Test; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertEquals; + +public class LinesIntersectionServiceUnitTest { + private LinesIntersectionService service = new LinesIntersectionService(); + + @Test + public void givenNotParallelLines_whenCalculatePoint_thenPresent() { + + double m1 = 0; + double b1 = 0; + double m2 = 1; + double b2 = -1; + + Optional point = service.calculateIntersectionPoint(m1, b1, m2, b2); + + assertTrue(point.isPresent()); + assertEquals(point.get().getX(), 1, 0.001); + assertEquals(point.get().getY(), 0, 0.001); + } + + @Test + public void givenParallelLines_whenCalculatePoint_thenEmpty() { + double m1 = 1; + double b1 = 0; + double m2 = 1; + double b2 = -1; + + Optional point = service.calculateIntersectionPoint(m1, b1, m2, b2); + + assertFalse(point.isPresent()); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceTest.java deleted file mode 100644 index 7f9b8acdbd..0000000000 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceTest.java +++ /dev/null @@ -1,23 +0,0 @@ -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/CycleDetectionBruteForceUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.java new file mode 100644 index 0000000000..af2430ec55 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.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 CycleDetectionBruteForceUnitTest extends CycleDetectionTestBase { + boolean cycleExists; + Node head; + + public CycleDetectionBruteForceUnitTest(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 deleted file mode 100644 index 17d339bc33..0000000000 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsTest.java +++ /dev/null @@ -1,23 +0,0 @@ -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/CycleDetectionByFastAndSlowIteratorsUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.java new file mode 100644 index 0000000000..ce31c84067 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.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 CycleDetectionByFastAndSlowIteratorsUnitTest extends CycleDetectionTestBase { + boolean cycleExists; + Node head; + + public CycleDetectionByFastAndSlowIteratorsUnitTest(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 deleted file mode 100644 index 73a2cc7861..0000000000 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingTest.java +++ /dev/null @@ -1,23 +0,0 @@ -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/CycleDetectionByHashingUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.java new file mode 100644 index 0000000000..4451c3d3c9 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.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 CycleDetectionByHashingUnitTest extends CycleDetectionTestBase { + boolean cycleExists; + Node head; + + public CycleDetectionByHashingUnitTest(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/CycleRemovalBruteForceTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceTest.java deleted file mode 100644 index 6484c9988e..0000000000 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceTest.java +++ /dev/null @@ -1,24 +0,0 @@ -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/CycleRemovalBruteForceUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.java new file mode 100644 index 0000000000..f69e3c35ba --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.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 CycleRemovalBruteForceUnitTest extends CycleDetectionTestBase { + boolean cycleExists; + Node head; + + public CycleRemovalBruteForceUnitTest(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 deleted file mode 100644 index 7bfd89c502..0000000000 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesTest.java +++ /dev/null @@ -1,24 +0,0 @@ -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/CycleRemovalByCountingLoopNodesUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.java new file mode 100644 index 0000000000..c17aa6eeab --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.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 CycleRemovalByCountingLoopNodesUnitTest extends CycleDetectionTestBase { + boolean cycleExists; + Node head; + + public CycleRemovalByCountingLoopNodesUnitTest(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 deleted file mode 100644 index c77efb3e3e..0000000000 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesTest.java +++ /dev/null @@ -1,24 +0,0 @@ -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/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java new file mode 100644 index 0000000000..06ff840a59 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.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 CycleRemovalWithoutCountingLoopNodesUnitTest extends CycleDetectionTestBase { + boolean cycleExists; + Node head; + + public CycleRemovalWithoutCountingLoopNodesUnitTest(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/algorithms/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java new file mode 100644 index 0000000000..59afed65de --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.algorithms.mcts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.algorithms.mcts.montecarlo.MonteCarloTreeSearch; +import com.baeldung.algorithms.mcts.montecarlo.State; +import com.baeldung.algorithms.mcts.montecarlo.UCT; +import com.baeldung.algorithms.mcts.tictactoe.Board; +import com.baeldung.algorithms.mcts.tictactoe.Position; +import com.baeldung.algorithms.mcts.tree.Tree; + +public class MCTSUnitTest { + private Tree gameTree; + private MonteCarloTreeSearch mcts; + + @Before + public void initGameTree() { + gameTree = new Tree(); + mcts = new MonteCarloTreeSearch(); + } + + @Test + public void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() { + double uctValue = 15.79; + assertEquals(UCT.uctValue(600, 300, 20), uctValue, 0.01); + } + + @Test + public void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() { + State initState = gameTree.getRoot().getState(); + List possibleStates = initState.getAllPossibleStates(); + assertTrue(possibleStates.size() > 0); + } + + @Test + public void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() { + Board board = new Board(); + int initAvailablePositions = board.getEmptyPositions().size(); + board.performMove(Board.P1, new Position(1, 1)); + int availablePositions = board.getEmptyPositions().size(); + assertTrue(initAvailablePositions > availablePositions); + } + + @Test + public void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() { + Board board = new Board(); + + int player = Board.P1; + int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE; + for (int i = 0; i < totalMoves; i++) { + board = mcts.findNextMove(board, player); + if (board.checkStatus() != -1) { + break; + } + player = 3 - player; + } + int winStatus = board.checkStatus(); + assertEquals(winStatus, Board.DRAW); + } + + @Test + public void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() { + Board board = new Board(); + MonteCarloTreeSearch mcts1 = new MonteCarloTreeSearch(); + mcts1.setLevel(1); + MonteCarloTreeSearch mcts3 = new MonteCarloTreeSearch(); + mcts3.setLevel(3); + + int player = Board.P1; + int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE; + for (int i = 0; i < totalMoves; i++) { + if (player == Board.P1) + board = mcts3.findNextMove(board, player); + else + board = mcts1.findNextMove(board, player); + + if (board.checkStatus() != -1) { + break; + } + player = 3 - player; + } + int winStatus = board.checkStatus(); + assertTrue(winStatus == Board.DRAW || winStatus == Board.P1); + } + +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java new file mode 100644 index 0000000000..59f0fcf053 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.algorithms.minimax; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; +import com.baeldung.algorithms.minimax.MiniMax; +import com.baeldung.algorithms.minimax.Tree; + +public class MinimaxUnitTest { + private Tree gameTree; + private MiniMax miniMax; + + @Before + public void initMiniMaxUtility() { + miniMax = new MiniMax(); + } + + @Test + public void givenMiniMax_whenConstructTree_thenNotNullTree() { + assertNull(gameTree); + miniMax.constructTree(6); + gameTree = miniMax.getTree(); + assertNotNull(gameTree); + } + + @Test + public void givenMiniMax_whenCheckWin_thenComputeOptimal() { + miniMax.constructTree(6); + boolean result = miniMax.checkWin(); + assertTrue(result); + miniMax.constructTree(8); + result = miniMax.checkWin(); + assertFalse(result); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterTest.java b/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterTest.java deleted file mode 100644 index a4a169f158..0000000000 --- a/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterTest.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.baeldung.algorithms.moneywords; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -import com.baeldung.algorithms.numberwordconverter.NumberWordConverter; - -public class NumberWordConverterTest { - - @Test - public void whenMoneyNegative_thenReturnInvalidInput() { - assertEquals(NumberWordConverter.INVALID_INPUT_GIVEN, NumberWordConverter.getMoneyIntoWords(-13)); - } - - @Test - public void whenZeroDollarsGiven_thenReturnEmptyString() { - assertEquals("", NumberWordConverter.getMoneyIntoWords(0)); - } - - @Test - public void whenOnlyDollarsGiven_thenReturnWords() { - assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1)); - } - - @Test - public void whenOnlyCentsGiven_thenReturnWords() { - assertEquals("sixty cents", NumberWordConverter.getMoneyIntoWords(0.6)); - } - - @Test - public void whenAlmostAMillioDollarsGiven_thenReturnWords() { - String expectedResult = "nine hundred ninety nine thousand nine hundred ninety nine dollars"; - assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(999_999)); - } - - @Test - public void whenThirtyMillionDollarsGiven_thenReturnWords() { - String expectedResult = "thirty three million three hundred forty eight thousand nine hundred seventy eight dollars"; - assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(33_348_978)); - } - - @Test - public void whenTwoBillionDollarsGiven_thenReturnWords() { - String expectedResult = "two billion one hundred thirty three million two hundred forty seven thousand eight hundred ten dollars"; - assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(2_133_247_810)); - } - - @Test - public void whenGivenDollarsAndCents_thenReturnWords() { - String expectedResult = "nine hundred twenty four dollars and sixty cents"; - assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(924.6)); - } - - @Test - public void whenOneDollarAndNoCents_thenReturnDollarSingular() { - assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1)); - } - - @Test - public void whenNoDollarsAndOneCent_thenReturnCentSingular() { - assertEquals("one cent", NumberWordConverter.getMoneyIntoWords(0.01)); - } - - @Test - public void whenNoDollarsAndTwoCents_thenReturnCentsPlural() { - assertEquals("two cents", NumberWordConverter.getMoneyIntoWords(0.02)); - } - - @Test - public void whenNoDollarsAndNinetyNineCents_thenReturnWords() { - assertEquals("ninety nine cents", NumberWordConverter.getMoneyIntoWords(0.99)); - } - - @Test - public void whenNoDollarsAndNineFiveNineCents_thenCorrectRounding() { - assertEquals("ninety six cents", NumberWordConverter.getMoneyIntoWords(0.959)); - } - - @Test - public void whenGivenDollarsAndCents_thenReturnWordsVersionTwo() { - assertEquals("three hundred ten £ 00/100", NumberWordConverter.getMoneyIntoWords("310")); - } -} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterUnitTest.java new file mode 100644 index 0000000000..26643e9c1e --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterUnitTest.java @@ -0,0 +1,84 @@ +package com.baeldung.algorithms.moneywords; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.algorithms.numberwordconverter.NumberWordConverter; + +public class NumberWordConverterUnitTest { + + @Test + public void whenMoneyNegative_thenReturnInvalidInput() { + assertEquals(NumberWordConverter.INVALID_INPUT_GIVEN, NumberWordConverter.getMoneyIntoWords(-13)); + } + + @Test + public void whenZeroDollarsGiven_thenReturnEmptyString() { + assertEquals("", NumberWordConverter.getMoneyIntoWords(0)); + } + + @Test + public void whenOnlyDollarsGiven_thenReturnWords() { + assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1)); + } + + @Test + public void whenOnlyCentsGiven_thenReturnWords() { + assertEquals("sixty cents", NumberWordConverter.getMoneyIntoWords(0.6)); + } + + @Test + public void whenAlmostAMillioDollarsGiven_thenReturnWords() { + String expectedResult = "nine hundred ninety nine thousand nine hundred ninety nine dollars"; + assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(999_999)); + } + + @Test + public void whenThirtyMillionDollarsGiven_thenReturnWords() { + String expectedResult = "thirty three million three hundred forty eight thousand nine hundred seventy eight dollars"; + assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(33_348_978)); + } + + @Test + public void whenTwoBillionDollarsGiven_thenReturnWords() { + String expectedResult = "two billion one hundred thirty three million two hundred forty seven thousand eight hundred ten dollars"; + assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(2_133_247_810)); + } + + @Test + public void whenGivenDollarsAndCents_thenReturnWords() { + String expectedResult = "nine hundred twenty four dollars and sixty cents"; + assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(924.6)); + } + + @Test + public void whenOneDollarAndNoCents_thenReturnDollarSingular() { + assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1)); + } + + @Test + public void whenNoDollarsAndOneCent_thenReturnCentSingular() { + assertEquals("one cent", NumberWordConverter.getMoneyIntoWords(0.01)); + } + + @Test + public void whenNoDollarsAndTwoCents_thenReturnCentsPlural() { + assertEquals("two cents", NumberWordConverter.getMoneyIntoWords(0.02)); + } + + @Test + public void whenNoDollarsAndNinetyNineCents_thenReturnWords() { + assertEquals("ninety nine cents", NumberWordConverter.getMoneyIntoWords(0.99)); + } + + @Test + public void whenNoDollarsAndNineFiveNineCents_thenCorrectRounding() { + assertEquals("ninety six cents", NumberWordConverter.getMoneyIntoWords(0.959)); + } + + @Test + public void whenGivenDollarsAndCents_thenReturnWordsVersionTwo() { + assertEquals("three hundred ten £ 00/100", NumberWordConverter.getMoneyIntoWords("310")); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java b/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java deleted file mode 100644 index 4995e938b7..0000000000 --- a/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.algorithms.prime; - -import static com.baeldung.algorithms.prime.PrimeGenerator.*; - -import java.util.Arrays; -import java.util.List; -import org.junit.Test; -import static org.junit.Assert.*; - -public class PrimeGeneratorTest { - @Test - public void whenBruteForced_returnsSuccessfully() { - final List primeNumbers = primeNumbersBruteForce(20); - assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); - } - - @Test - public void whenOptimized_returnsSuccessfully() { - final List primeNumbers = primeNumbersTill(20); - assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); - } - - @Test - public void whenSieveOfEratosthenes_returnsSuccessfully() { - final List primeNumbers = sieveOfEratosthenes(20); - assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); - } -} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java new file mode 100644 index 0000000000..6707b34477 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.algorithms.rectanglesoverlap; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; +import org.junit.Test; + +import com.baeldung.algorithms.rectanglesoverlap.Point; +import com.baeldung.algorithms.rectanglesoverlap.Rectangle; + +public class RectangleUnitTest { + + @Test + public void givenTwoOverlappingRectangles_whenisOverlappingCalled_shouldReturnTrue() { + Rectangle rectangle1 = new Rectangle(new Point(2, 1), new Point(4, 3)); + Rectangle rectangle2 = new Rectangle(new Point(1, 1), new Point(6, 4)); + assertTrue(rectangle1.isOverlapping(rectangle2)); + + rectangle1 = new Rectangle(new Point(-5, -2), new Point(2, 3)); + rectangle2 = new Rectangle(new Point(-2, -1), new Point(5, 2)); + assertTrue(rectangle1.isOverlapping(rectangle2)); + + rectangle1 = new Rectangle(new Point(-5, 1), new Point(2, 4)); + rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, 5)); + assertTrue(rectangle1.isOverlapping(rectangle2)); + } + + @Test + public void givenTwoNonOverlappingRectangles_whenisOverlappingCalled_shouldReturnFalse() { + Rectangle rectangle1 = new Rectangle(new Point(-5, 1), new Point(-3, 4)); + Rectangle rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, 5)); + assertFalse(rectangle1.isOverlapping(rectangle2)); + + rectangle1 = new Rectangle(new Point(-5, 1), new Point(3, 4)); + rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, -1)); + assertFalse(rectangle1.isOverlapping(rectangle2)); + + rectangle1 = new Rectangle(new Point(-2, 1), new Point(0, 3)); + rectangle2 = new Rectangle(new Point(3, 1), new Point(5, 4)); + assertFalse(rectangle1.isOverlapping(rectangle2)); + } + +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/romannumerals/RomanArabicConverterUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/romannumerals/RomanArabicConverterUnitTest.java new file mode 100644 index 0000000000..b289ec6bc9 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/romannumerals/RomanArabicConverterUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.algorithms.romannumerals; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class RomanArabicConverterUnitTest { + + @Test + public void given2018Roman_WhenConvertingToArabic_ThenReturn2018() { + + String roman2018 = "MMXVIII"; + + int result = RomanArabicConverter.romanToArabic(roman2018); + + assertThat(result).isEqualTo(2018); + } + + @Test + public void given1999Arabic_WhenConvertingToRoman_ThenReturnMCMXCIX() { + + int arabic1999 = 1999; + + String result = RomanArabicConverter.arabicToRoman(arabic1999); + + assertThat(result).isEqualTo("MCMXCIX"); + } + +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java new file mode 100644 index 0000000000..54863cddc8 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.algorithms.string; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class EnglishAlphabetLettersUnitTest { + + @Test + void givenString_whenContainsAllCharacter_thenTrue() { + String input = "Farmer jack realized that big yellow quilts were expensive"; + Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllTheLetters(input)); + } + + @Test + void givenString_whenContainsAllCharacter_thenUsingStreamExpectTrue() { + String input = "Farmer jack realized that big yellow quilts were expensive"; + Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllLetterUsingStream(input)); + } + +} diff --git a/algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java b/algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java deleted file mode 100644 index c085d54689..0000000000 --- a/algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.jgrapht; - -import static org.junit.Assert.assertEquals; - -import java.util.List; - -import org.jgrapht.VertexFactory; -import org.jgrapht.alg.HamiltonianCycle; -import org.jgrapht.generate.CompleteGraphGenerator; -import org.jgrapht.graph.DefaultEdge; -import org.jgrapht.graph.SimpleWeightedGraph; -import org.junit.Before; -import org.junit.Test; - -public class CompleteGraphTest { - - static SimpleWeightedGraph completeGraph; - static int size = 10; - - @Before - public void createCompleteGraph() { - completeGraph = new SimpleWeightedGraph<>(DefaultEdge.class); - CompleteGraphGenerator completeGenerator = new CompleteGraphGenerator(size); - VertexFactory vFactory = new VertexFactory() { - private int id = 0; - public String createVertex() { - return "v" + id++; - } - }; - completeGenerator.generateGraph(completeGraph, vFactory, null); - } - - @Test - public void givenCompleteGraph_whenGetHamiltonianCyclePath_thenGetVerticeListInSequence() { - List verticeList = HamiltonianCycle.getApproximateOptimalForCompleteGraph(completeGraph); - assertEquals(verticeList.size(), completeGraph.vertexSet().size()); - } -} diff --git a/algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphUnitTest.java b/algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphUnitTest.java new file mode 100644 index 0000000000..0b0d6ae822 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.jgrapht; + +import static org.junit.Assert.assertEquals; + +import java.util.List; + +import org.jgrapht.VertexFactory; +import org.jgrapht.alg.HamiltonianCycle; +import org.jgrapht.generate.CompleteGraphGenerator; +import org.jgrapht.graph.DefaultEdge; +import org.jgrapht.graph.SimpleWeightedGraph; +import org.junit.Before; +import org.junit.Test; + +public class CompleteGraphUnitTest { + + static SimpleWeightedGraph completeGraph; + static int size = 10; + + @Before + public void createCompleteGraph() { + completeGraph = new SimpleWeightedGraph<>(DefaultEdge.class); + CompleteGraphGenerator completeGenerator = new CompleteGraphGenerator(size); + VertexFactory vFactory = new VertexFactory() { + private int id = 0; + public String createVertex() { + return "v" + id++; + } + }; + completeGenerator.generateGraph(completeGraph, vFactory, null); + } + + @Test + public void givenCompleteGraph_whenGetHamiltonianCyclePath_thenGetVerticeListInSequence() { + List verticeList = HamiltonianCycle.getApproximateOptimalForCompleteGraph(completeGraph); + assertEquals(verticeList.size(), completeGraph.vertexSet().size()); + } +} diff --git a/algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java b/algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java deleted file mode 100644 index 7f4cc99715..0000000000 --- a/algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.baeldung.jgrapht; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.stream.IntStream; - -import org.jgrapht.DirectedGraph; -import org.jgrapht.GraphPath; -import org.jgrapht.alg.CycleDetector; -import org.jgrapht.alg.KosarajuStrongConnectivityInspector; -import org.jgrapht.alg.interfaces.StrongConnectivityAlgorithm; -import org.jgrapht.alg.shortestpath.AllDirectedPaths; -import org.jgrapht.alg.shortestpath.BellmanFordShortestPath; -import org.jgrapht.alg.shortestpath.DijkstraShortestPath; -import org.jgrapht.graph.DefaultDirectedGraph; -import org.jgrapht.graph.DefaultEdge; -import org.jgrapht.graph.DirectedSubgraph; -import org.jgrapht.traverse.BreadthFirstIterator; -import org.jgrapht.traverse.DepthFirstIterator; -import org.junit.Before; -import org.junit.Test; - -public class DirectedGraphTests { - DirectedGraph directedGraph; - - @Before - public void createDirectedGraph() { - directedGraph = new DefaultDirectedGraph(DefaultEdge.class); - IntStream.range(1, 10).forEach(i -> { - directedGraph.addVertex("v" + i); - }); - directedGraph.addEdge("v1", "v2"); - directedGraph.addEdge("v2", "v4"); - directedGraph.addEdge("v4", "v3"); - directedGraph.addEdge("v3", "v1"); - directedGraph.addEdge("v5", "v4"); - directedGraph.addEdge("v5", "v6"); - directedGraph.addEdge("v6", "v7"); - directedGraph.addEdge("v7", "v5"); - directedGraph.addEdge("v8", "v5"); - directedGraph.addEdge("v9", "v8"); - } - - @Test - public void givenDirectedGraph_whenGetStronglyConnectedSubgraphs_thenPathExistsBetweenStronglyconnectedVertices() { - StrongConnectivityAlgorithm scAlg = new KosarajuStrongConnectivityInspector<>(directedGraph); - List> stronglyConnectedSubgraphs = scAlg.stronglyConnectedSubgraphs(); - List stronglyConnectedVertices = new ArrayList<>(stronglyConnectedSubgraphs.get(3).vertexSet()); - - String randomVertex1 = stronglyConnectedVertices.get(0); - String randomVertex2 = stronglyConnectedVertices.get(3); - AllDirectedPaths allDirectedPaths = new AllDirectedPaths<>(directedGraph); - - List> possiblePathList = allDirectedPaths.getAllPaths(randomVertex1, randomVertex2, false, stronglyConnectedVertices.size()); - assertTrue(possiblePathList.size() > 0); - } - - @Test - public void givenDirectedGraphWithCycle_whenCheckCycles_thenDetectCycles() { - CycleDetector cycleDetector = new CycleDetector(directedGraph); - assertTrue(cycleDetector.detectCycles()); - Set cycleVertices = cycleDetector.findCycles(); - assertTrue(cycleVertices.size() > 0); - } - - @Test - public void givenDirectedGraph_whenCreateInstanceDepthFirstIterator_thenGetIterator() { - DepthFirstIterator depthFirstIterator = new DepthFirstIterator<>(directedGraph); - assertNotNull(depthFirstIterator); - } - - @Test - public void givenDirectedGraph_whenCreateInstanceBreadthFirstIterator_thenGetIterator() { - BreadthFirstIterator breadthFirstIterator = new BreadthFirstIterator<>(directedGraph); - assertNotNull(breadthFirstIterator); - } - - @Test - public void givenDirectedGraph_whenGetDijkstraShortestPath_thenGetNotNullPath() { - DijkstraShortestPath dijkstraShortestPath = new DijkstraShortestPath(directedGraph); - List shortestPath = dijkstraShortestPath.getPath("v1", "v4").getVertexList(); - assertNotNull(shortestPath); - } - - @Test - public void givenDirectedGraph_whenGetBellmanFordShortestPath_thenGetNotNullPath() { - BellmanFordShortestPath bellmanFordShortestPath = new BellmanFordShortestPath(directedGraph); - List shortestPath = bellmanFordShortestPath.getPath("v1", "v4").getVertexList(); - assertNotNull(shortestPath); - } -} diff --git a/algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphUnitTest.java b/algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphUnitTest.java new file mode 100644 index 0000000000..3aebaf49a2 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphUnitTest.java @@ -0,0 +1,95 @@ +package com.baeldung.jgrapht; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.stream.IntStream; + +import org.jgrapht.DirectedGraph; +import org.jgrapht.GraphPath; +import org.jgrapht.alg.CycleDetector; +import org.jgrapht.alg.KosarajuStrongConnectivityInspector; +import org.jgrapht.alg.interfaces.StrongConnectivityAlgorithm; +import org.jgrapht.alg.shortestpath.AllDirectedPaths; +import org.jgrapht.alg.shortestpath.BellmanFordShortestPath; +import org.jgrapht.alg.shortestpath.DijkstraShortestPath; +import org.jgrapht.graph.DefaultDirectedGraph; +import org.jgrapht.graph.DefaultEdge; +import org.jgrapht.graph.DirectedSubgraph; +import org.jgrapht.traverse.BreadthFirstIterator; +import org.jgrapht.traverse.DepthFirstIterator; +import org.junit.Before; +import org.junit.Test; + +public class DirectedGraphUnitTest { + DirectedGraph directedGraph; + + @Before + public void createDirectedGraph() { + directedGraph = new DefaultDirectedGraph(DefaultEdge.class); + IntStream.range(1, 10).forEach(i -> { + directedGraph.addVertex("v" + i); + }); + directedGraph.addEdge("v1", "v2"); + directedGraph.addEdge("v2", "v4"); + directedGraph.addEdge("v4", "v3"); + directedGraph.addEdge("v3", "v1"); + directedGraph.addEdge("v5", "v4"); + directedGraph.addEdge("v5", "v6"); + directedGraph.addEdge("v6", "v7"); + directedGraph.addEdge("v7", "v5"); + directedGraph.addEdge("v8", "v5"); + directedGraph.addEdge("v9", "v8"); + } + + @Test + public void givenDirectedGraph_whenGetStronglyConnectedSubgraphs_thenPathExistsBetweenStronglyconnectedVertices() { + StrongConnectivityAlgorithm scAlg = new KosarajuStrongConnectivityInspector<>(directedGraph); + List> stronglyConnectedSubgraphs = scAlg.stronglyConnectedSubgraphs(); + List stronglyConnectedVertices = new ArrayList<>(stronglyConnectedSubgraphs.get(3).vertexSet()); + + String randomVertex1 = stronglyConnectedVertices.get(0); + String randomVertex2 = stronglyConnectedVertices.get(3); + AllDirectedPaths allDirectedPaths = new AllDirectedPaths<>(directedGraph); + + List> possiblePathList = allDirectedPaths.getAllPaths(randomVertex1, randomVertex2, false, stronglyConnectedVertices.size()); + assertTrue(possiblePathList.size() > 0); + } + + @Test + public void givenDirectedGraphWithCycle_whenCheckCycles_thenDetectCycles() { + CycleDetector cycleDetector = new CycleDetector(directedGraph); + assertTrue(cycleDetector.detectCycles()); + Set cycleVertices = cycleDetector.findCycles(); + assertTrue(cycleVertices.size() > 0); + } + + @Test + public void givenDirectedGraph_whenCreateInstanceDepthFirstIterator_thenGetIterator() { + DepthFirstIterator depthFirstIterator = new DepthFirstIterator<>(directedGraph); + assertNotNull(depthFirstIterator); + } + + @Test + public void givenDirectedGraph_whenCreateInstanceBreadthFirstIterator_thenGetIterator() { + BreadthFirstIterator breadthFirstIterator = new BreadthFirstIterator<>(directedGraph); + assertNotNull(breadthFirstIterator); + } + + @Test + public void givenDirectedGraph_whenGetDijkstraShortestPath_thenGetNotNullPath() { + DijkstraShortestPath dijkstraShortestPath = new DijkstraShortestPath(directedGraph); + List shortestPath = dijkstraShortestPath.getPath("v1", "v4").getVertexList(); + assertNotNull(shortestPath); + } + + @Test + public void givenDirectedGraph_whenGetBellmanFordShortestPath_thenGetNotNullPath() { + BellmanFordShortestPath bellmanFordShortestPath = new BellmanFordShortestPath(directedGraph); + List shortestPath = bellmanFordShortestPath.getPath("v1", "v4").getVertexList(); + assertNotNull(shortestPath); + } +} diff --git a/algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java b/algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java deleted file mode 100644 index 6f0fb92ab7..0000000000 --- a/algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.jgrapht; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.stream.IntStream; - -import org.jgrapht.GraphPath; -import org.jgrapht.alg.cycle.HierholzerEulerianCycle; -import org.jgrapht.graph.DefaultEdge; -import org.jgrapht.graph.SimpleWeightedGraph; -import org.junit.Before; -import org.junit.Test; - -public class EulerianCircuitTest { - SimpleWeightedGraph simpleGraph; - - @Before - public void createGraphWithEulerianCircuit() { - simpleGraph = new SimpleWeightedGraph<>(DefaultEdge.class); - IntStream.range(1, 6).forEach(i -> { - simpleGraph.addVertex("v" + i); - }); - IntStream.range(1, 6).forEach(i -> { - int endVertexNo = (i + 1) > 5 ? 1 : i + 1; - simpleGraph.addEdge("v" + i, "v" + endVertexNo); - }); - } - - @Test - public void givenGraph_whenCheckEluerianCycle_thenGetResult() { - HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>(); - assertTrue(eulerianCycle.isEulerian(simpleGraph)); - } - - @Test - public void givenGraphWithEulerianCircuit_whenGetEulerianCycle_thenGetGraphPath() { - HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>(); - GraphPath path = eulerianCycle.getEulerianCycle(simpleGraph); - assertTrue(path.getEdgeList().containsAll(simpleGraph.edgeSet())); - } -} diff --git a/algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitUnitTest.java b/algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitUnitTest.java new file mode 100644 index 0000000000..8cf1b70898 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.jgrapht; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.stream.IntStream; + +import org.jgrapht.GraphPath; +import org.jgrapht.alg.cycle.HierholzerEulerianCycle; +import org.jgrapht.graph.DefaultEdge; +import org.jgrapht.graph.SimpleWeightedGraph; +import org.junit.Before; +import org.junit.Test; + +public class EulerianCircuitUnitTest { + SimpleWeightedGraph simpleGraph; + + @Before + public void createGraphWithEulerianCircuit() { + simpleGraph = new SimpleWeightedGraph<>(DefaultEdge.class); + IntStream.range(1, 6).forEach(i -> { + simpleGraph.addVertex("v" + i); + }); + IntStream.range(1, 6).forEach(i -> { + int endVertexNo = (i + 1) > 5 ? 1 : i + 1; + simpleGraph.addEdge("v" + i, "v" + endVertexNo); + }); + } + + @Test + public void givenGraph_whenCheckEluerianCycle_thenGetResult() { + HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>(); + assertTrue(eulerianCycle.isEulerian(simpleGraph)); + } + + @Test + public void givenGraphWithEulerianCircuit_whenGetEulerianCycle_thenGetGraphPath() { + HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>(); + GraphPath path = eulerianCycle.getEulerianCycle(simpleGraph); + assertTrue(path.getEdgeList().containsAll(simpleGraph.edgeSet())); + } +} diff --git a/animal-sniffer-mvn-plugin/pom.xml b/animal-sniffer-mvn-plugin/pom.xml index ab7b38f6e0..cdfb1fb2a3 100644 --- a/animal-sniffer-mvn-plugin/pom.xml +++ b/animal-sniffer-mvn-plugin/pom.xml @@ -1,11 +1,11 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung animal-sniffer-mvn-plugin jar 1.0-SNAPSHOT - example-animal-sniffer-mvn-plugin + animal-sniffer-mvn-plugin http://maven.apache.org @@ -14,15 +14,6 @@ 1.0.0-SNAPSHOT - - - junit - junit - ${junit.version} - test - - - diff --git a/animal-sniffer-mvn-plugin/src/main/resources/logback.xml b/animal-sniffer-mvn-plugin/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/animal-sniffer-mvn-plugin/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/annotations/annotation-processing/pom.xml b/annotations/annotation-processing/pom.xml index 39a644905d..8e53334521 100644 --- a/annotations/annotation-processing/pom.xml +++ b/annotations/annotation-processing/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 annotation-processing diff --git a/annotations/annotation-processing/src/main/resources/logback.xml b/annotations/annotation-processing/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/annotations/annotation-processing/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/annotations/annotation-user/pom.xml b/annotations/annotation-user/pom.xml index 5a00951a18..07ea9a5b5a 100644 --- a/annotations/annotation-user/pom.xml +++ b/annotations/annotation-user/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 annotation-user diff --git a/annotations/annotation-user/src/main/resources/logback.xml b/annotations/annotation-user/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/annotations/annotation-user/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/annotations/pom.xml b/annotations/pom.xml index 52508e5bfc..2c73d3d91b 100644 --- a/annotations/pom.xml +++ b/annotations/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 annotations pom diff --git a/antlr/README.md b/antlr/README.md new file mode 100644 index 0000000000..419d9ddfbb --- /dev/null +++ b/antlr/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Java with ANTLR](http://www.baeldung.com/java-antlr) diff --git a/antlr/pom.xml b/antlr/pom.xml new file mode 100644 index 0000000000..ac66891598 --- /dev/null +++ b/antlr/pom.xml @@ -0,0 +1,58 @@ + + 4.0.0 + antlr + antlr + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + org.antlr + antlr4-maven-plugin + ${antlr.version} + + + + antlr4 + + + + + + org.codehaus.mojo + build-helper-maven-plugin + ${mojo.version} + + + generate-sources + + add-source + + + + ${basedir}/target/generated-sources/antlr4 + + + + + + + + + + org.antlr + antlr4-runtime + ${antlr.version} + + + + 4.7.1 + 3.0.0 + + \ No newline at end of file diff --git a/antlr/src/main/antlr4/com/baeldung/antlr/Java8.g4 b/antlr/src/main/antlr4/com/baeldung/antlr/Java8.g4 new file mode 100644 index 0000000000..5cde8f9ace --- /dev/null +++ b/antlr/src/main/antlr4/com/baeldung/antlr/Java8.g4 @@ -0,0 +1,1775 @@ +/* + * [The "BSD license"] + * Copyright (c) 2014 Terence Parr + * Copyright (c) 2014 Sam Harwell + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * A Java 8 grammar for ANTLR 4 derived from the Java Language Specification + * chapter 19. + * + * NOTE: This grammar results in a generated parser that is much slower + * than the Java 7 grammar in the grammars-v4/java directory. This + * one is, however, extremely close to the spec. + * + * You can test with + * + * $ antlr4 Java8.g4 + * $ javac *.java + * $ grun Java8 compilationUnit *.java + * + * Or, +~/antlr/code/grammars-v4/java8 $ java Test . +/Users/parrt/antlr/code/grammars-v4/java8/./Java8BaseListener.java +/Users/parrt/antlr/code/grammars-v4/java8/./Java8Lexer.java +/Users/parrt/antlr/code/grammars-v4/java8/./Java8Listener.java +/Users/parrt/antlr/code/grammars-v4/java8/./Java8Parser.java +/Users/parrt/antlr/code/grammars-v4/java8/./Test.java +Total lexer+parser dateTime 30844ms. + */ +grammar Java8; + +/* + * Productions from §3 (Lexical Structure) + */ + +literal + : IntegerLiteral + | FloatingPointLiteral + | BooleanLiteral + | CharacterLiteral + | StringLiteral + | NullLiteral + ; + +/* + * Productions from §4 (Types, Values, and Variables) + */ + +primitiveType + : annotation* numericType + | annotation* 'boolean' + ; + +numericType + : integralType + | floatingPointType + ; + +integralType + : 'byte' + | 'short' + | 'int' + | 'long' + | 'char' + ; + +floatingPointType + : 'float' + | 'double' + ; + +referenceType + : classOrInterfaceType + | typeVariable + | arrayType + ; + +classOrInterfaceType + : ( classType_lfno_classOrInterfaceType + | interfaceType_lfno_classOrInterfaceType + ) + ( classType_lf_classOrInterfaceType + | interfaceType_lf_classOrInterfaceType + )* + ; + +classType + : annotation* Identifier typeArguments? + | classOrInterfaceType '.' annotation* Identifier typeArguments? + ; + +classType_lf_classOrInterfaceType + : '.' annotation* Identifier typeArguments? + ; + +classType_lfno_classOrInterfaceType + : annotation* Identifier typeArguments? + ; + +interfaceType + : classType + ; + +interfaceType_lf_classOrInterfaceType + : classType_lf_classOrInterfaceType + ; + +interfaceType_lfno_classOrInterfaceType + : classType_lfno_classOrInterfaceType + ; + +typeVariable + : annotation* Identifier + ; + +arrayType + : primitiveType dims + | classOrInterfaceType dims + | typeVariable dims + ; + +dims + : annotation* '[' ']' (annotation* '[' ']')* + ; + +typeParameter + : typeParameterModifier* Identifier typeBound? + ; + +typeParameterModifier + : annotation + ; + +typeBound + : 'extends' typeVariable + | 'extends' classOrInterfaceType additionalBound* + ; + +additionalBound + : '&' interfaceType + ; + +typeArguments + : '<' typeArgumentList '>' + ; + +typeArgumentList + : typeArgument (',' typeArgument)* + ; + +typeArgument + : referenceType + | wildcard + ; + +wildcard + : annotation* '?' wildcardBounds? + ; + +wildcardBounds + : 'extends' referenceType + | 'super' referenceType + ; + +/* + * Productions from §6 (Names) + */ + +packageName + : Identifier + | packageName '.' Identifier + ; + +typeName + : Identifier + | packageOrTypeName '.' Identifier + ; + +packageOrTypeName + : Identifier + | packageOrTypeName '.' Identifier + ; + +expressionName + : Identifier + | ambiguousName '.' Identifier + ; + +methodName + : Identifier + ; + +ambiguousName + : Identifier + | ambiguousName '.' Identifier + ; + +/* + * Productions from §7 (Packages) + */ + +compilationUnit + : packageDeclaration? importDeclaration* typeDeclaration* EOF + ; + +packageDeclaration + : packageModifier* 'package' packageName ';' + ; + +packageModifier + : annotation + ; + +importDeclaration + : singleTypeImportDeclaration + | typeImportOnDemandDeclaration + | singleStaticImportDeclaration + | staticImportOnDemandDeclaration + ; + +singleTypeImportDeclaration + : 'import' typeName ';' + ; + +typeImportOnDemandDeclaration + : 'import' packageOrTypeName '.' '*' ';' + ; + +singleStaticImportDeclaration + : 'import' 'static' typeName '.' Identifier ';' + ; + +staticImportOnDemandDeclaration + : 'import' 'static' typeName '.' '*' ';' + ; + +typeDeclaration + : classDeclaration + | interfaceDeclaration + | ';' + ; + +/* + * Productions from §8 (Classes) + */ + +classDeclaration + : normalClassDeclaration + | enumDeclaration + ; + +normalClassDeclaration + : classModifier* 'class' Identifier typeParameters? superclass? superinterfaces? classBody + ; + +classModifier + : annotation + | 'public' + | 'protected' + | 'private' + | 'abstract' + | 'static' + | 'final' + | 'strictfp' + ; + +typeParameters + : '<' typeParameterList '>' + ; + +typeParameterList + : typeParameter (',' typeParameter)* + ; + +superclass + : 'extends' classType + ; + +superinterfaces + : 'implements' interfaceTypeList + ; + +interfaceTypeList + : interfaceType (',' interfaceType)* + ; + +classBody + : '{' classBodyDeclaration* '}' + ; + +classBodyDeclaration + : classMemberDeclaration + | instanceInitializer + | staticInitializer + | constructorDeclaration + ; + +classMemberDeclaration + : fieldDeclaration + | methodDeclaration + | classDeclaration + | interfaceDeclaration + | ';' + ; + +fieldDeclaration + : fieldModifier* unannType variableDeclaratorList ';' + ; + +fieldModifier + : annotation + | 'public' + | 'protected' + | 'private' + | 'static' + | 'final' + | 'transient' + | 'volatile' + ; + +variableDeclaratorList + : variableDeclarator (',' variableDeclarator)* + ; + +variableDeclarator + : variableDeclaratorId ('=' variableInitializer)? + ; + +variableDeclaratorId + : Identifier dims? + ; + +variableInitializer + : expression + | arrayInitializer + ; + +unannType + : unannPrimitiveType + | unannReferenceType + ; + +unannPrimitiveType + : numericType + | 'boolean' + ; + +unannReferenceType + : unannClassOrInterfaceType + | unannTypeVariable + | unannArrayType + ; + +unannClassOrInterfaceType + : ( unannClassType_lfno_unannClassOrInterfaceType + | unannInterfaceType_lfno_unannClassOrInterfaceType + ) + ( unannClassType_lf_unannClassOrInterfaceType + | unannInterfaceType_lf_unannClassOrInterfaceType + )* + ; + +unannClassType + : Identifier typeArguments? + | unannClassOrInterfaceType '.' annotation* Identifier typeArguments? + ; + +unannClassType_lf_unannClassOrInterfaceType + : '.' annotation* Identifier typeArguments? + ; + +unannClassType_lfno_unannClassOrInterfaceType + : Identifier typeArguments? + ; + +unannInterfaceType + : unannClassType + ; + +unannInterfaceType_lf_unannClassOrInterfaceType + : unannClassType_lf_unannClassOrInterfaceType + ; + +unannInterfaceType_lfno_unannClassOrInterfaceType + : unannClassType_lfno_unannClassOrInterfaceType + ; + +unannTypeVariable + : Identifier + ; + +unannArrayType + : unannPrimitiveType dims + | unannClassOrInterfaceType dims + | unannTypeVariable dims + ; + +methodDeclaration + : methodModifier* methodHeader methodBody + ; + +methodModifier + : annotation + | 'public' + | 'protected' + | 'private' + | 'abstract' + | 'static' + | 'final' + | 'synchronized' + | 'native' + | 'strictfp' + ; + +methodHeader + : result methodDeclarator throws_? + | typeParameters annotation* result methodDeclarator throws_? + ; + +result + : unannType + | 'void' + ; + +methodDeclarator + : Identifier '(' formalParameterList? ')' dims? + ; + +formalParameterList + : receiverParameter + | formalParameters ',' lastFormalParameter + | lastFormalParameter + ; + +formalParameters + : formalParameter (',' formalParameter)* + | receiverParameter (',' formalParameter)* + ; + +formalParameter + : variableModifier* unannType variableDeclaratorId + ; + +variableModifier + : annotation + | 'final' + ; + +lastFormalParameter + : variableModifier* unannType annotation* '...' variableDeclaratorId + | formalParameter + ; + +receiverParameter + : annotation* unannType (Identifier '.')? 'this' + ; + +throws_ + : 'throws' exceptionTypeList + ; + +exceptionTypeList + : exceptionType (',' exceptionType)* + ; + +exceptionType + : classType + | typeVariable + ; + +methodBody + : block + | ';' + ; + +instanceInitializer + : block + ; + +staticInitializer + : 'static' block + ; + +constructorDeclaration + : constructorModifier* constructorDeclarator throws_? constructorBody + ; + +constructorModifier + : annotation + | 'public' + | 'protected' + | 'private' + ; + +constructorDeclarator + : typeParameters? simpleTypeName '(' formalParameterList? ')' + ; + +simpleTypeName + : Identifier + ; + +constructorBody + : '{' explicitConstructorInvocation? blockStatements? '}' + ; + +explicitConstructorInvocation + : typeArguments? 'this' '(' argumentList? ')' ';' + | typeArguments? 'super' '(' argumentList? ')' ';' + | expressionName '.' typeArguments? 'super' '(' argumentList? ')' ';' + | primary '.' typeArguments? 'super' '(' argumentList? ')' ';' + ; + +enumDeclaration + : classModifier* 'enum' Identifier superinterfaces? enumBody + ; + +enumBody + : '{' enumConstantList? ','? enumBodyDeclarations? '}' + ; + +enumConstantList + : enumConstant (',' enumConstant)* + ; + +enumConstant + : enumConstantModifier* Identifier ('(' argumentList? ')')? classBody? + ; + +enumConstantModifier + : annotation + ; + +enumBodyDeclarations + : ';' classBodyDeclaration* + ; + +/* + * Productions from §9 (Interfaces) + */ + +interfaceDeclaration + : normalInterfaceDeclaration + | annotationTypeDeclaration + ; + +normalInterfaceDeclaration + : interfaceModifier* 'interface' Identifier typeParameters? extendsInterfaces? interfaceBody + ; + +interfaceModifier + : annotation + | 'public' + | 'protected' + | 'private' + | 'abstract' + | 'static' + | 'strictfp' + ; + +extendsInterfaces + : 'extends' interfaceTypeList + ; + +interfaceBody + : '{' interfaceMemberDeclaration* '}' + ; + +interfaceMemberDeclaration + : constantDeclaration + | interfaceMethodDeclaration + | classDeclaration + | interfaceDeclaration + | ';' + ; + +constantDeclaration + : constantModifier* unannType variableDeclaratorList ';' + ; + +constantModifier + : annotation + | 'public' + | 'static' + | 'final' + ; + +interfaceMethodDeclaration + : interfaceMethodModifier* methodHeader methodBody + ; + +interfaceMethodModifier + : annotation + | 'public' + | 'abstract' + | 'default' + | 'static' + | 'strictfp' + ; + +annotationTypeDeclaration + : interfaceModifier* '@' 'interface' Identifier annotationTypeBody + ; + +annotationTypeBody + : '{' annotationTypeMemberDeclaration* '}' + ; + +annotationTypeMemberDeclaration + : annotationTypeElementDeclaration + | constantDeclaration + | classDeclaration + | interfaceDeclaration + | ';' + ; + +annotationTypeElementDeclaration + : annotationTypeElementModifier* unannType Identifier '(' ')' dims? defaultValue? ';' + ; + +annotationTypeElementModifier + : annotation + | 'public' + | 'abstract' + ; + +defaultValue + : 'default' elementValue + ; + +annotation + : normalAnnotation + | markerAnnotation + | singleElementAnnotation + ; + +normalAnnotation + : '@' typeName '(' elementValuePairList? ')' + ; + +elementValuePairList + : elementValuePair (',' elementValuePair)* + ; + +elementValuePair + : Identifier '=' elementValue + ; + +elementValue + : conditionalExpression + | elementValueArrayInitializer + | annotation + ; + +elementValueArrayInitializer + : '{' elementValueList? ','? '}' + ; + +elementValueList + : elementValue (',' elementValue)* + ; + +markerAnnotation + : '@' typeName + ; + +singleElementAnnotation + : '@' typeName '(' elementValue ')' + ; + +/* + * Productions from §10 (Arrays) + */ + +arrayInitializer + : '{' variableInitializerList? ','? '}' + ; + +variableInitializerList + : variableInitializer (',' variableInitializer)* + ; + +/* + * Productions from §14 (Blocks and Statements) + */ + +block + : '{' blockStatements? '}' + ; + +blockStatements + : blockStatement+ + ; + +blockStatement + : localVariableDeclarationStatement + | classDeclaration + | statement + ; + +localVariableDeclarationStatement + : localVariableDeclaration ';' + ; + +localVariableDeclaration + : variableModifier* unannType variableDeclaratorList + ; + +statement + : statementWithoutTrailingSubstatement + | labeledStatement + | ifThenStatement + | ifThenElseStatement + | whileStatement + | forStatement + ; + +statementNoShortIf + : statementWithoutTrailingSubstatement + | labeledStatementNoShortIf + | ifThenElseStatementNoShortIf + | whileStatementNoShortIf + | forStatementNoShortIf + ; + +statementWithoutTrailingSubstatement + : block + | emptyStatement + | expressionStatement + | assertStatement + | switchStatement + | doStatement + | breakStatement + | continueStatement + | returnStatement + | synchronizedStatement + | throwStatement + | tryStatement + ; + +emptyStatement + : ';' + ; + +labeledStatement + : Identifier ':' statement + ; + +labeledStatementNoShortIf + : Identifier ':' statementNoShortIf + ; + +expressionStatement + : statementExpression ';' + ; + +statementExpression + : assignment + | preIncrementExpression + | preDecrementExpression + | postIncrementExpression + | postDecrementExpression + | methodInvocation + | classInstanceCreationExpression + ; + +ifThenStatement + : 'if' '(' expression ')' statement + ; + +ifThenElseStatement + : 'if' '(' expression ')' statementNoShortIf 'else' statement + ; + +ifThenElseStatementNoShortIf + : 'if' '(' expression ')' statementNoShortIf 'else' statementNoShortIf + ; + +assertStatement + : 'assert' expression ';' + | 'assert' expression ':' expression ';' + ; + +switchStatement + : 'switch' '(' expression ')' switchBlock + ; + +switchBlock + : '{' switchBlockStatementGroup* switchLabel* '}' + ; + +switchBlockStatementGroup + : switchLabels blockStatements + ; + +switchLabels + : switchLabel switchLabel* + ; + +switchLabel + : 'case' constantExpression ':' + | 'case' enumConstantName ':' + | 'default' ':' + ; + +enumConstantName + : Identifier + ; + +whileStatement + : 'while' '(' expression ')' statement + ; + +whileStatementNoShortIf + : 'while' '(' expression ')' statementNoShortIf + ; + +doStatement + : 'do' statement 'while' '(' expression ')' ';' + ; + +forStatement + : basicForStatement + | enhancedForStatement + ; + +forStatementNoShortIf + : basicForStatementNoShortIf + | enhancedForStatementNoShortIf + ; + +basicForStatement + : 'for' '(' forInit? ';' expression? ';' forUpdate? ')' statement + ; + +basicForStatementNoShortIf + : 'for' '(' forInit? ';' expression? ';' forUpdate? ')' statementNoShortIf + ; + +forInit + : statementExpressionList + | localVariableDeclaration + ; + +forUpdate + : statementExpressionList + ; + +statementExpressionList + : statementExpression (',' statementExpression)* + ; + +enhancedForStatement + : 'for' '(' variableModifier* unannType variableDeclaratorId ':' expression ')' statement + ; + +enhancedForStatementNoShortIf + : 'for' '(' variableModifier* unannType variableDeclaratorId ':' expression ')' statementNoShortIf + ; + +breakStatement + : 'break' Identifier? ';' + ; + +continueStatement + : 'continue' Identifier? ';' + ; + +returnStatement + : 'return' expression? ';' + ; + +throwStatement + : 'throw' expression ';' + ; + +synchronizedStatement + : 'synchronized' '(' expression ')' block + ; + +tryStatement + : 'try' block catches + | 'try' block catches? finally_ + | tryWithResourcesStatement + ; + +catches + : catchClause catchClause* + ; + +catchClause + : 'catch' '(' catchFormalParameter ')' block + ; + +catchFormalParameter + : variableModifier* catchType variableDeclaratorId + ; + +catchType + : unannClassType ('|' classType)* + ; + +finally_ + : 'finally' block + ; + +tryWithResourcesStatement + : 'try' resourceSpecification block catches? finally_? + ; + +resourceSpecification + : '(' resourceList ';'? ')' + ; + +resourceList + : resource (';' resource)* + ; + +resource + : variableModifier* unannType variableDeclaratorId '=' expression + ; + +/* + * Productions from §15 (Expressions) + */ + +primary + : ( primaryNoNewArray_lfno_primary + | arrayCreationExpression + ) + ( primaryNoNewArray_lf_primary + )* + ; + +primaryNoNewArray + : literal + | typeName ('[' ']')* '.' 'class' + | 'void' '.' 'class' + | 'this' + | typeName '.' 'this' + | '(' expression ')' + | classInstanceCreationExpression + | fieldAccess + | arrayAccess + | methodInvocation + | methodReference + ; + +primaryNoNewArray_lf_arrayAccess + : + ; + +primaryNoNewArray_lfno_arrayAccess + : literal + | typeName ('[' ']')* '.' 'class' + | 'void' '.' 'class' + | 'this' + | typeName '.' 'this' + | '(' expression ')' + | classInstanceCreationExpression + | fieldAccess + | methodInvocation + | methodReference + ; + +primaryNoNewArray_lf_primary + : classInstanceCreationExpression_lf_primary + | fieldAccess_lf_primary + | arrayAccess_lf_primary + | methodInvocation_lf_primary + | methodReference_lf_primary + ; + +primaryNoNewArray_lf_primary_lf_arrayAccess_lf_primary + : + ; + +primaryNoNewArray_lf_primary_lfno_arrayAccess_lf_primary + : classInstanceCreationExpression_lf_primary + | fieldAccess_lf_primary + | methodInvocation_lf_primary + | methodReference_lf_primary + ; + +primaryNoNewArray_lfno_primary + : literal + | typeName ('[' ']')* '.' 'class' + | unannPrimitiveType ('[' ']')* '.' 'class' + | 'void' '.' 'class' + | 'this' + | typeName '.' 'this' + | '(' expression ')' + | classInstanceCreationExpression_lfno_primary + | fieldAccess_lfno_primary + | arrayAccess_lfno_primary + | methodInvocation_lfno_primary + | methodReference_lfno_primary + ; + +primaryNoNewArray_lfno_primary_lf_arrayAccess_lfno_primary + : + ; + +primaryNoNewArray_lfno_primary_lfno_arrayAccess_lfno_primary + : literal + | typeName ('[' ']')* '.' 'class' + | unannPrimitiveType ('[' ']')* '.' 'class' + | 'void' '.' 'class' + | 'this' + | typeName '.' 'this' + | '(' expression ')' + | classInstanceCreationExpression_lfno_primary + | fieldAccess_lfno_primary + | methodInvocation_lfno_primary + | methodReference_lfno_primary + ; + +classInstanceCreationExpression + : 'new' typeArguments? annotation* Identifier ('.' annotation* Identifier)* typeArgumentsOrDiamond? '(' argumentList? ')' classBody? + | expressionName '.' 'new' typeArguments? annotation* Identifier typeArgumentsOrDiamond? '(' argumentList? ')' classBody? + | primary '.' 'new' typeArguments? annotation* Identifier typeArgumentsOrDiamond? '(' argumentList? ')' classBody? + ; + +classInstanceCreationExpression_lf_primary + : '.' 'new' typeArguments? annotation* Identifier typeArgumentsOrDiamond? '(' argumentList? ')' classBody? + ; + +classInstanceCreationExpression_lfno_primary + : 'new' typeArguments? annotation* Identifier ('.' annotation* Identifier)* typeArgumentsOrDiamond? '(' argumentList? ')' classBody? + | expressionName '.' 'new' typeArguments? annotation* Identifier typeArgumentsOrDiamond? '(' argumentList? ')' classBody? + ; + +typeArgumentsOrDiamond + : typeArguments + | '<' '>' + ; + +fieldAccess + : primary '.' Identifier + | 'super' '.' Identifier + | typeName '.' 'super' '.' Identifier + ; + +fieldAccess_lf_primary + : '.' Identifier + ; + +fieldAccess_lfno_primary + : 'super' '.' Identifier + | typeName '.' 'super' '.' Identifier + ; + +arrayAccess + : ( expressionName '[' expression ']' + | primaryNoNewArray_lfno_arrayAccess '[' expression ']' + ) + ( primaryNoNewArray_lf_arrayAccess '[' expression ']' + )* + ; + +arrayAccess_lf_primary + : ( primaryNoNewArray_lf_primary_lfno_arrayAccess_lf_primary '[' expression ']' + ) + ( primaryNoNewArray_lf_primary_lf_arrayAccess_lf_primary '[' expression ']' + )* + ; + +arrayAccess_lfno_primary + : ( expressionName '[' expression ']' + | primaryNoNewArray_lfno_primary_lfno_arrayAccess_lfno_primary '[' expression ']' + ) + ( primaryNoNewArray_lfno_primary_lf_arrayAccess_lfno_primary '[' expression ']' + )* + ; + +methodInvocation + : methodName '(' argumentList? ')' + | typeName '.' typeArguments? Identifier '(' argumentList? ')' + | expressionName '.' typeArguments? Identifier '(' argumentList? ')' + | primary '.' typeArguments? Identifier '(' argumentList? ')' + | 'super' '.' typeArguments? Identifier '(' argumentList? ')' + | typeName '.' 'super' '.' typeArguments? Identifier '(' argumentList? ')' + ; + +methodInvocation_lf_primary + : '.' typeArguments? Identifier '(' argumentList? ')' + ; + +methodInvocation_lfno_primary + : methodName '(' argumentList? ')' + | typeName '.' typeArguments? Identifier '(' argumentList? ')' + | expressionName '.' typeArguments? Identifier '(' argumentList? ')' + | 'super' '.' typeArguments? Identifier '(' argumentList? ')' + | typeName '.' 'super' '.' typeArguments? Identifier '(' argumentList? ')' + ; + +argumentList + : expression (',' expression)* + ; + +methodReference + : expressionName '::' typeArguments? Identifier + | referenceType '::' typeArguments? Identifier + | primary '::' typeArguments? Identifier + | 'super' '::' typeArguments? Identifier + | typeName '.' 'super' '::' typeArguments? Identifier + | classType '::' typeArguments? 'new' + | arrayType '::' 'new' + ; + +methodReference_lf_primary + : '::' typeArguments? Identifier + ; + +methodReference_lfno_primary + : expressionName '::' typeArguments? Identifier + | referenceType '::' typeArguments? Identifier + | 'super' '::' typeArguments? Identifier + | typeName '.' 'super' '::' typeArguments? Identifier + | classType '::' typeArguments? 'new' + | arrayType '::' 'new' + ; + +arrayCreationExpression + : 'new' primitiveType dimExprs dims? + | 'new' classOrInterfaceType dimExprs dims? + | 'new' primitiveType dims arrayInitializer + | 'new' classOrInterfaceType dims arrayInitializer + ; + +dimExprs + : dimExpr dimExpr* + ; + +dimExpr + : annotation* '[' expression ']' + ; + +constantExpression + : expression + ; + +expression + : lambdaExpression + | assignmentExpression + ; + +lambdaExpression + : lambdaParameters '->' lambdaBody + ; + +lambdaParameters + : Identifier + | '(' formalParameterList? ')' + | '(' inferredFormalParameterList ')' + ; + +inferredFormalParameterList + : Identifier (',' Identifier)* + ; + +lambdaBody + : expression + | block + ; + +assignmentExpression + : conditionalExpression + | assignment + ; + +assignment + : leftHandSide assignmentOperator expression + ; + +leftHandSide + : expressionName + | fieldAccess + | arrayAccess + ; + +assignmentOperator + : '=' + | '*=' + | '/=' + | '%=' + | '+=' + | '-=' + | '<<=' + | '>>=' + | '>>>=' + | '&=' + | '^=' + | '|=' + ; + +conditionalExpression + : conditionalOrExpression + | conditionalOrExpression '?' expression ':' conditionalExpression + ; + +conditionalOrExpression + : conditionalAndExpression + | conditionalOrExpression '||' conditionalAndExpression + ; + +conditionalAndExpression + : inclusiveOrExpression + | conditionalAndExpression '&&' inclusiveOrExpression + ; + +inclusiveOrExpression + : exclusiveOrExpression + | inclusiveOrExpression '|' exclusiveOrExpression + ; + +exclusiveOrExpression + : andExpression + | exclusiveOrExpression '^' andExpression + ; + +andExpression + : equalityExpression + | andExpression '&' equalityExpression + ; + +equalityExpression + : relationalExpression + | equalityExpression '==' relationalExpression + | equalityExpression '!=' relationalExpression + ; + +relationalExpression + : shiftExpression + | relationalExpression '<' shiftExpression + | relationalExpression '>' shiftExpression + | relationalExpression '<=' shiftExpression + | relationalExpression '>=' shiftExpression + | relationalExpression 'instanceof' referenceType + ; + +shiftExpression + : additiveExpression + | shiftExpression '<' '<' additiveExpression + | shiftExpression '>' '>' additiveExpression + | shiftExpression '>' '>' '>' additiveExpression + ; + +additiveExpression + : multiplicativeExpression + | additiveExpression '+' multiplicativeExpression + | additiveExpression '-' multiplicativeExpression + ; + +multiplicativeExpression + : unaryExpression + | multiplicativeExpression '*' unaryExpression + | multiplicativeExpression '/' unaryExpression + | multiplicativeExpression '%' unaryExpression + ; + +unaryExpression + : preIncrementExpression + | preDecrementExpression + | '+' unaryExpression + | '-' unaryExpression + | unaryExpressionNotPlusMinus + ; + +preIncrementExpression + : '++' unaryExpression + ; + +preDecrementExpression + : '--' unaryExpression + ; + +unaryExpressionNotPlusMinus + : postfixExpression + | '~' unaryExpression + | '!' unaryExpression + | castExpression + ; + +postfixExpression + : ( primary + | expressionName + ) + ( postIncrementExpression_lf_postfixExpression + | postDecrementExpression_lf_postfixExpression + )* + ; + +postIncrementExpression + : postfixExpression '++' + ; + +postIncrementExpression_lf_postfixExpression + : '++' + ; + +postDecrementExpression + : postfixExpression '--' + ; + +postDecrementExpression_lf_postfixExpression + : '--' + ; + +castExpression + : '(' primitiveType ')' unaryExpression + | '(' referenceType additionalBound* ')' unaryExpressionNotPlusMinus + | '(' referenceType additionalBound* ')' lambdaExpression + ; + +// LEXER + +// §3.9 Keywords + +ABSTRACT : 'abstract'; +ASSERT : 'assert'; +BOOLEAN : 'boolean'; +BREAK : 'break'; +BYTE : 'byte'; +CASE : 'case'; +CATCH : 'catch'; +CHAR : 'char'; +CLASS : 'class'; +CONST : 'const'; +CONTINUE : 'continue'; +DEFAULT : 'default'; +DO : 'do'; +DOUBLE : 'double'; +ELSE : 'else'; +ENUM : 'enum'; +EXTENDS : 'extends'; +FINAL : 'final'; +FINALLY : 'finally'; +FLOAT : 'float'; +FOR : 'for'; +IF : 'if'; +GOTO : 'goto'; +IMPLEMENTS : 'implements'; +IMPORT : 'import'; +INSTANCEOF : 'instanceof'; +INT : 'int'; +INTERFACE : 'interface'; +LONG : 'long'; +NATIVE : 'native'; +NEW : 'new'; +PACKAGE : 'package'; +PRIVATE : 'private'; +PROTECTED : 'protected'; +PUBLIC : 'public'; +RETURN : 'return'; +SHORT : 'short'; +STATIC : 'static'; +STRICTFP : 'strictfp'; +SUPER : 'super'; +SWITCH : 'switch'; +SYNCHRONIZED : 'synchronized'; +THIS : 'this'; +THROW : 'throw'; +THROWS : 'throws'; +TRANSIENT : 'transient'; +TRY : 'try'; +VOID : 'void'; +VOLATILE : 'volatile'; +WHILE : 'while'; + +// §3.10.1 Integer Literals + +IntegerLiteral + : DecimalIntegerLiteral + | HexIntegerLiteral + | OctalIntegerLiteral + | BinaryIntegerLiteral + ; + +fragment +DecimalIntegerLiteral + : DecimalNumeral IntegerTypeSuffix? + ; + +fragment +HexIntegerLiteral + : HexNumeral IntegerTypeSuffix? + ; + +fragment +OctalIntegerLiteral + : OctalNumeral IntegerTypeSuffix? + ; + +fragment +BinaryIntegerLiteral + : BinaryNumeral IntegerTypeSuffix? + ; + +fragment +IntegerTypeSuffix + : [lL] + ; + +fragment +DecimalNumeral + : '0' + | NonZeroDigit (Digits? | Underscores Digits) + ; + +fragment +Digits + : Digit (DigitsAndUnderscores? Digit)? + ; + +fragment +Digit + : '0' + | NonZeroDigit + ; + +fragment +NonZeroDigit + : [1-9] + ; + +fragment +DigitsAndUnderscores + : DigitOrUnderscore+ + ; + +fragment +DigitOrUnderscore + : Digit + | '_' + ; + +fragment +Underscores + : '_'+ + ; + +fragment +HexNumeral + : '0' [xX] HexDigits + ; + +fragment +HexDigits + : HexDigit (HexDigitsAndUnderscores? HexDigit)? + ; + +fragment +HexDigit + : [0-9a-fA-F] + ; + +fragment +HexDigitsAndUnderscores + : HexDigitOrUnderscore+ + ; + +fragment +HexDigitOrUnderscore + : HexDigit + | '_' + ; + +fragment +OctalNumeral + : '0' Underscores? OctalDigits + ; + +fragment +OctalDigits + : OctalDigit (OctalDigitsAndUnderscores? OctalDigit)? + ; + +fragment +OctalDigit + : [0-7] + ; + +fragment +OctalDigitsAndUnderscores + : OctalDigitOrUnderscore+ + ; + +fragment +OctalDigitOrUnderscore + : OctalDigit + | '_' + ; + +fragment +BinaryNumeral + : '0' [bB] BinaryDigits + ; + +fragment +BinaryDigits + : BinaryDigit (BinaryDigitsAndUnderscores? BinaryDigit)? + ; + +fragment +BinaryDigit + : [01] + ; + +fragment +BinaryDigitsAndUnderscores + : BinaryDigitOrUnderscore+ + ; + +fragment +BinaryDigitOrUnderscore + : BinaryDigit + | '_' + ; + +// §3.10.2 Floating-Point Literals + +FloatingPointLiteral + : DecimalFloatingPointLiteral + | HexadecimalFloatingPointLiteral + ; + +fragment +DecimalFloatingPointLiteral + : Digits '.' Digits? ExponentPart? FloatTypeSuffix? + | '.' Digits ExponentPart? FloatTypeSuffix? + | Digits ExponentPart FloatTypeSuffix? + | Digits FloatTypeSuffix + ; + +fragment +ExponentPart + : ExponentIndicator SignedInteger + ; + +fragment +ExponentIndicator + : [eE] + ; + +fragment +SignedInteger + : Sign? Digits + ; + +fragment +Sign + : [+-] + ; + +fragment +FloatTypeSuffix + : [fFdD] + ; + +fragment +HexadecimalFloatingPointLiteral + : HexSignificand BinaryExponent FloatTypeSuffix? + ; + +fragment +HexSignificand + : HexNumeral '.'? + | '0' [xX] HexDigits? '.' HexDigits + ; + +fragment +BinaryExponent + : BinaryExponentIndicator SignedInteger + ; + +fragment +BinaryExponentIndicator + : [pP] + ; + +// §3.10.3 Boolean Literals + +BooleanLiteral + : 'true' + | 'false' + ; + +// §3.10.4 Character Literals + +CharacterLiteral + : '\'' SingleCharacter '\'' + | '\'' EscapeSequence '\'' + ; + +fragment +SingleCharacter + : ~['\\\r\n] + ; + +// §3.10.5 String Literals + +StringLiteral + : '"' StringCharacters? '"' + ; + +fragment +StringCharacters + : StringCharacter+ + ; + +fragment +StringCharacter + : ~["\\\r\n] + | EscapeSequence + ; + +// §3.10.6 Escape Sequences for Character and String Literals + +fragment +EscapeSequence + : '\\' [btnfr"'\\] + | OctalEscape + | UnicodeEscape // This is not in the spec but prevents having to preprocess the input + ; + +fragment +OctalEscape + : '\\' OctalDigit + | '\\' OctalDigit OctalDigit + | '\\' ZeroToThree OctalDigit OctalDigit + ; + +fragment +ZeroToThree + : [0-3] + ; + +// This is not in the spec but prevents having to preprocess the input +fragment +UnicodeEscape + : '\\' 'u'+ HexDigit HexDigit HexDigit HexDigit + ; + +// §3.10.7 The Null Literal + +NullLiteral + : 'null' + ; + +// §3.11 Separators + +LPAREN : '('; +RPAREN : ')'; +LBRACE : '{'; +RBRACE : '}'; +LBRACK : '['; +RBRACK : ']'; +SEMI : ';'; +COMMA : ','; +DOT : '.'; + +// §3.12 Operators + +ASSIGN : '='; +GT : '>'; +LT : '<'; +BANG : '!'; +TILDE : '~'; +QUESTION : '?'; +COLON : ':'; +EQUAL : '=='; +LE : '<='; +GE : '>='; +NOTEQUAL : '!='; +AND : '&&'; +OR : '||'; +INC : '++'; +DEC : '--'; +ADD : '+'; +SUB : '-'; +MUL : '*'; +DIV : '/'; +BITAND : '&'; +BITOR : '|'; +CARET : '^'; +MOD : '%'; +ARROW : '->'; +COLONCOLON : '::'; + +ADD_ASSIGN : '+='; +SUB_ASSIGN : '-='; +MUL_ASSIGN : '*='; +DIV_ASSIGN : '/='; +AND_ASSIGN : '&='; +OR_ASSIGN : '|='; +XOR_ASSIGN : '^='; +MOD_ASSIGN : '%='; +LSHIFT_ASSIGN : '<<='; +RSHIFT_ASSIGN : '>>='; +URSHIFT_ASSIGN : '>>>='; + +// §3.8 Identifiers (must appear after all keywords in the grammar) + +Identifier + : JavaLetter JavaLetterOrDigit* + ; + +fragment +JavaLetter + : [a-zA-Z$_] // these are the "java letters" below 0x7F + | // covers all characters above 0x7F which are not a surrogate + ~[\u0000-\u007F\uD800-\uDBFF] + {Character.isJavaIdentifierStart(_input.LA(-1))}? + | // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF + [\uD800-\uDBFF] [\uDC00-\uDFFF] + {Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? + ; + +fragment +JavaLetterOrDigit + : [a-zA-Z0-9$_] // these are the "java letters or digits" below 0x7F + | // covers all characters above 0x7F which are not a surrogate + ~[\u0000-\u007F\uD800-\uDBFF] + {Character.isJavaIdentifierPart(_input.LA(-1))}? + | // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF + [\uD800-\uDBFF] [\uDC00-\uDFFF] + {Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? + ; + +// +// Additional symbols not defined in the lexical specification +// + +AT : '@'; +ELLIPSIS : '...'; + +// +// Whitespace and comments +// + +WS : [ \t\r\n\u000C]+ -> skip + ; + +COMMENT + : '/*' .*? '*/' -> skip + ; + +LINE_COMMENT + : '//' ~[\r\n]* -> skip + ; \ No newline at end of file diff --git a/antlr/src/main/antlr4/com/baeldung/antlr/Log.g4 b/antlr/src/main/antlr4/com/baeldung/antlr/Log.g4 new file mode 100644 index 0000000000..3ecb966f50 --- /dev/null +++ b/antlr/src/main/antlr4/com/baeldung/antlr/Log.g4 @@ -0,0 +1,16 @@ +grammar Log; + +log : entry+; +entry : timestamp ' ' level ' ' message CRLF; +timestamp : DATE ' ' TIME; +level : 'ERROR' | 'INFO' | 'DEBUG'; +message : (TEXT | ' ')+; + +fragment DIGIT : [0-9]; +fragment TWODIGIT : DIGIT DIGIT; +fragment LETTER : [A-Za-z]; + +DATE : TWODIGIT TWODIGIT '-' LETTER LETTER LETTER '-' TWODIGIT; +TIME : TWODIGIT ':' TWODIGIT ':' TWODIGIT; +TEXT : LETTER+; +CRLF : '\r'? '\n' | '\r'; \ No newline at end of file diff --git a/antlr/src/main/java/com/baeldung/antlr/java/UppercaseMethodListener.java b/antlr/src/main/java/com/baeldung/antlr/java/UppercaseMethodListener.java new file mode 100644 index 0000000000..5092359b72 --- /dev/null +++ b/antlr/src/main/java/com/baeldung/antlr/java/UppercaseMethodListener.java @@ -0,0 +1,28 @@ +package com.baeldung.antlr.java; + +import com.baeldung.antlr.Java8BaseListener; +import com.baeldung.antlr.Java8Parser; +import org.antlr.v4.runtime.tree.TerminalNode; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class UppercaseMethodListener extends Java8BaseListener { + + private List errors = new ArrayList(); + + @Override + public void enterMethodDeclarator(Java8Parser.MethodDeclaratorContext ctx) { + TerminalNode node = ctx.Identifier(); + String methodName = node.getText(); + + if (Character.isUpperCase(methodName.charAt(0))){ + errors.add(String.format("Method %s is uppercased!", methodName)); + } + } + + public List getErrors(){ + return Collections.unmodifiableList(errors); + } +} diff --git a/antlr/src/main/java/com/baeldung/antlr/log/LogListener.java b/antlr/src/main/java/com/baeldung/antlr/log/LogListener.java new file mode 100644 index 0000000000..1f6d91df95 --- /dev/null +++ b/antlr/src/main/java/com/baeldung/antlr/log/LogListener.java @@ -0,0 +1,51 @@ +package com.baeldung.antlr.log; + +import com.baeldung.antlr.LogBaseListener; +import com.baeldung.antlr.LogParser; +import com.baeldung.antlr.log.model.LogLevel; +import com.baeldung.antlr.log.model.LogEntry; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; + +public class LogListener extends LogBaseListener { + + private static final DateTimeFormatter DEFAULT_DATETIME_FORMATTER + = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss", Locale.ENGLISH); + + private List entries = new ArrayList<>(); + private LogEntry currentLogEntry; + + @Override + public void enterEntry(LogParser.EntryContext ctx) { + this.currentLogEntry = new LogEntry(); + } + + @Override + public void exitEntry(LogParser.EntryContext ctx) { + entries.add(currentLogEntry); + } + + @Override + public void enterTimestamp(LogParser.TimestampContext ctx) { + currentLogEntry.setTimestamp(LocalDateTime.parse(ctx.getText(), DEFAULT_DATETIME_FORMATTER)); + } + + @Override + public void enterMessage(LogParser.MessageContext ctx) { + currentLogEntry.setMessage(ctx.getText()); + } + + @Override + public void enterLevel(LogParser.LevelContext ctx) { + currentLogEntry.setLevel(LogLevel.valueOf(ctx.getText())); + } + + public List getEntries() { + return Collections.unmodifiableList(entries); + } +} diff --git a/antlr/src/main/java/com/baeldung/antlr/log/model/LogEntry.java b/antlr/src/main/java/com/baeldung/antlr/log/model/LogEntry.java new file mode 100644 index 0000000000..2b406c4ae9 --- /dev/null +++ b/antlr/src/main/java/com/baeldung/antlr/log/model/LogEntry.java @@ -0,0 +1,35 @@ +package com.baeldung.antlr.log.model; + + +import java.time.LocalDateTime; + +public class LogEntry { + + private LogLevel level; + private String message; + private LocalDateTime timestamp; + + public LogLevel getLevel() { + return level; + } + + public void setLevel(LogLevel level) { + this.level = level; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public LocalDateTime getTimestamp() { + return timestamp; + } + + public void setTimestamp(LocalDateTime timestamp) { + this.timestamp = timestamp; + } +} diff --git a/antlr/src/main/java/com/baeldung/antlr/log/model/LogLevel.java b/antlr/src/main/java/com/baeldung/antlr/log/model/LogLevel.java new file mode 100644 index 0000000000..004d9c6e8c --- /dev/null +++ b/antlr/src/main/java/com/baeldung/antlr/log/model/LogLevel.java @@ -0,0 +1,5 @@ +package com.baeldung.antlr.log.model; + +public enum LogLevel { + DEBUG, INFO, ERROR +} diff --git a/antlr/src/main/resources/logback.xml b/antlr/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/antlr/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/antlr/src/test/java/com/baeldung/antlr/JavaParserUnitTest.java b/antlr/src/test/java/com/baeldung/antlr/JavaParserUnitTest.java new file mode 100644 index 0000000000..0d43e0f284 --- /dev/null +++ b/antlr/src/test/java/com/baeldung/antlr/JavaParserUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.antlr; + +import com.baeldung.antlr.java.UppercaseMethodListener; +import org.antlr.v4.runtime.CharStreams; +import org.antlr.v4.runtime.CommonTokenStream; +import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.ParseTreeWalker; +import org.junit.Test; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +public class JavaParserUnitTest { + + @Test + public void whenOneMethodStartsWithUpperCase_thenOneErrorReturned() throws Exception{ + + String javaClassContent = "public class SampleClass { void DoSomething(){} }"; + Java8Lexer java8Lexer = new Java8Lexer(CharStreams.fromString(javaClassContent)); + CommonTokenStream tokens = new CommonTokenStream(java8Lexer); + Java8Parser java8Parser = new Java8Parser(tokens); + ParseTree tree = java8Parser.compilationUnit(); + ParseTreeWalker walker = new ParseTreeWalker(); + UppercaseMethodListener uppercaseMethodListener = new UppercaseMethodListener(); + walker.walk(uppercaseMethodListener, tree); + + assertThat(uppercaseMethodListener.getErrors().size(), is(1)); + assertThat(uppercaseMethodListener.getErrors().get(0), + is("Method DoSomething is uppercased!")); + } +} diff --git a/antlr/src/test/java/com/baeldung/antlr/LogParserUnitTest.java b/antlr/src/test/java/com/baeldung/antlr/LogParserUnitTest.java new file mode 100644 index 0000000000..d263c2bd19 --- /dev/null +++ b/antlr/src/test/java/com/baeldung/antlr/LogParserUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.antlr; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import com.baeldung.antlr.log.LogListener; +import com.baeldung.antlr.log.model.LogLevel; +import com.baeldung.antlr.log.model.LogEntry; +import org.antlr.v4.runtime.CharStreams; +import org.antlr.v4.runtime.CommonTokenStream; +import org.antlr.v4.runtime.tree.ParseTreeWalker; +import org.junit.Test; + +import java.time.LocalDateTime; + + +public class LogParserUnitTest { + + @Test + public void whenLogContainsOneErrorLogEntry_thenOneErrorIsReturned() throws Exception { + String logLines = "2018-May-05 14:20:21 DEBUG entering awesome method\r\n" + + "2018-May-05 14:20:24 ERROR Bad thing happened\r\n"; + LogLexer serverLogLexer = new LogLexer(CharStreams.fromString(logLines)); + CommonTokenStream tokens = new CommonTokenStream( serverLogLexer ); + LogParser logParser = new LogParser(tokens); + ParseTreeWalker walker = new ParseTreeWalker(); + LogListener logWalker = new LogListener(); + walker.walk(logWalker, logParser.log()); + + assertThat(logWalker.getEntries().size(), is(2)); + LogEntry error = logWalker.getEntries().get(1); + assertThat(error.getLevel(), is(LogLevel.ERROR)); + assertThat(error.getMessage(), is("Bad thing happened")); + assertThat(error.getTimestamp(), is(LocalDateTime.of(2018,5,5,14,20,24))); + } +} diff --git a/apache-avro/README.md b/apache-avro/README.md new file mode 100644 index 0000000000..32d84ecc76 --- /dev/null +++ b/apache-avro/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Guide to Apache Avro](http://www.baeldung.com/java-apache-avro) diff --git a/apache-avro/pom.xml b/apache-avro/pom.xml new file mode 100644 index 0000000000..3e3234ff96 --- /dev/null +++ b/apache-avro/pom.xml @@ -0,0 +1,89 @@ + + + 4.0.0 + com.baeldung + apache-avro + 0.0.1-SNAPSHOT + Apache Avro + + + UTF-8 + 3.5 + 1.8.2 + 1.8 + 1.7.25 + + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + junit + junit + 4.10 + test + + + org.slf4j + slf4j-simple + ${slf4j.version} + compile + + + org.apache.avro + avro + ${avro.version} + + + org.apache.avro + avro-compiler + ${avro.version} + + + + org.apache.avro + avro-maven-plugin + ${avro.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${compiler-plugin.version} + + ${java.version} + ${java.version} + + + + org.apache.avro + avro-maven-plugin + ${avro.version} + + + schemas + generate-sources + + schema + protocol + idl-protocol + + + ${project.basedir}/src/main/resources/ + ${project.basedir}/src/main/java/ + + + + + + + diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/AvroClassGenerator.java b/apache-avro/src/main/java/com/baeldung/avro/util/AvroClassGenerator.java new file mode 100644 index 0000000000..718b62a752 --- /dev/null +++ b/apache-avro/src/main/java/com/baeldung/avro/util/AvroClassGenerator.java @@ -0,0 +1,14 @@ +package com.baeldung.avro.util; + +import org.apache.avro.Schema; +import org.apache.avro.compiler.specific.SpecificCompiler; + +import java.io.File; +import java.io.IOException; + +public class AvroClassGenerator { + public void generateAvroClasses() throws IOException { + SpecificCompiler compiler = new SpecificCompiler(new Schema.Parser().parse(new File("src/main/resources/avroHttpRequest-schema.avsc"))); + compiler.compileToDestination(new File("src/main/resources"), new File("src/main/java")); + } +} diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/AvroSchemaBuilder.java b/apache-avro/src/main/java/com/baeldung/avro/util/AvroSchemaBuilder.java new file mode 100644 index 0000000000..4a1314cd00 --- /dev/null +++ b/apache-avro/src/main/java/com/baeldung/avro/util/AvroSchemaBuilder.java @@ -0,0 +1,24 @@ +package com.baeldung.avro.util; + + +import org.apache.avro.Schema; +import org.apache.avro.SchemaBuilder; + +public class AvroSchemaBuilder { + + public Schema createAvroHttpRequestSchema(){ + + Schema clientIdentifier = SchemaBuilder.record("ClientIdentifier").namespace("com.baeldung.avro.model") + .fields().requiredString("hostName").requiredString("ipAddress").endRecord(); + + Schema avroHttpRequest = SchemaBuilder.record("AvroHttpRequest").namespace("com.baeldung.avro.model").fields() + .requiredLong("requestTime") + .name("clientIdentifier").type(clientIdentifier).noDefault() + .name("employeeNames").type().array().items().stringType().arrayDefault(null) + .name("active").type().enumeration("Active").symbols("YES", "NO").noDefault() + .endRecord(); + return avroHttpRequest; + } +} + + diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/model/Active.java b/apache-avro/src/main/java/com/baeldung/avro/util/model/Active.java new file mode 100644 index 0000000000..3ae0508394 --- /dev/null +++ b/apache-avro/src/main/java/com/baeldung/avro/util/model/Active.java @@ -0,0 +1,13 @@ +/** + * Autogenerated by Avro + * + * DO NOT EDIT DIRECTLY + */ +package com.baeldung.avro.util.model; +@SuppressWarnings("all") +@org.apache.avro.specific.AvroGenerated +public enum Active { + YES, NO ; + public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"enum\",\"name\":\"Active\",\"namespace\":\"com.baeldung.avro.model\",\"symbols\":[\"YES\",\"NO\"]}"); + public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; } +} diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/model/AvroHttpRequest.java b/apache-avro/src/main/java/com/baeldung/avro/util/model/AvroHttpRequest.java new file mode 100644 index 0000000000..56b36050a5 --- /dev/null +++ b/apache-avro/src/main/java/com/baeldung/avro/util/model/AvroHttpRequest.java @@ -0,0 +1,491 @@ +/** + * Autogenerated by Avro + * + * DO NOT EDIT DIRECTLY + */ +package com.baeldung.avro.util.model; + +import org.apache.avro.specific.SpecificData; +import org.apache.avro.message.BinaryMessageEncoder; +import org.apache.avro.message.BinaryMessageDecoder; +import org.apache.avro.message.SchemaStore; + +@SuppressWarnings("all") +@org.apache.avro.specific.AvroGenerated +public class AvroHttpRequest extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord { + private static final long serialVersionUID = -8649010116827875312L; + public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"AvroHttpRequest\",\"namespace\":\"com.baeldung.avro.model\",\"fields\":[{\"name\":\"requestTime\",\"type\":\"long\"},{\"name\":\"clientIdentifier\",\"type\":{\"type\":\"record\",\"name\":\"ClientIdentifier\",\"fields\":[{\"name\":\"hostName\",\"type\":\"string\"},{\"name\":\"ipAddress\",\"type\":\"string\"}]}},{\"name\":\"employeeNames\",\"type\":{\"type\":\"array\",\"items\":\"string\"},\"default\":null},{\"name\":\"active\",\"type\":{\"type\":\"enum\",\"name\":\"Active\",\"symbols\":[\"YES\",\"NO\"]}}]}"); + public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; } + + private static SpecificData MODEL$ = new SpecificData(); + + private static final BinaryMessageEncoder ENCODER = + new BinaryMessageEncoder(MODEL$, SCHEMA$); + + private static final BinaryMessageDecoder DECODER = + new BinaryMessageDecoder(MODEL$, SCHEMA$); + + /** + * Return the BinaryMessageDecoder instance used by this class. + */ + public static BinaryMessageDecoder getDecoder() { + return DECODER; + } + + /** + * Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}. + * @param resolver a {@link SchemaStore} used to find schemas by fingerprint + */ + public static BinaryMessageDecoder createDecoder(SchemaStore resolver) { + return new BinaryMessageDecoder(MODEL$, SCHEMA$, resolver); + } + + /** Serializes this AvroHttpRequest to a ByteBuffer. */ + public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException { + return ENCODER.encode(this); + } + + /** Deserializes a AvroHttpRequest from a ByteBuffer. */ + public static AvroHttpRequest fromByteBuffer( + java.nio.ByteBuffer b) throws java.io.IOException { + return DECODER.decode(b); + } + + @Deprecated public long requestTime; + @Deprecated public ClientIdentifier clientIdentifier; + @Deprecated public java.util.List employeeNames; + @Deprecated public Active active; + + /** + * Default constructor. Note that this does not initialize fields + * to their default values from the schema. If that is desired then + * one should use newBuilder(). + */ + public AvroHttpRequest() {} + + /** + * All-args constructor. + * @param requestTime The new value for requestTime + * @param clientIdentifier The new value for clientIdentifier + * @param employeeNames The new value for employeeNames + * @param active The new value for active + */ + public AvroHttpRequest(java.lang.Long requestTime, ClientIdentifier clientIdentifier, java.util.List employeeNames, Active active) { + this.requestTime = requestTime; + this.clientIdentifier = clientIdentifier; + this.employeeNames = employeeNames; + this.active = active; + } + + public org.apache.avro.Schema getSchema() { return SCHEMA$; } + // Used by DatumWriter. Applications should not call. + public java.lang.Object get(int field$) { + switch (field$) { + case 0: return requestTime; + case 1: return clientIdentifier; + case 2: return employeeNames; + case 3: return active; + default: throw new org.apache.avro.AvroRuntimeException("Bad index"); + } + } + + // Used by DatumReader. Applications should not call. + @SuppressWarnings(value="unchecked") + public void put(int field$, java.lang.Object value$) { + switch (field$) { + case 0: requestTime = (java.lang.Long)value$; break; + case 1: clientIdentifier = (ClientIdentifier)value$; break; + case 2: employeeNames = (java.util.List)value$; break; + case 3: active = (Active)value$; break; + default: throw new org.apache.avro.AvroRuntimeException("Bad index"); + } + } + + /** + * Gets the value of the 'requestTime' field. + * @return The value of the 'requestTime' field. + */ + public java.lang.Long getRequestTime() { + return requestTime; + } + + /** + * Sets the value of the 'requestTime' field. + * @param value the value to set. + */ + public void setRequestTime(java.lang.Long value) { + this.requestTime = value; + } + + /** + * Gets the value of the 'clientIdentifier' field. + * @return The value of the 'clientIdentifier' field. + */ + public ClientIdentifier getClientIdentifier() { + return clientIdentifier; + } + + /** + * Sets the value of the 'clientIdentifier' field. + * @param value the value to set. + */ + public void setClientIdentifier(ClientIdentifier value) { + this.clientIdentifier = value; + } + + /** + * Gets the value of the 'employeeNames' field. + * @return The value of the 'employeeNames' field. + */ + public java.util.List getEmployeeNames() { + return employeeNames; + } + + /** + * Sets the value of the 'employeeNames' field. + * @param value the value to set. + */ + public void setEmployeeNames(java.util.List value) { + this.employeeNames = value; + } + + /** + * Gets the value of the 'active' field. + * @return The value of the 'active' field. + */ + public Active getActive() { + return active; + } + + /** + * Sets the value of the 'active' field. + * @param value the value to set. + */ + public void setActive(Active value) { + this.active = value; + } + + /** + * Creates a new AvroHttpRequest RecordBuilder. + * @return A new AvroHttpRequest RecordBuilder + */ + public static AvroHttpRequest.Builder newBuilder() { + return new AvroHttpRequest.Builder(); + } + + /** + * Creates a new AvroHttpRequest RecordBuilder by copying an existing Builder. + * @param other The existing builder to copy. + * @return A new AvroHttpRequest RecordBuilder + */ + public static AvroHttpRequest.Builder newBuilder(AvroHttpRequest.Builder other) { + return new AvroHttpRequest.Builder(other); + } + + /** + * Creates a new AvroHttpRequest RecordBuilder by copying an existing AvroHttpRequest instance. + * @param other The existing instance to copy. + * @return A new AvroHttpRequest RecordBuilder + */ + public static AvroHttpRequest.Builder newBuilder(AvroHttpRequest other) { + return new AvroHttpRequest.Builder(other); + } + + /** + * RecordBuilder for AvroHttpRequest instances. + */ + public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase + implements org.apache.avro.data.RecordBuilder { + + private long requestTime; + private ClientIdentifier clientIdentifier; + private ClientIdentifier.Builder clientIdentifierBuilder; + private java.util.List employeeNames; + private Active active; + + /** Creates a new Builder */ + private Builder() { + super(SCHEMA$); + } + + /** + * Creates a Builder by copying an existing Builder. + * @param other The existing Builder to copy. + */ + private Builder(AvroHttpRequest.Builder other) { + super(other); + if (isValidValue(fields()[0], other.requestTime)) { + this.requestTime = data().deepCopy(fields()[0].schema(), other.requestTime); + fieldSetFlags()[0] = true; + } + if (isValidValue(fields()[1], other.clientIdentifier)) { + this.clientIdentifier = data().deepCopy(fields()[1].schema(), other.clientIdentifier); + fieldSetFlags()[1] = true; + } + if (other.hasClientIdentifierBuilder()) { + this.clientIdentifierBuilder = ClientIdentifier.newBuilder(other.getClientIdentifierBuilder()); + } + if (isValidValue(fields()[2], other.employeeNames)) { + this.employeeNames = data().deepCopy(fields()[2].schema(), other.employeeNames); + fieldSetFlags()[2] = true; + } + if (isValidValue(fields()[3], other.active)) { + this.active = data().deepCopy(fields()[3].schema(), other.active); + fieldSetFlags()[3] = true; + } + } + + /** + * Creates a Builder by copying an existing AvroHttpRequest instance + * @param other The existing instance to copy. + */ + private Builder(AvroHttpRequest other) { + super(SCHEMA$); + if (isValidValue(fields()[0], other.requestTime)) { + this.requestTime = data().deepCopy(fields()[0].schema(), other.requestTime); + fieldSetFlags()[0] = true; + } + if (isValidValue(fields()[1], other.clientIdentifier)) { + this.clientIdentifier = data().deepCopy(fields()[1].schema(), other.clientIdentifier); + fieldSetFlags()[1] = true; + } + this.clientIdentifierBuilder = null; + if (isValidValue(fields()[2], other.employeeNames)) { + this.employeeNames = data().deepCopy(fields()[2].schema(), other.employeeNames); + fieldSetFlags()[2] = true; + } + if (isValidValue(fields()[3], other.active)) { + this.active = data().deepCopy(fields()[3].schema(), other.active); + fieldSetFlags()[3] = true; + } + } + + /** + * Gets the value of the 'requestTime' field. + * @return The value. + */ + public java.lang.Long getRequestTime() { + return requestTime; + } + + /** + * Sets the value of the 'requestTime' field. + * @param value The value of 'requestTime'. + * @return This builder. + */ + public AvroHttpRequest.Builder setRequestTime(long value) { + validate(fields()[0], value); + this.requestTime = value; + fieldSetFlags()[0] = true; + return this; + } + + /** + * Checks whether the 'requestTime' field has been set. + * @return True if the 'requestTime' field has been set, false otherwise. + */ + public boolean hasRequestTime() { + return fieldSetFlags()[0]; + } + + + /** + * Clears the value of the 'requestTime' field. + * @return This builder. + */ + public AvroHttpRequest.Builder clearRequestTime() { + fieldSetFlags()[0] = false; + return this; + } + + /** + * Gets the value of the 'clientIdentifier' field. + * @return The value. + */ + public ClientIdentifier getClientIdentifier() { + return clientIdentifier; + } + + /** + * Sets the value of the 'clientIdentifier' field. + * @param value The value of 'clientIdentifier'. + * @return This builder. + */ + public AvroHttpRequest.Builder setClientIdentifier(ClientIdentifier value) { + validate(fields()[1], value); + this.clientIdentifierBuilder = null; + this.clientIdentifier = value; + fieldSetFlags()[1] = true; + return this; + } + + /** + * Checks whether the 'clientIdentifier' field has been set. + * @return True if the 'clientIdentifier' field has been set, false otherwise. + */ + public boolean hasClientIdentifier() { + return fieldSetFlags()[1]; + } + + /** + * Gets the Builder instance for the 'clientIdentifier' field and creates one if it doesn't exist yet. + * @return This builder. + */ + public ClientIdentifier.Builder getClientIdentifierBuilder() { + if (clientIdentifierBuilder == null) { + if (hasClientIdentifier()) { + setClientIdentifierBuilder(ClientIdentifier.newBuilder(clientIdentifier)); + } else { + setClientIdentifierBuilder(ClientIdentifier.newBuilder()); + } + } + return clientIdentifierBuilder; + } + + /** + * Sets the Builder instance for the 'clientIdentifier' field + * @param value The builder instance that must be set. + * @return This builder. + */ + public AvroHttpRequest.Builder setClientIdentifierBuilder(ClientIdentifier.Builder value) { + clearClientIdentifier(); + clientIdentifierBuilder = value; + return this; + } + + /** + * Checks whether the 'clientIdentifier' field has an active Builder instance + * @return True if the 'clientIdentifier' field has an active Builder instance + */ + public boolean hasClientIdentifierBuilder() { + return clientIdentifierBuilder != null; + } + + /** + * Clears the value of the 'clientIdentifier' field. + * @return This builder. + */ + public AvroHttpRequest.Builder clearClientIdentifier() { + clientIdentifier = null; + clientIdentifierBuilder = null; + fieldSetFlags()[1] = false; + return this; + } + + /** + * Gets the value of the 'employeeNames' field. + * @return The value. + */ + public java.util.List getEmployeeNames() { + return employeeNames; + } + + /** + * Sets the value of the 'employeeNames' field. + * @param value The value of 'employeeNames'. + * @return This builder. + */ + public AvroHttpRequest.Builder setEmployeeNames(java.util.List value) { + validate(fields()[2], value); + this.employeeNames = value; + fieldSetFlags()[2] = true; + return this; + } + + /** + * Checks whether the 'employeeNames' field has been set. + * @return True if the 'employeeNames' field has been set, false otherwise. + */ + public boolean hasEmployeeNames() { + return fieldSetFlags()[2]; + } + + + /** + * Clears the value of the 'employeeNames' field. + * @return This builder. + */ + public AvroHttpRequest.Builder clearEmployeeNames() { + employeeNames = null; + fieldSetFlags()[2] = false; + return this; + } + + /** + * Gets the value of the 'active' field. + * @return The value. + */ + public Active getActive() { + return active; + } + + /** + * Sets the value of the 'active' field. + * @param value The value of 'active'. + * @return This builder. + */ + public AvroHttpRequest.Builder setActive(Active value) { + validate(fields()[3], value); + this.active = value; + fieldSetFlags()[3] = true; + return this; + } + + /** + * Checks whether the 'active' field has been set. + * @return True if the 'active' field has been set, false otherwise. + */ + public boolean hasActive() { + return fieldSetFlags()[3]; + } + + + /** + * Clears the value of the 'active' field. + * @return This builder. + */ + public AvroHttpRequest.Builder clearActive() { + active = null; + fieldSetFlags()[3] = false; + return this; + } + + @Override + @SuppressWarnings("unchecked") + public AvroHttpRequest build() { + try { + AvroHttpRequest record = new AvroHttpRequest(); + record.requestTime = fieldSetFlags()[0] ? this.requestTime : (java.lang.Long) defaultValue(fields()[0]); + if (clientIdentifierBuilder != null) { + record.clientIdentifier = this.clientIdentifierBuilder.build(); + } else { + record.clientIdentifier = fieldSetFlags()[1] ? this.clientIdentifier : (ClientIdentifier) defaultValue(fields()[1]); + } + record.employeeNames = fieldSetFlags()[2] ? this.employeeNames : (java.util.List) defaultValue(fields()[2]); + record.active = fieldSetFlags()[3] ? this.active : (Active) defaultValue(fields()[3]); + return record; + } catch (java.lang.Exception e) { + throw new org.apache.avro.AvroRuntimeException(e); + } + } + } + + @SuppressWarnings("unchecked") + private static final org.apache.avro.io.DatumWriter + WRITER$ = (org.apache.avro.io.DatumWriter)MODEL$.createDatumWriter(SCHEMA$); + + @Override public void writeExternal(java.io.ObjectOutput out) + throws java.io.IOException { + WRITER$.write(this, SpecificData.getEncoder(out)); + } + + @SuppressWarnings("unchecked") + private static final org.apache.avro.io.DatumReader + READER$ = (org.apache.avro.io.DatumReader)MODEL$.createDatumReader(SCHEMA$); + + @Override public void readExternal(java.io.ObjectInput in) + throws java.io.IOException { + READER$.read(this, SpecificData.getDecoder(in)); + } + +} diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/model/ClientIdentifier.java b/apache-avro/src/main/java/com/baeldung/avro/util/model/ClientIdentifier.java new file mode 100644 index 0000000000..503dde40df --- /dev/null +++ b/apache-avro/src/main/java/com/baeldung/avro/util/model/ClientIdentifier.java @@ -0,0 +1,308 @@ +/** + * Autogenerated by Avro + * + * DO NOT EDIT DIRECTLY + */ +package com.baeldung.avro.util.model; + +import org.apache.avro.specific.SpecificData; +import org.apache.avro.message.BinaryMessageEncoder; +import org.apache.avro.message.BinaryMessageDecoder; +import org.apache.avro.message.SchemaStore; + +@SuppressWarnings("all") +@org.apache.avro.specific.AvroGenerated +public class ClientIdentifier extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord { + private static final long serialVersionUID = 8754570983127295424L; + public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"ClientIdentifier\",\"namespace\":\"com.baeldung.avro.model\",\"fields\":[{\"name\":\"hostName\",\"type\":\"string\"},{\"name\":\"ipAddress\",\"type\":\"string\"}]}"); + public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; } + + private static SpecificData MODEL$ = new SpecificData(); + + private static final BinaryMessageEncoder ENCODER = + new BinaryMessageEncoder(MODEL$, SCHEMA$); + + private static final BinaryMessageDecoder DECODER = + new BinaryMessageDecoder(MODEL$, SCHEMA$); + + /** + * Return the BinaryMessageDecoder instance used by this class. + */ + public static BinaryMessageDecoder getDecoder() { + return DECODER; + } + + /** + * Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}. + * @param resolver a {@link SchemaStore} used to find schemas by fingerprint + */ + public static BinaryMessageDecoder createDecoder(SchemaStore resolver) { + return new BinaryMessageDecoder(MODEL$, SCHEMA$, resolver); + } + + /** Serializes this ClientIdentifier to a ByteBuffer. */ + public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException { + return ENCODER.encode(this); + } + + /** Deserializes a ClientIdentifier from a ByteBuffer. */ + public static ClientIdentifier fromByteBuffer( + java.nio.ByteBuffer b) throws java.io.IOException { + return DECODER.decode(b); + } + + @Deprecated public java.lang.CharSequence hostName; + @Deprecated public java.lang.CharSequence ipAddress; + + /** + * Default constructor. Note that this does not initialize fields + * to their default values from the schema. If that is desired then + * one should use newBuilder(). + */ + public ClientIdentifier() {} + + /** + * All-args constructor. + * @param hostName The new value for hostName + * @param ipAddress The new value for ipAddress + */ + public ClientIdentifier(java.lang.CharSequence hostName, java.lang.CharSequence ipAddress) { + this.hostName = hostName; + this.ipAddress = ipAddress; + } + + public org.apache.avro.Schema getSchema() { return SCHEMA$; } + // Used by DatumWriter. Applications should not call. + public java.lang.Object get(int field$) { + switch (field$) { + case 0: return hostName; + case 1: return ipAddress; + default: throw new org.apache.avro.AvroRuntimeException("Bad index"); + } + } + + // Used by DatumReader. Applications should not call. + @SuppressWarnings(value="unchecked") + public void put(int field$, java.lang.Object value$) { + switch (field$) { + case 0: hostName = (java.lang.CharSequence)value$; break; + case 1: ipAddress = (java.lang.CharSequence)value$; break; + default: throw new org.apache.avro.AvroRuntimeException("Bad index"); + } + } + + /** + * Gets the value of the 'hostName' field. + * @return The value of the 'hostName' field. + */ + public java.lang.CharSequence getHostName() { + return hostName; + } + + /** + * Sets the value of the 'hostName' field. + * @param value the value to set. + */ + public void setHostName(java.lang.CharSequence value) { + this.hostName = value; + } + + /** + * Gets the value of the 'ipAddress' field. + * @return The value of the 'ipAddress' field. + */ + public java.lang.CharSequence getIpAddress() { + return ipAddress; + } + + /** + * Sets the value of the 'ipAddress' field. + * @param value the value to set. + */ + public void setIpAddress(java.lang.CharSequence value) { + this.ipAddress = value; + } + + /** + * Creates a new ClientIdentifier RecordBuilder. + * @return A new ClientIdentifier RecordBuilder + */ + public static ClientIdentifier.Builder newBuilder() { + return new ClientIdentifier.Builder(); + } + + /** + * Creates a new ClientIdentifier RecordBuilder by copying an existing Builder. + * @param other The existing builder to copy. + * @return A new ClientIdentifier RecordBuilder + */ + public static ClientIdentifier.Builder newBuilder(ClientIdentifier.Builder other) { + return new ClientIdentifier.Builder(other); + } + + /** + * Creates a new ClientIdentifier RecordBuilder by copying an existing ClientIdentifier instance. + * @param other The existing instance to copy. + * @return A new ClientIdentifier RecordBuilder + */ + public static ClientIdentifier.Builder newBuilder(ClientIdentifier other) { + return new ClientIdentifier.Builder(other); + } + + /** + * RecordBuilder for ClientIdentifier instances. + */ + public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase + implements org.apache.avro.data.RecordBuilder { + + private java.lang.CharSequence hostName; + private java.lang.CharSequence ipAddress; + + /** Creates a new Builder */ + private Builder() { + super(SCHEMA$); + } + + /** + * Creates a Builder by copying an existing Builder. + * @param other The existing Builder to copy. + */ + private Builder(ClientIdentifier.Builder other) { + super(other); + if (isValidValue(fields()[0], other.hostName)) { + this.hostName = data().deepCopy(fields()[0].schema(), other.hostName); + fieldSetFlags()[0] = true; + } + if (isValidValue(fields()[1], other.ipAddress)) { + this.ipAddress = data().deepCopy(fields()[1].schema(), other.ipAddress); + fieldSetFlags()[1] = true; + } + } + + /** + * Creates a Builder by copying an existing ClientIdentifier instance + * @param other The existing instance to copy. + */ + private Builder(ClientIdentifier other) { + super(SCHEMA$); + if (isValidValue(fields()[0], other.hostName)) { + this.hostName = data().deepCopy(fields()[0].schema(), other.hostName); + fieldSetFlags()[0] = true; + } + if (isValidValue(fields()[1], other.ipAddress)) { + this.ipAddress = data().deepCopy(fields()[1].schema(), other.ipAddress); + fieldSetFlags()[1] = true; + } + } + + /** + * Gets the value of the 'hostName' field. + * @return The value. + */ + public java.lang.CharSequence getHostName() { + return hostName; + } + + /** + * Sets the value of the 'hostName' field. + * @param value The value of 'hostName'. + * @return This builder. + */ + public ClientIdentifier.Builder setHostName(java.lang.CharSequence value) { + validate(fields()[0], value); + this.hostName = value; + fieldSetFlags()[0] = true; + return this; + } + + /** + * Checks whether the 'hostName' field has been set. + * @return True if the 'hostName' field has been set, false otherwise. + */ + public boolean hasHostName() { + return fieldSetFlags()[0]; + } + + + /** + * Clears the value of the 'hostName' field. + * @return This builder. + */ + public ClientIdentifier.Builder clearHostName() { + hostName = null; + fieldSetFlags()[0] = false; + return this; + } + + /** + * Gets the value of the 'ipAddress' field. + * @return The value. + */ + public java.lang.CharSequence getIpAddress() { + return ipAddress; + } + + /** + * Sets the value of the 'ipAddress' field. + * @param value The value of 'ipAddress'. + * @return This builder. + */ + public ClientIdentifier.Builder setIpAddress(java.lang.CharSequence value) { + validate(fields()[1], value); + this.ipAddress = value; + fieldSetFlags()[1] = true; + return this; + } + + /** + * Checks whether the 'ipAddress' field has been set. + * @return True if the 'ipAddress' field has been set, false otherwise. + */ + public boolean hasIpAddress() { + return fieldSetFlags()[1]; + } + + + /** + * Clears the value of the 'ipAddress' field. + * @return This builder. + */ + public ClientIdentifier.Builder clearIpAddress() { + ipAddress = null; + fieldSetFlags()[1] = false; + return this; + } + + @Override + @SuppressWarnings("unchecked") + public ClientIdentifier build() { + try { + ClientIdentifier record = new ClientIdentifier(); + record.hostName = fieldSetFlags()[0] ? this.hostName : (java.lang.CharSequence) defaultValue(fields()[0]); + record.ipAddress = fieldSetFlags()[1] ? this.ipAddress : (java.lang.CharSequence) defaultValue(fields()[1]); + return record; + } catch (java.lang.Exception e) { + throw new org.apache.avro.AvroRuntimeException(e); + } + } + } + + @SuppressWarnings("unchecked") + private static final org.apache.avro.io.DatumWriter + WRITER$ = (org.apache.avro.io.DatumWriter)MODEL$.createDatumWriter(SCHEMA$); + + @Override public void writeExternal(java.io.ObjectOutput out) + throws java.io.IOException { + WRITER$.write(this, SpecificData.getEncoder(out)); + } + + @SuppressWarnings("unchecked") + private static final org.apache.avro.io.DatumReader + READER$ = (org.apache.avro.io.DatumReader)MODEL$.createDatumReader(SCHEMA$); + + @Override public void readExternal(java.io.ObjectInput in) + throws java.io.IOException { + READER$.read(this, SpecificData.getDecoder(in)); + } + +} diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java new file mode 100644 index 0000000000..7d30c3d1ee --- /dev/null +++ b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java @@ -0,0 +1,41 @@ +package com.baeldung.avro.util.serealization; + +import com.baeldung.avro.util.model.AvroHttpRequest; +import org.apache.avro.io.DatumReader; +import org.apache.avro.io.Decoder; +import org.apache.avro.io.DecoderFactory; +import org.apache.avro.specific.SpecificDatumReader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; + +public class AvroDeSerealizer { + + private static Logger logger = LoggerFactory.getLogger(AvroDeSerealizer.class); + + public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data) { + DatumReader reader = new SpecificDatumReader<>(AvroHttpRequest.class); + Decoder decoder = null; + try { + decoder = DecoderFactory.get() + .jsonDecoder(AvroHttpRequest.getClassSchema(), new String(data)); + return reader.read(null, decoder); + } catch (IOException e) { + logger.error("Deserialization error" + e.getMessage()); + } + return null; + } + + public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data) { + DatumReader employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class); + Decoder decoder = DecoderFactory.get() + .binaryDecoder(data, null); + try { + return employeeReader.read(null, decoder); + } catch (IOException e) { + logger.error("Deserialization error" + e.getMessage()); + } + return null; + } +} diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java new file mode 100644 index 0000000000..767b688dea --- /dev/null +++ b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java @@ -0,0 +1,50 @@ +package com.baeldung.avro.util.serealization; + +import com.baeldung.avro.util.model.AvroHttpRequest; +import org.apache.avro.io.*; +import org.apache.avro.specific.SpecificDatumWriter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +public class AvroSerealizer { + + private static final Logger logger = LoggerFactory.getLogger(AvroSerealizer.class); + + public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request) { + DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class); + byte[] data = new byte[0]; + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + Encoder jsonEncoder = null; + try { + jsonEncoder = EncoderFactory.get() + .jsonEncoder(AvroHttpRequest.getClassSchema(), stream); + writer.write(request, jsonEncoder); + jsonEncoder.flush(); + data = stream.toByteArray(); + } catch (IOException e) { + logger.error("Serialization error " + e.getMessage()); + } + return data; + } + + public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request) { + DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class); + byte[] data = new byte[0]; + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + Encoder jsonEncoder = EncoderFactory.get() + .binaryEncoder(stream, null); + try { + writer.write(request, jsonEncoder); + jsonEncoder.flush(); + data = stream.toByteArray(); + } catch (IOException e) { + logger.error("Serialization error " + e.getMessage()); + } + + return data; + } + +} diff --git a/apache-avro/src/main/resources/avroHttpRequest-schema.avsc b/apache-avro/src/main/resources/avroHttpRequest-schema.avsc new file mode 100644 index 0000000000..18179a9cde --- /dev/null +++ b/apache-avro/src/main/resources/avroHttpRequest-schema.avsc @@ -0,0 +1,47 @@ +{ + "type":"record", + "name":"AvroHttpRequest", + "namespace":"com.baeldung.avro.model", + "fields":[ + { + "name":"requestTime", + "type":"long" + }, + { + "name":"clientIdentifier", + "type":{ + "type":"record", + "name":"ClientIdentifier", + "fields":[ + { + "name":"hostName", + "type":"string" + }, + { + "name":"ipAddress", + "type":"string" + } + ] + } + }, + { + "name":"employeeNames", + "type":{ + "type":"array", + "items":"string" + }, + "default":null + }, + { + "name":"active", + "type":{ + "type":"enum", + "name":"Active", + "symbols":[ + "YES", + "NO" + ] + } + } + ] +} \ No newline at end of file diff --git a/apache-avro/src/main/resources/logback.xml b/apache-avro/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-avro/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java b/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java new file mode 100644 index 0000000000..ecd15ccbbc --- /dev/null +++ b/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java @@ -0,0 +1,83 @@ +package com.baeldung.avro.util.serealization; + +import com.baeldung.avro.util.model.Active; +import com.baeldung.avro.util.model.AvroHttpRequest; +import com.baeldung.avro.util.model.ClientIdentifier; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import static org.junit.Assert.*; + +public class AvroSerealizerDeSerealizerTest { + + AvroSerealizer serealizer; + AvroDeSerealizer deSerealizer; + AvroHttpRequest request; + + @Before + public void setUp() throws Exception { + serealizer = new AvroSerealizer(); + deSerealizer = new AvroDeSerealizer(); + + ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder() + .setHostName("localhost") + .setIpAddress("255.255.255.0") + .build(); + + List employees = new ArrayList(); + employees.add("James"); + employees.add("Alice"); + employees.add("David"); + employees.add("Han"); + + request = AvroHttpRequest.newBuilder() + .setRequestTime(01l) + .setActive(Active.YES) + .setClientIdentifier(clientIdentifier) + .setEmployeeNames(employees) + .build(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void WhenSerializedUsingJSONEncoder_thenObjectGetsSerialized() { + byte[] data = serealizer.serealizeAvroHttpRequestJSON(request); + assertTrue(Objects.nonNull(data)); + assertTrue(data.length > 0); + } + + @Test + public void WhenSerializedUsingBinaryEncoder_thenObjectGetsSerialized() { + byte[] data = serealizer.serealizeAvroHttpRequestBinary(request); + assertTrue(Objects.nonNull(data)); + assertTrue(data.length > 0); + } + + @Test + public void WhenDeserializeUsingJSONDecoder_thenActualAndExpectedObjectsAreEqual() { + byte[] data = serealizer.serealizeAvroHttpRequestJSON(request); + AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data); + assertEquals(actualRequest, request); + assertTrue(actualRequest.getRequestTime() + .equals(request.getRequestTime())); + } + + @Test + public void WhenDeserializeUsingBinaryecoder_thenActualAndExpectedObjectsAreEqual() { + byte[] data = serealizer.serealizeAvroHttpRequestBinary(request); + AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data); + assertEquals(actualRequest, request); + assertTrue(actualRequest.getRequestTime() + .equals(request.getRequestTime())); + } + +} + diff --git a/apache-bval/pom.xml b/apache-bval/pom.xml index f8a3b8279d..5ddb1ecb59 100644 --- a/apache-bval/pom.xml +++ b/apache-bval/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 apache-bval apache-bval diff --git a/apache-bval/src/main/resources/logback.xml b/apache-bval/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-bval/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-cayenne/pom.xml b/apache-cayenne/pom.xml index fc16db3c81..591809d47f 100644 --- a/apache-cayenne/pom.xml +++ b/apache-cayenne/pom.xml @@ -28,12 +28,6 @@ runtime - - junit - junit - ${junit.version} - test - @@ -47,12 +41,8 @@ - UTF-8 - UTF-8 - 1.8 5.1.44 4.0.M5 - 4.12 diff --git a/apache-cayenne/src/main/resources/logback.xml b/apache-cayenne/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-cayenne/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationIntegrationTest.java b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationIntegrationTest.java deleted file mode 100644 index 546b8fe45c..0000000000 --- a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationIntegrationTest.java +++ /dev/null @@ -1,256 +0,0 @@ -package com.baeldung.apachecayenne; - -import com.baeldung.apachecayenne.persistent.Author; -import org.apache.cayenne.ObjectContext; -import org.apache.cayenne.QueryResponse; -import org.apache.cayenne.configuration.server.ServerRuntime; -import org.apache.cayenne.exp.Expression; -import org.apache.cayenne.exp.ExpressionFactory; -import org.apache.cayenne.query.*; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static junit.framework.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class CayenneAdvancedOperationIntegrationTest { - private static ObjectContext context = null; - - @BeforeClass - public static void setupTheCayenneContext() { - ServerRuntime cayenneRuntime = ServerRuntime.builder() - .addConfig("cayenne-project.xml") - .build(); - context = cayenneRuntime.newContext(); - } - - @Before - public void saveThreeAuthors() { - Author authorOne = context.newObject(Author.class); - authorOne.setName("Paul Xavier"); - Author authorTwo = context.newObject(Author.class); - authorTwo.setName("pAuL Smith"); - Author authorThree = context.newObject(Author.class); - authorThree.setName("Vicky Sarra"); - context.commitChanges(); - } - - @After - public void deleteAllAuthors() { - SQLTemplate deleteAuthors = new SQLTemplate(Author.class, "delete from author"); - context.performGenericQuery(deleteAuthors); - } - - @Test - public void givenAuthors_whenFindAllSQLTmplt_thenWeGetThreeAuthors() { - SQLTemplate select = new SQLTemplate(Author.class, "select * from Author"); - List authors = context.performQuery(select); - - assertEquals(authors.size(), 3); - } - - @Test - public void givenAuthors_whenFindByNameSQLTmplt_thenWeGetOneAuthor() { - SQLTemplate select = new SQLTemplate(Author.class, "select * from Author where name = 'Vicky Sarra'"); - List authors = context.performQuery(select); - Author author = authors.get(0); - - assertEquals(authors.size(), 1); - assertEquals(author.getName(), "Vicky Sarra"); - } - - @Test - public void givenAuthors_whenLikeSltQry_thenWeGetOneAuthor() { - Expression qualifier = ExpressionFactory.likeExp(Author.NAME.getName(), "Paul%"); - SelectQuery query = new SelectQuery(Author.class, qualifier); - List authorsTwo = context.performQuery(query); - - assertEquals(authorsTwo.size(), 1); - } - - @Test - public void givenAuthors_whenCtnsIgnorCaseSltQry_thenWeGetTwoAuthors() { - Expression qualifier = ExpressionFactory.containsIgnoreCaseExp(Author.NAME.getName(), "Paul"); - SelectQuery query = new SelectQuery(Author.class, qualifier); - List authors = context.performQuery(query); - - assertEquals(authors.size(), 2); - } - - @Test - public void givenAuthors_whenCtnsIgnorCaseEndsWSltQry_thenWeGetTwoAuthors() { - Expression qualifier = ExpressionFactory.containsIgnoreCaseExp(Author.NAME.getName(), "Paul") - .andExp(ExpressionFactory.endsWithExp(Author.NAME.getName(), "h")); - SelectQuery query = new SelectQuery(Author.class, qualifier); - List authors = context.performQuery(query); - - Author author = authors.get(0); - - assertEquals(authors.size(), 1); - assertEquals(author.getName(), "pAuL Smith"); - } - - @Test - public void givenAuthors_whenAscOrderingSltQry_thenWeGetOrderedAuthors() { - SelectQuery query = new SelectQuery(Author.class); - query.addOrdering(Author.NAME.asc()); - - List authors = query.select(context); - Author firstAuthor = authors.get(0); - - assertEquals(authors.size(), 3); - assertEquals(firstAuthor.getName(), "Paul Xavier"); - } - - @Test - public void givenAuthors_whenDescOrderingSltQry_thenWeGetOrderedAuthors() { - SelectQuery query = new SelectQuery(Author.class); - query.addOrdering(Author.NAME.desc()); - - List authors = query.select(context); - Author firstAuthor = authors.get(0); - - assertEquals(authors.size(), 3); - assertEquals(firstAuthor.getName(), "pAuL Smith"); - } - - @Test - public void givenAuthors_onContainsObjS_thenWeGetOneRecord() { - List authors = ObjectSelect.query(Author.class) - .where(Author.NAME.contains("Paul")) - .select(context); - - assertEquals(authors.size(), 1); - } - - @Test - public void givenAuthors_whenLikeObjS_thenWeGetTwoAuthors() { - List authors = ObjectSelect.query(Author.class) - .where(Author.NAME.likeIgnoreCase("Paul%")) - .select(context); - - assertEquals(authors.size(), 2); - } - - @Test - public void givenTwoAuthor_whenEndsWithObjS_thenWeGetOrderedAuthors() { - List authors = ObjectSelect.query(Author.class) - .where(Author.NAME.endsWith("Sarra")) - .select(context); - Author firstAuthor = authors.get(0); - - assertEquals(authors.size(), 1); - assertEquals(firstAuthor.getName(), "Vicky Sarra"); - } - - @Test - public void givenTwoAuthor_whenInObjS_thenWeGetAuthors() { - List names = Arrays.asList("Paul Xavier", "pAuL Smith", "Vicky Sarra"); - List authors = ObjectSelect.query(Author.class) - .where(Author.NAME.in(names)) - .select(context); - - assertEquals(authors.size(), 3); - } - - @Test - public void givenTwoAuthor_whenNinObjS_thenWeGetAuthors() { - List names = Arrays.asList("Paul Xavier", "pAuL Smith"); - List authors = ObjectSelect.query(Author.class) - .where(Author.NAME.nin(names)) - .select(context); - Author author = authors.get(0); - - assertEquals(authors.size(), 1); - assertEquals(author.getName(), "Vicky Sarra"); - } - - @Test - public void givenTwoAuthor_whenIsNotNullObjS_thenWeGetAuthors() { - List authors = ObjectSelect.query(Author.class) - .where(Author.NAME.isNotNull()) - .select(context); - - assertEquals(authors.size(), 3); - } - - @Test - public void givenAuthors_whenFindAllEJBQL_thenWeGetThreeAuthors() { - EJBQLQuery query = new EJBQLQuery("select a FROM Author a"); - List authors = context.performQuery(query); - - assertEquals(authors.size(), 3); - } - - @Test - public void givenAuthors_whenFindByNameEJBQL_thenWeGetOneAuthor() { - EJBQLQuery query = new EJBQLQuery("select a FROM Author a WHERE a.name = 'Vicky Sarra'"); - List authors = context.performQuery(query); - Author author = authors.get(0); - - assertEquals(authors.size(), 1); - assertEquals(author.getName(), "Vicky Sarra"); - } - - @Test - public void givenAuthors_whenUpdadingByNameEJBQL_thenWeGetTheUpdatedAuthor() { - EJBQLQuery query = new EJBQLQuery("UPDATE Author AS a SET a.name = 'Vicky Edison' WHERE a.name = 'Vicky Sarra'"); - QueryResponse queryResponse = context.performGenericQuery(query); - - EJBQLQuery queryUpdatedAuthor = new EJBQLQuery("select a FROM Author a WHERE a.name = 'Vicky Edison'"); - List authors = context.performQuery(queryUpdatedAuthor); - Author author = authors.get(0); - - assertNotNull(author); - } - - @Test - public void givenAuthors_whenSeletingNamesEJBQL_thenWeGetListWithSizeThree() { - String [] args = {"Paul Xavier", "pAuL Smith", "Vicky Sarra"}; - List names = Arrays.asList(args); - EJBQLQuery query = new EJBQLQuery("select a.name FROM Author a"); - List nameList = context.performQuery(query); - - Collections.sort(names); - Collections.sort(nameList); - - assertEquals(names.size(), 3); - assertEquals(nameList.size(), 3); - assertEquals(names, nameList); - } - - @Test - public void givenAuthors_whenDeletingAllWithEJB_thenWeGetNoAuthor() { - EJBQLQuery deleteQuery = new EJBQLQuery("delete FROM Author"); - EJBQLQuery findAllQuery = new EJBQLQuery("select a FROM Author a"); - - context.performQuery(deleteQuery); - List objects = context.performQuery(findAllQuery); - - assertEquals(objects.size(), 0); - } - - @Test - public void givenAuthors_whenInsertingSQLExec_thenWeGetNewAuthor() { - int inserted = SQLExec - .query("INSERT INTO Author (name) VALUES ('Baeldung')") - .update(context); - - assertEquals(inserted, 1); - } - - @Test - public void givenAuthors_whenUpdatingSQLExec_thenItsUpdated() { - int updated = SQLExec - .query("UPDATE Author SET name = 'Baeldung' WHERE name = 'Vicky Sarra'") - .update(context); - - assertEquals(updated, 1); - } -} diff --git a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationLiveTest.java b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationLiveTest.java new file mode 100644 index 0000000000..b54b62ca02 --- /dev/null +++ b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationLiveTest.java @@ -0,0 +1,256 @@ +package com.baeldung.apachecayenne; + +import com.baeldung.apachecayenne.persistent.Author; +import org.apache.cayenne.ObjectContext; +import org.apache.cayenne.QueryResponse; +import org.apache.cayenne.configuration.server.ServerRuntime; +import org.apache.cayenne.exp.Expression; +import org.apache.cayenne.exp.ExpressionFactory; +import org.apache.cayenne.query.*; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static junit.framework.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class CayenneAdvancedOperationLiveTest { + private static ObjectContext context = null; + + @BeforeClass + public static void setupTheCayenneContext() { + ServerRuntime cayenneRuntime = ServerRuntime.builder() + .addConfig("cayenne-project.xml") + .build(); + context = cayenneRuntime.newContext(); + } + + @Before + public void saveThreeAuthors() { + Author authorOne = context.newObject(Author.class); + authorOne.setName("Paul Xavier"); + Author authorTwo = context.newObject(Author.class); + authorTwo.setName("pAuL Smith"); + Author authorThree = context.newObject(Author.class); + authorThree.setName("Vicky Sarra"); + context.commitChanges(); + } + + @After + public void deleteAllAuthors() { + SQLTemplate deleteAuthors = new SQLTemplate(Author.class, "delete from author"); + context.performGenericQuery(deleteAuthors); + } + + @Test + public void givenAuthors_whenFindAllSQLTmplt_thenWeGetThreeAuthors() { + SQLTemplate select = new SQLTemplate(Author.class, "select * from Author"); + List authors = context.performQuery(select); + + assertEquals(authors.size(), 3); + } + + @Test + public void givenAuthors_whenFindByNameSQLTmplt_thenWeGetOneAuthor() { + SQLTemplate select = new SQLTemplate(Author.class, "select * from Author where name = 'Vicky Sarra'"); + List authors = context.performQuery(select); + Author author = authors.get(0); + + assertEquals(authors.size(), 1); + assertEquals(author.getName(), "Vicky Sarra"); + } + + @Test + public void givenAuthors_whenLikeSltQry_thenWeGetOneAuthor() { + Expression qualifier = ExpressionFactory.likeExp(Author.NAME.getName(), "Paul%"); + SelectQuery query = new SelectQuery(Author.class, qualifier); + List authorsTwo = context.performQuery(query); + + assertEquals(authorsTwo.size(), 1); + } + + @Test + public void givenAuthors_whenCtnsIgnorCaseSltQry_thenWeGetTwoAuthors() { + Expression qualifier = ExpressionFactory.containsIgnoreCaseExp(Author.NAME.getName(), "Paul"); + SelectQuery query = new SelectQuery(Author.class, qualifier); + List authors = context.performQuery(query); + + assertEquals(authors.size(), 2); + } + + @Test + public void givenAuthors_whenCtnsIgnorCaseEndsWSltQry_thenWeGetTwoAuthors() { + Expression qualifier = ExpressionFactory.containsIgnoreCaseExp(Author.NAME.getName(), "Paul") + .andExp(ExpressionFactory.endsWithExp(Author.NAME.getName(), "h")); + SelectQuery query = new SelectQuery(Author.class, qualifier); + List authors = context.performQuery(query); + + Author author = authors.get(0); + + assertEquals(authors.size(), 1); + assertEquals(author.getName(), "pAuL Smith"); + } + + @Test + public void givenAuthors_whenAscOrderingSltQry_thenWeGetOrderedAuthors() { + SelectQuery query = new SelectQuery(Author.class); + query.addOrdering(Author.NAME.asc()); + + List authors = query.select(context); + Author firstAuthor = authors.get(0); + + assertEquals(authors.size(), 3); + assertEquals(firstAuthor.getName(), "Paul Xavier"); + } + + @Test + public void givenAuthors_whenDescOrderingSltQry_thenWeGetOrderedAuthors() { + SelectQuery query = new SelectQuery(Author.class); + query.addOrdering(Author.NAME.desc()); + + List authors = query.select(context); + Author firstAuthor = authors.get(0); + + assertEquals(authors.size(), 3); + assertEquals(firstAuthor.getName(), "pAuL Smith"); + } + + @Test + public void givenAuthors_onContainsObjS_thenWeGetOneRecord() { + List authors = ObjectSelect.query(Author.class) + .where(Author.NAME.contains("Paul")) + .select(context); + + assertEquals(authors.size(), 1); + } + + @Test + public void givenAuthors_whenLikeObjS_thenWeGetTwoAuthors() { + List authors = ObjectSelect.query(Author.class) + .where(Author.NAME.likeIgnoreCase("Paul%")) + .select(context); + + assertEquals(authors.size(), 2); + } + + @Test + public void givenTwoAuthor_whenEndsWithObjS_thenWeGetOrderedAuthors() { + List authors = ObjectSelect.query(Author.class) + .where(Author.NAME.endsWith("Sarra")) + .select(context); + Author firstAuthor = authors.get(0); + + assertEquals(authors.size(), 1); + assertEquals(firstAuthor.getName(), "Vicky Sarra"); + } + + @Test + public void givenTwoAuthor_whenInObjS_thenWeGetAuthors() { + List names = Arrays.asList("Paul Xavier", "pAuL Smith", "Vicky Sarra"); + List authors = ObjectSelect.query(Author.class) + .where(Author.NAME.in(names)) + .select(context); + + assertEquals(authors.size(), 3); + } + + @Test + public void givenTwoAuthor_whenNinObjS_thenWeGetAuthors() { + List names = Arrays.asList("Paul Xavier", "pAuL Smith"); + List authors = ObjectSelect.query(Author.class) + .where(Author.NAME.nin(names)) + .select(context); + Author author = authors.get(0); + + assertEquals(authors.size(), 1); + assertEquals(author.getName(), "Vicky Sarra"); + } + + @Test + public void givenTwoAuthor_whenIsNotNullObjS_thenWeGetAuthors() { + List authors = ObjectSelect.query(Author.class) + .where(Author.NAME.isNotNull()) + .select(context); + + assertEquals(authors.size(), 3); + } + + @Test + public void givenAuthors_whenFindAllEJBQL_thenWeGetThreeAuthors() { + EJBQLQuery query = new EJBQLQuery("select a FROM Author a"); + List authors = context.performQuery(query); + + assertEquals(authors.size(), 3); + } + + @Test + public void givenAuthors_whenFindByNameEJBQL_thenWeGetOneAuthor() { + EJBQLQuery query = new EJBQLQuery("select a FROM Author a WHERE a.name = 'Vicky Sarra'"); + List authors = context.performQuery(query); + Author author = authors.get(0); + + assertEquals(authors.size(), 1); + assertEquals(author.getName(), "Vicky Sarra"); + } + + @Test + public void givenAuthors_whenUpdadingByNameEJBQL_thenWeGetTheUpdatedAuthor() { + EJBQLQuery query = new EJBQLQuery("UPDATE Author AS a SET a.name = 'Vicky Edison' WHERE a.name = 'Vicky Sarra'"); + QueryResponse queryResponse = context.performGenericQuery(query); + + EJBQLQuery queryUpdatedAuthor = new EJBQLQuery("select a FROM Author a WHERE a.name = 'Vicky Edison'"); + List authors = context.performQuery(queryUpdatedAuthor); + Author author = authors.get(0); + + assertNotNull(author); + } + + @Test + public void givenAuthors_whenSeletingNamesEJBQL_thenWeGetListWithSizeThree() { + String [] args = {"Paul Xavier", "pAuL Smith", "Vicky Sarra"}; + List names = Arrays.asList(args); + EJBQLQuery query = new EJBQLQuery("select a.name FROM Author a"); + List nameList = context.performQuery(query); + + Collections.sort(names); + Collections.sort(nameList); + + assertEquals(names.size(), 3); + assertEquals(nameList.size(), 3); + assertEquals(names, nameList); + } + + @Test + public void givenAuthors_whenDeletingAllWithEJB_thenWeGetNoAuthor() { + EJBQLQuery deleteQuery = new EJBQLQuery("delete FROM Author"); + EJBQLQuery findAllQuery = new EJBQLQuery("select a FROM Author a"); + + context.performQuery(deleteQuery); + List objects = context.performQuery(findAllQuery); + + assertEquals(objects.size(), 0); + } + + @Test + public void givenAuthors_whenInsertingSQLExec_thenWeGetNewAuthor() { + int inserted = SQLExec + .query("INSERT INTO Author (name) VALUES ('Baeldung')") + .update(context); + + assertEquals(inserted, 1); + } + + @Test + public void givenAuthors_whenUpdatingSQLExec_thenItsUpdated() { + int updated = SQLExec + .query("UPDATE Author SET name = 'Baeldung' WHERE name = 'Vicky Sarra'") + .update(context); + + assertEquals(updated, 1); + } +} diff --git a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationIntegrationTest.java b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationIntegrationTest.java deleted file mode 100644 index 85f06d5538..0000000000 --- a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationIntegrationTest.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.baeldung.apachecayenne; - -import com.baeldung.apachecayenne.persistent.Article; -import com.baeldung.apachecayenne.persistent.Author; -import org.apache.cayenne.ObjectContext; -import org.apache.cayenne.configuration.server.ServerRuntime; -import org.apache.cayenne.query.ObjectSelect; -import org.apache.cayenne.query.SQLTemplate; -import org.junit.After; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.util.List; - -import static junit.framework.Assert.assertEquals; -import static org.junit.Assert.assertNull; - - -public class CayenneOperationIntegrationTest { - private static ObjectContext context = null; - - @BeforeClass - public static void setupTheCayenneContext() { - ServerRuntime cayenneRuntime = ServerRuntime.builder() - .addConfig("cayenne-project.xml") - .build(); - context = cayenneRuntime.newContext(); - } - - @After - public void deleteAllRecords() { - SQLTemplate deleteArticles = new SQLTemplate(Article.class, "delete from article"); - SQLTemplate deleteAuthors = new SQLTemplate(Author.class, "delete from author"); - - context.performGenericQuery(deleteArticles); - context.performGenericQuery(deleteAuthors); - } - - @Test - public void givenAuthor_whenInsert_thenWeGetOneRecordInTheDatabase() { - Author author = context.newObject(Author.class); - author.setName("Paul"); - - context.commitChanges(); - - long records = ObjectSelect.dataRowQuery(Author.class).selectCount(context); - assertEquals(1, records); - } - - @Test - public void givenAuthor_whenInsert_andQueryByFirstName_thenWeGetTheAuthor() { - Author author = context.newObject(Author.class); - author.setName("Paul"); - - context.commitChanges(); - - Author expectedAuthor = ObjectSelect.query(Author.class) - .where(Author.NAME.eq("Paul")) - .selectOne(context); - - assertEquals("Paul", expectedAuthor.getName()); - } - - @Test - public void givenTwoAuthor_whenInsert_andQueryAll_thenWeGetTwoAuthors() { - Author firstAuthor = context.newObject(Author.class); - firstAuthor.setName("Paul"); - - Author secondAuthor = context.newObject(Author.class); - secondAuthor.setName("Ludovic"); - - context.commitChanges(); - - List authors = ObjectSelect.query(Author.class).select(context); - assertEquals(2, authors.size()); - } - - @Test - public void givenAuthor_whenUpdating_thenWeGetAnUpatedeAuthor() { - Author author = context.newObject(Author.class); - author.setName("Paul"); - context.commitChanges(); - - Author expectedAuthor = ObjectSelect.query(Author.class) - .where(Author.NAME.eq("Paul")) - .selectOne(context); - expectedAuthor.setName("Garcia"); - context.commitChanges(); - - assertEquals(author.getName(), expectedAuthor.getName()); - } - - @Test - public void givenAuthor_whenDeleting_thenWeLostHisDetails() { - Author author = context.newObject(Author.class); - author.setName("Paul"); - context.commitChanges(); - - Author savedAuthor = ObjectSelect.query(Author.class) - .where(Author.NAME.eq("Paul")).selectOne(context); - if(savedAuthor != null) { - context.deleteObjects(author); - context.commitChanges(); - } - - Author expectedAuthor = ObjectSelect.query(Author.class) - .where(Author.NAME.eq("Paul")).selectOne(context); - assertNull(expectedAuthor); - } - - @Test - public void givenAuthor_whenAttachingToArticle_thenTheRelationIsMade() { - Author author = context.newObject(Author.class); - author.setName("Paul"); - - Article article = context.newObject(Article.class); - article.setTitle("My post title"); - article.setContent("The content"); - article.setAuthor(author); - - context.commitChanges(); - - Author expectedAuthor = ObjectSelect.query(Author.class) - .where(Author.NAME.eq("Paul")) - .selectOne(context); - - Article expectedArticle = (expectedAuthor.getArticles()).get(0); - assertEquals(article.getTitle(), expectedArticle.getTitle()); - } - -} diff --git a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationLiveTest.java b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationLiveTest.java new file mode 100644 index 0000000000..e6ca4a3634 --- /dev/null +++ b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationLiveTest.java @@ -0,0 +1,131 @@ +package com.baeldung.apachecayenne; + +import com.baeldung.apachecayenne.persistent.Article; +import com.baeldung.apachecayenne.persistent.Author; +import org.apache.cayenne.ObjectContext; +import org.apache.cayenne.configuration.server.ServerRuntime; +import org.apache.cayenne.query.ObjectSelect; +import org.apache.cayenne.query.SQLTemplate; +import org.junit.After; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +import static junit.framework.Assert.assertEquals; +import static org.junit.Assert.assertNull; + + +public class CayenneOperationLiveTest { + private static ObjectContext context = null; + + @BeforeClass + public static void setupTheCayenneContext() { + ServerRuntime cayenneRuntime = ServerRuntime.builder() + .addConfig("cayenne-project.xml") + .build(); + context = cayenneRuntime.newContext(); + } + + @After + public void deleteAllRecords() { + SQLTemplate deleteArticles = new SQLTemplate(Article.class, "delete from article"); + SQLTemplate deleteAuthors = new SQLTemplate(Author.class, "delete from author"); + + context.performGenericQuery(deleteArticles); + context.performGenericQuery(deleteAuthors); + } + + @Test + public void givenAuthor_whenInsert_thenWeGetOneRecordInTheDatabase() { + Author author = context.newObject(Author.class); + author.setName("Paul"); + + context.commitChanges(); + + long records = ObjectSelect.dataRowQuery(Author.class).selectCount(context); + assertEquals(1, records); + } + + @Test + public void givenAuthor_whenInsert_andQueryByFirstName_thenWeGetTheAuthor() { + Author author = context.newObject(Author.class); + author.setName("Paul"); + + context.commitChanges(); + + Author expectedAuthor = ObjectSelect.query(Author.class) + .where(Author.NAME.eq("Paul")) + .selectOne(context); + + assertEquals("Paul", expectedAuthor.getName()); + } + + @Test + public void givenTwoAuthor_whenInsert_andQueryAll_thenWeGetTwoAuthors() { + Author firstAuthor = context.newObject(Author.class); + firstAuthor.setName("Paul"); + + Author secondAuthor = context.newObject(Author.class); + secondAuthor.setName("Ludovic"); + + context.commitChanges(); + + List authors = ObjectSelect.query(Author.class).select(context); + assertEquals(2, authors.size()); + } + + @Test + public void givenAuthor_whenUpdating_thenWeGetAnUpatedeAuthor() { + Author author = context.newObject(Author.class); + author.setName("Paul"); + context.commitChanges(); + + Author expectedAuthor = ObjectSelect.query(Author.class) + .where(Author.NAME.eq("Paul")) + .selectOne(context); + expectedAuthor.setName("Garcia"); + context.commitChanges(); + + assertEquals(author.getName(), expectedAuthor.getName()); + } + + @Test + public void givenAuthor_whenDeleting_thenWeLostHisDetails() { + Author author = context.newObject(Author.class); + author.setName("Paul"); + context.commitChanges(); + + Author savedAuthor = ObjectSelect.query(Author.class) + .where(Author.NAME.eq("Paul")).selectOne(context); + if(savedAuthor != null) { + context.deleteObjects(author); + context.commitChanges(); + } + + Author expectedAuthor = ObjectSelect.query(Author.class) + .where(Author.NAME.eq("Paul")).selectOne(context); + assertNull(expectedAuthor); + } + + @Test + public void givenAuthor_whenAttachingToArticle_thenTheRelationIsMade() { + Author author = context.newObject(Author.class); + author.setName("Paul"); + + Article article = context.newObject(Article.class); + article.setTitle("My post title"); + article.setContent("The content"); + article.setAuthor(author); + + context.commitChanges(); + + Author expectedAuthor = ObjectSelect.query(Author.class) + .where(Author.NAME.eq("Paul")) + .selectOne(context); + + Article expectedArticle = (expectedAuthor.getArticles()).get(0); + assertEquals(article.getTitle(), expectedArticle.getTitle()); + } + +} diff --git a/apache-curator/pom.xml b/apache-curator/pom.xml index d867d7e74b..ac10811e7a 100644 --- a/apache-curator/pom.xml +++ b/apache-curator/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 apache-curator 0.0.1-SNAPSHOT diff --git a/apache-curator/src/main/resources/logback.xml b/apache-curator/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-curator/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/BaseManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/BaseManualTest.java new file mode 100644 index 0000000000..5722228b26 --- /dev/null +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/BaseManualTest.java @@ -0,0 +1,22 @@ +package com.baeldung.apache.curator; + +import org.apache.curator.RetryPolicy; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.retry.RetryNTimes; +import org.junit.Before; + +public abstract class BaseManualTest { + + @Before + public void setup() { + org.apache.log4j.BasicConfigurator.configure(); + } + + protected CuratorFramework newClient() { + int sleepMsBetweenRetries = 100; + int maxRetries = 3; + RetryPolicy retryPolicy = new RetryNTimes(maxRetries, sleepMsBetweenRetries); + return CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy); + } +} diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/BaseTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/BaseTest.java deleted file mode 100644 index cfac3ee3f2..0000000000 --- a/apache-curator/src/test/java/com/baeldung/apache/curator/BaseTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.apache.curator; - -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.RetryNTimes; -import org.junit.Before; - -public abstract class BaseTest { - - @Before - public void setup() { - org.apache.log4j.BasicConfigurator.configure(); - } - - protected CuratorFramework newClient() { - int sleepMsBetweenRetries = 100; - int maxRetries = 3; - RetryPolicy retryPolicy = new RetryNTimes(maxRetries, sleepMsBetweenRetries); - return CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy); - } -} diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java index d02ef8131d..1a6fe6ccd0 100644 --- a/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java @@ -12,9 +12,9 @@ import org.apache.curator.framework.CuratorFramework; import org.apache.curator.x.async.AsyncCuratorFramework; import org.junit.Test; -import com.baeldung.apache.curator.BaseTest; +import com.baeldung.apache.curator.BaseManualTest; -public class ConfigurationManagementManualTest extends BaseTest { +public class ConfigurationManagementManualTest extends BaseManualTest { private static final String KEY_FORMAT = "/%s"; diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java index 4400c1d1aa..d7caa18ce9 100644 --- a/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java @@ -11,9 +11,9 @@ import org.apache.curator.x.async.modeled.ModeledFramework; import org.apache.curator.x.async.modeled.ZPath; import org.junit.Test; -import com.baeldung.apache.curator.BaseTest; +import com.baeldung.apache.curator.BaseManualTest; -public class ModelTypedExamplesManualTest extends BaseTest { +public class ModelTypedExamplesManualTest extends BaseManualTest { @Test public void givenPath_whenStoreAModel_thenNodesAreCreated() diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java index 04f4104e6b..0c5890ad59 100644 --- a/apache-curator/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java @@ -10,9 +10,9 @@ import org.apache.curator.framework.recipes.shared.SharedCount; import org.apache.curator.framework.state.ConnectionState; import org.junit.Test; -import com.baeldung.apache.curator.BaseTest; +import com.baeldung.apache.curator.BaseManualTest; -public class RecipesManualTest extends BaseTest { +public class RecipesManualTest extends BaseManualTest { @Test public void givenRunningZookeeper_whenUsingLeaderElection_thenNoErrors() { diff --git a/apache-cxf/README.md b/apache-cxf/README.md index 1e66ce5da8..d03999dce3 100644 --- a/apache-cxf/README.md +++ b/apache-cxf/README.md @@ -3,3 +3,4 @@ - [Apache CXF Support for RESTful Web Services](http://www.baeldung.com/apache-cxf-rest-api) - [A Guide to Apache CXF with Spring](http://www.baeldung.com/apache-cxf-with-spring) - [Introduction to Apache CXF](http://www.baeldung.com/introduction-to-apache-cxf) +- [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse) diff --git a/apache-cxf/cxf-aegis/pom.xml b/apache-cxf/cxf-aegis/pom.xml index 338860472c..b7e9e426a2 100644 --- a/apache-cxf/cxf-aegis/pom.xml +++ b/apache-cxf/cxf-aegis/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 cxf-aegis @@ -17,8 +17,4 @@ - - 3.1.8 - - diff --git a/apache-cxf/cxf-aegis/src/main/resources/logback.xml b/apache-cxf/cxf-aegis/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-cxf/cxf-aegis/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-cxf/cxf-introduction/pom.xml b/apache-cxf/cxf-introduction/pom.xml index 3c44734733..a9e82c16b3 100644 --- a/apache-cxf/cxf-introduction/pom.xml +++ b/apache-cxf/cxf-introduction/pom.xml @@ -1,7 +1,7 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 cxf-introduction @@ -36,9 +36,4 @@ - - 3.1.8 - 2.19.1 - - diff --git a/apache-cxf/cxf-introduction/src/main/resources/logback.xml b/apache-cxf/cxf-introduction/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-cxf/cxf-introduction/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/pom.xml b/apache-cxf/cxf-jaxrs-implementation/pom.xml index ce35d67948..89acbdf1bd 100644 --- a/apache-cxf/cxf-jaxrs-implementation/pom.xml +++ b/apache-cxf/cxf-jaxrs-implementation/pom.xml @@ -1,7 +1,7 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 cxf-jaxrs-implementation @@ -48,10 +48,7 @@ - UTF-8 - 3.1.8 4.5.2 - 2.19.1 diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/logback.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-cxf/cxf-spring/pom.xml b/apache-cxf/cxf-spring/pom.xml index a06165f4ad..31e75e7cdd 100644 --- a/apache-cxf/cxf-spring/pom.xml +++ b/apache-cxf/cxf-spring/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 cxf-spring war @@ -101,11 +101,7 @@ - 3.1.8 4.3.4.RELEASE - 3.1.0 - 2.6 - 2.19.1 1.6.1 diff --git a/apache-cxf/cxf-spring/src/main/resources/logback.xml b/apache-cxf/cxf-spring/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-cxf/cxf-spring/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-cxf/pom.xml b/apache-cxf/pom.xml index 5a864b18ef..8918fd4450 100644 --- a/apache-cxf/pom.xml +++ b/apache-cxf/pom.xml @@ -17,6 +17,7 @@ cxf-spring cxf-jaxrs-implementation cxf-aegis + sse-jaxrs @@ -33,7 +34,7 @@ - 1.5.0 + 3.1.8 diff --git a/apache-cxf/sse-jaxrs/pom.xml b/apache-cxf/sse-jaxrs/pom.xml new file mode 100644 index 0000000000..d4b6c19d03 --- /dev/null +++ b/apache-cxf/sse-jaxrs/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + + sse-jaxrs + pom + + + com.baeldung + apache-cxf + 0.0.1-SNAPSHOT + + + + sse-jaxrs-server + sse-jaxrs-client + + + diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml new file mode 100644 index 0000000000..0f5406fbc7 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + + com.baeldung + sse-jaxrs + 0.0.1-SNAPSHOT + + + sse-jaxrs-client + + + 3.2.0 + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + singleEvent + + java + + + com.baeldung.sse.jaxrs.client.SseClientApp + + + + broadcast + + java + + + com.baeldung.sse.jaxrs.client.SseClientBroadcastApp + + + + + + + + + + org.apache.cxf + cxf-rt-rs-client + ${cxf-version} + + + org.apache.cxf + cxf-rt-rs-sse + ${cxf-version} + + + + diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java new file mode 100644 index 0000000000..5d42b3a243 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java @@ -0,0 +1,48 @@ +package com.baeldung.sse.jaxrs.client; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.sse.InboundSseEvent; +import javax.ws.rs.sse.SseEventSource; +import java.util.function.Consumer; + +public class SseClientApp { + + private static final String url = "http://127.0.0.1:9080/sse-jaxrs-server/sse/stock/prices"; + + public static void main(String... args) throws Exception { + + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(url); + try (SseEventSource eventSource = SseEventSource.target(target).build()) { + + eventSource.register(onEvent, onError, onComplete); + eventSource.open(); + + //Consuming events for one hour + Thread.sleep(60 * 60 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + client.close(); + System.out.println("End"); + } + + // A new event is received + private static Consumer onEvent = (inboundSseEvent) -> { + String data = inboundSseEvent.readData(); + System.out.println(data); + }; + + //Error + private static Consumer onError = (throwable) -> { + throwable.printStackTrace(); + }; + + //Connection close and there is nothing to receive + private static Runnable onComplete = () -> { + System.out.println("Done!"); + }; + +} diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java new file mode 100644 index 0000000000..9afc187a6d --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java @@ -0,0 +1,52 @@ +package com.baeldung.sse.jaxrs.client; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.sse.InboundSseEvent; +import javax.ws.rs.sse.SseEventSource; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +public class SseClientBroadcastApp { + + private static final String subscribeUrl = "http://localhost:9080/sse-jaxrs-server/sse/stock/subscribe"; + + + public static void main(String... args) throws Exception { + + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(subscribeUrl); + try (final SseEventSource eventSource = SseEventSource.target(target) + .reconnectingEvery(5, TimeUnit.SECONDS) + .build()) { + eventSource.register(onEvent, onError, onComplete); + eventSource.open(); + System.out.println("Wainting for incoming event ..."); + + //Consuming events for one hour + Thread.sleep(60 * 60 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + client.close(); + System.out.println("End"); + } + + // A new event is received + private static Consumer onEvent = (inboundSseEvent) -> { + String data = inboundSseEvent.readData(); + System.out.println(data); + }; + + //Error + private static Consumer onError = (throwable) -> { + throwable.printStackTrace(); + }; + + //Connection close and there is nothing to receive + private static Runnable onComplete = () -> { + System.out.println("Done!"); + }; + +} diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml new file mode 100644 index 0000000000..2e82dc3829 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml @@ -0,0 +1,85 @@ + + + 4.0.0 + + + com.baeldung + sse-jaxrs + 0.0.1-SNAPSHOT + + + sse-jaxrs-server + war + + + 2.4.2 + false + 18.0.0.2 + + + + ${project.artifactId} + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + ${liberty-maven-plugin.version} + + + io.openliberty + openliberty-webProfile8 + ${openliberty-version} + zip + + project + true + src/main/liberty/config/server.xml + + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + + + + + + javax.ws.rs + javax.ws.rs-api + 2.1 + provided + + + javax.enterprise + cdi-api + 2.0 + provided + + + javax.json.bind + javax.json.bind-api + 1.0 + provided + + + + + diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java new file mode 100644 index 0000000000..058d19f045 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java @@ -0,0 +1,8 @@ +package com.baeldung.sse.jaxrs; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("sse") +public class AppConfig extends Application { +} diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java new file mode 100644 index 0000000000..1f60168a1b --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java @@ -0,0 +1,119 @@ +package com.baeldung.sse.jaxrs; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.sse.OutboundSseEvent; +import javax.ws.rs.sse.Sse; +import javax.ws.rs.sse.SseBroadcaster; +import javax.ws.rs.sse.SseEventSink; + +@ApplicationScoped +@Path("stock") +public class SseResource { + + @Inject + private StockService stockService; + + private Sse sse; + private SseBroadcaster sseBroadcaster; + private OutboundSseEvent.Builder eventBuilder; + + @Context + public void setSse(Sse sse) { + this.sse = sse; + this.eventBuilder = sse.newEventBuilder(); + this.sseBroadcaster = sse.newBroadcaster(); + } + + @GET + @Path("prices") + @Produces("text/event-stream") + public void getStockPrices(@Context SseEventSink sseEventSink, + @HeaderParam(HttpHeaders.LAST_EVENT_ID_HEADER) @DefaultValue("-1") int lastReceivedId) { + + int lastEventId = 1; + if (lastReceivedId != -1) { + lastEventId = ++lastReceivedId; + } + boolean running = true; + while (running) { + Stock stock = stockService.getNextTransaction(lastEventId); + if (stock != null) { + OutboundSseEvent sseEvent = this.eventBuilder + .name("stock") + .id(String.valueOf(lastEventId)) + .mediaType(MediaType.APPLICATION_JSON_TYPE) + .data(Stock.class, stock) + .reconnectDelay(3000) + .comment("price change") + .build(); + sseEventSink.send(sseEvent); + lastEventId++; + } + //Simulate connection close + if (lastEventId % 5 == 0) { + sseEventSink.close(); + break; + } + + try { + //Wait 5 seconds + Thread.sleep(5 * 1000); + } catch (InterruptedException ex) { + // ... + } + //Simulatae a while boucle break + running = lastEventId <= 2000; + } + sseEventSink.close(); + } + + @GET + @Path("subscribe") + @Produces(MediaType.SERVER_SENT_EVENTS) + public void listen(@Context SseEventSink sseEventSink) { + sseEventSink.send(sse.newEvent("Welcome !")); + this.sseBroadcaster.register(sseEventSink); + sseEventSink.send(sse.newEvent("You are registred !")); + } + + @GET + @Path("publish") + public void broadcast() { + Runnable r = new Runnable() { + @Override + public void run() { + int lastEventId = 0; + boolean running = true; + while (running) { + lastEventId++; + Stock stock = stockService.getNextTransaction(lastEventId); + if (stock != null) { + OutboundSseEvent sseEvent = eventBuilder + .name("stock") + .id(String.valueOf(lastEventId)) + .mediaType(MediaType.APPLICATION_JSON_TYPE) + .data(Stock.class, stock) + .reconnectDelay(3000) + .comment("price change") + .build(); + sseBroadcaster.broadcast(sseEvent); + } + try { + //Wait 5 seconds + Thread.currentThread().sleep(5 * 1000); + } catch (InterruptedException ex) { + // ... + } + //Simulatae a while boucle break + running = lastEventId <= 2000; + } + } + }; + new Thread(r).start(); + } +} diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java new file mode 100644 index 0000000000..a186b32771 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java @@ -0,0 +1,50 @@ +package com.baeldung.sse.jaxrs; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +public class Stock { + private Integer id; + private String name; + private BigDecimal price; + LocalDateTime dateTime; + + public Stock(Integer id, String name, BigDecimal price, LocalDateTime dateTime) { + this.id = id; + this.name = name; + this.price = price; + this.dateTime = dateTime; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public LocalDateTime getDateTime() { + return dateTime; + } + + public void setDateTime(LocalDateTime dateTime) { + this.dateTime = dateTime; + } +} diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java new file mode 100644 index 0000000000..15818ead5d --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java @@ -0,0 +1,78 @@ +package com.baeldung.sse.jaxrs; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.context.Initialized; +import javax.enterprise.event.Event; +import javax.enterprise.event.Observes; +import javax.inject.Inject; +import javax.inject.Named; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Random; +import java.util.concurrent.atomic.AtomicInteger; + +@ApplicationScoped +@Named +public class StockService { + + private static final BigDecimal UP = BigDecimal.valueOf(1.05f); + private static final BigDecimal DOWN = BigDecimal.valueOf(0.95f); + + List stockNames = Arrays.asList("GOOG", "IBM", "MS", "GOOG", "YAHO"); + List stocksDB = new ArrayList<>(); + private AtomicInteger counter = new AtomicInteger(0); + + public void init(@Observes @Initialized(ApplicationScoped.class) Object init) { + //Open price + System.out.println("@Start Init ..."); + stockNames.forEach(stockName -> { + stocksDB.add(new Stock(counter.incrementAndGet(), stockName, generateOpenPrice(), LocalDateTime.now())); + }); + + Runnable runnable = new Runnable() { + @Override + public void run() { + //Simulate Change price and put every x seconds + while (true) { + int indx = new Random().nextInt(stockNames.size()); + String stockName = stockNames.get(indx); + BigDecimal price = getLastPrice(stockName); + BigDecimal newprice = changePrice(price); + Stock stock = new Stock(counter.incrementAndGet(), stockName, newprice, LocalDateTime.now()); + stocksDB.add(stock); + + int r = new Random().nextInt(30); + try { + Thread.currentThread().sleep(r*1000); + } catch (InterruptedException ex) { + // ... + } + } + } + }; + new Thread(runnable).start(); + System.out.println("@End Init ..."); + } + + public Stock getNextTransaction(Integer lastEventId) { + return stocksDB.stream().filter(s -> s.getId().equals(lastEventId)).findFirst().orElse(null); + } + + BigDecimal generateOpenPrice() { + float min = 70; + float max = 120; + return BigDecimal.valueOf(min + new Random().nextFloat() * (max - min)).setScale(4,RoundingMode.CEILING); + } + + BigDecimal changePrice(BigDecimal price) { + return Math.random() >= 0.5 ? price.multiply(UP).setScale(4,RoundingMode.CEILING) : price.multiply(DOWN).setScale(4,RoundingMode.CEILING); + } + + private BigDecimal getLastPrice(String stockName) { + return stocksDB.stream().filter(stock -> stock.getName().equals(stockName)).findFirst().get().getPrice(); + } +} diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..9bf66d7795 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml @@ -0,0 +1,7 @@ + + + jaxrs-2.1 + cdi-2.0 + + + diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..4f0b3cdeeb --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml @@ -0,0 +1,6 @@ + + \ No newline at end of file diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..b4b8121fdd --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,11 @@ + + + Hello Servlet + + + index.html + + + diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html new file mode 100644 index 0000000000..9015a7a32c --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html @@ -0,0 +1 @@ +index diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html new file mode 100644 index 0000000000..5a46e2a5d3 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html @@ -0,0 +1,38 @@ + + + + Server-Sent Event Broadcasting + + +

Stock prices :

+
+
    +
+
+ + + \ No newline at end of file diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse.html b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse.html new file mode 100644 index 0000000000..8fddae4717 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse.html @@ -0,0 +1,38 @@ + + + + Server-Sent Event + + +

Stock prices :

+
+
    +
+
+ + + \ No newline at end of file diff --git a/apache-fop/pom.xml b/apache-fop/pom.xml index d0c6984757..879eb4f111 100644 --- a/apache-fop/pom.xml +++ b/apache-fop/pom.xml @@ -1,5 +1,5 @@ + 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 apache-fop diff --git a/apache-fop/src/main/resources/logback.xml b/apache-fop/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/apache-fop/src/main/resources/logback.xml +++ b/apache-fop/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/apache-meecrowave/README.md b/apache-meecrowave/README.md new file mode 100644 index 0000000000..42b93a383e --- /dev/null +++ b/apache-meecrowave/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +================================ +- [Building a Microservice with Apache Meecrowave](http://www.baeldung.com/apache-meecrowave) diff --git a/apache-meecrowave/pom.xml b/apache-meecrowave/pom.xml new file mode 100644 index 0000000000..cf13aa1c1b --- /dev/null +++ b/apache-meecrowave/pom.xml @@ -0,0 +1,57 @@ + + 4.0.0 + com.baeldung + apache-meecrowave + 0.0.1 + apache-meecrowave + A sample REST API application with Meecrowave + + + 1.8 + 1.8 + + + + + org.apache.meecrowave + meecrowave-core + 1.2.1 + + + + org.apache.meecrowave + meecrowave-jpa + 1.2.1 + + + + com.squareup.okhttp3 + okhttp + 3.10.0 + + + org.apache.meecrowave + meecrowave-junit + 1.2.0 + test + + + + junit + junit + 4.10 + test + + + + + + + org.apache.meecrowave + meecrowave-maven-plugin + 1.2.1 + + + + \ No newline at end of file diff --git a/apache-meecrowave/src/main/java/com/baeldung/meecrowave/Article.java b/apache-meecrowave/src/main/java/com/baeldung/meecrowave/Article.java new file mode 100644 index 0000000000..7925e8ff99 --- /dev/null +++ b/apache-meecrowave/src/main/java/com/baeldung/meecrowave/Article.java @@ -0,0 +1,30 @@ +package com.baeldung.meecrowave; + +public class Article { + private String name; + private String author; + + public Article() { + } + + public Article(String name, String author) { + this.author = author; + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } +} \ No newline at end of file diff --git a/apache-meecrowave/src/main/java/com/baeldung/meecrowave/ArticleEndpoints.java b/apache-meecrowave/src/main/java/com/baeldung/meecrowave/ArticleEndpoints.java new file mode 100644 index 0000000000..6cb7012c64 --- /dev/null +++ b/apache-meecrowave/src/main/java/com/baeldung/meecrowave/ArticleEndpoints.java @@ -0,0 +1,32 @@ +package com.baeldung.meecrowave; + +import javax.enterprise.context.RequestScoped; +import javax.inject.Inject; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +@RequestScoped +@Path("article") +public class ArticleEndpoints { + + @Inject + ArticleService articleService; + + @GET + public Response getArticle() { + return Response.ok() + .entity(new Article("name", "author")) + .build(); + + } + + @POST + public Response createArticle(Article article) { + return Response.status(Status.CREATED) + .entity(articleService.createArticle(article)) + .build(); + } +} \ No newline at end of file diff --git a/apache-meecrowave/src/main/java/com/baeldung/meecrowave/ArticleService.java b/apache-meecrowave/src/main/java/com/baeldung/meecrowave/ArticleService.java new file mode 100644 index 0000000000..7bd6b87345 --- /dev/null +++ b/apache-meecrowave/src/main/java/com/baeldung/meecrowave/ArticleService.java @@ -0,0 +1,10 @@ +package com.baeldung.meecrowave; + +import javax.enterprise.context.ApplicationScoped; + +@ApplicationScoped +public class ArticleService { + public Article createArticle(Article article) { + return article; + } +} diff --git a/apache-meecrowave/src/main/java/com/baeldung/meecrowave/Server.java b/apache-meecrowave/src/main/java/com/baeldung/meecrowave/Server.java new file mode 100644 index 0000000000..2aa7d0556f --- /dev/null +++ b/apache-meecrowave/src/main/java/com/baeldung/meecrowave/Server.java @@ -0,0 +1,16 @@ +package com.baeldung.meecrowave; + +import org.apache.meecrowave.Meecrowave; + +public class Server { + public static void main(String[] args) { + final Meecrowave.Builder builder = new Meecrowave.Builder(); + builder.setScanningPackageIncludes("com.baeldung.meecrowave"); + builder.setJaxrsMapping("/api/*"); + builder.setJsonpPrettify(true); + + try (Meecrowave meecrowave = new Meecrowave(builder)) { + meecrowave.bake().await(); + } + } +} diff --git a/apache-meecrowave/src/main/resources/logback.xml b/apache-meecrowave/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-meecrowave/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-meecrowave/src/test/java/com/baeldung/meecrowave/ArticleEndpointsTest.java b/apache-meecrowave/src/test/java/com/baeldung/meecrowave/ArticleEndpointsTest.java new file mode 100644 index 0000000000..0dc9773490 --- /dev/null +++ b/apache-meecrowave/src/test/java/com/baeldung/meecrowave/ArticleEndpointsTest.java @@ -0,0 +1,41 @@ +package com.baeldung.meecrowave; + + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.apache.meecrowave.Meecrowave; +import org.apache.meecrowave.junit.MonoMeecrowave; +import org.apache.meecrowave.testing.ConfigurationInject; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; + +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +@RunWith(MonoMeecrowave.Runner.class) +public class ArticleEndpointsTest { + + @ConfigurationInject + private Meecrowave.Builder config; + private static OkHttpClient client; + + @BeforeClass + public static void setup() { + client = new OkHttpClient(); + } + + @Test + public void whenRetunedArticle_thenCorrect() throws IOException { + final String base = "http://localhost:"+config.getHttpPort(); + + Request request = new Request.Builder() + .url(base+"/article") + .build(); + Response response = client.newCall(request).execute(); + assertEquals(200, response.code()); + } +} diff --git a/apache-opennlp/pom.xml b/apache-opennlp/pom.xml index 4095207aab..985c9a2df2 100644 --- a/apache-opennlp/pom.xml +++ b/apache-opennlp/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 apache-opennlp 1.0-SNAPSHOT @@ -24,12 +24,6 @@ ${org.assertj.version} test - - junit - junit - ${junit.version} - test - diff --git a/apache-opennlp/src/main/resources/logback.xml b/apache-opennlp/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-opennlp/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/ChunkerTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/ChunkerTest.java deleted file mode 100644 index cc3abb422b..0000000000 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/ChunkerTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.apache.opennlp; - -import java.io.FileInputStream; -import java.io.InputStream; -import opennlp.tools.chunker.ChunkerME; -import opennlp.tools.chunker.ChunkerModel; -import opennlp.tools.postag.POSModel; -import opennlp.tools.postag.POSTaggerME; -import opennlp.tools.tokenize.SimpleTokenizer; -import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; - -public class ChunkerTest { - - @Test - public void givenChunkerModel_whenChunk_thenChunksAreDetected() throws Exception { - - SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE; - String[] tokens = tokenizer.tokenize("He reckons the current account deficit will narrow to only 8 billion."); - - InputStream inputStreamPOSTagger = getClass().getResourceAsStream("/models/en-pos-maxent.bin"); - POSModel posModel = new POSModel(inputStreamPOSTagger); - POSTaggerME posTagger = new POSTaggerME(posModel); - String tags[] = posTagger.tag(tokens); - - InputStream inputStreamChunker = new FileInputStream("src/main/resources/models/en-chunker.bin"); - ChunkerModel chunkerModel = new ChunkerModel(inputStreamChunker); - ChunkerME chunker = new ChunkerME(chunkerModel); - String[] chunks = chunker.chunk(tokens, tags); - assertThat(chunks).contains("B-NP", "B-VP", "B-NP", "I-NP", "I-NP", "I-NP", "B-VP", "I-VP", "B-PP", "B-NP", "I-NP", "I-NP", "O"); - } -} diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/ChunkerUnitTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/ChunkerUnitTest.java new file mode 100644 index 0000000000..91dde8a2d1 --- /dev/null +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/ChunkerUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.apache.opennlp; + +import java.io.FileInputStream; +import java.io.InputStream; +import opennlp.tools.chunker.ChunkerME; +import opennlp.tools.chunker.ChunkerModel; +import opennlp.tools.postag.POSModel; +import opennlp.tools.postag.POSTaggerME; +import opennlp.tools.tokenize.SimpleTokenizer; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class ChunkerUnitTest { + + @Test + public void givenChunkerModel_whenChunk_thenChunksAreDetected() throws Exception { + + SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE; + String[] tokens = tokenizer.tokenize("He reckons the current account deficit will narrow to only 8 billion."); + + InputStream inputStreamPOSTagger = getClass().getResourceAsStream("/models/en-pos-maxent.bin"); + POSModel posModel = new POSModel(inputStreamPOSTagger); + POSTaggerME posTagger = new POSTaggerME(posModel); + String tags[] = posTagger.tag(tokens); + + InputStream inputStreamChunker = new FileInputStream("src/main/resources/models/en-chunker.bin"); + ChunkerModel chunkerModel = new ChunkerModel(inputStreamChunker); + ChunkerME chunker = new ChunkerME(chunkerModel); + String[] chunks = chunker.chunk(tokens, tags); + assertThat(chunks).contains("B-NP", "B-VP", "B-NP", "I-NP", "I-NP", "I-NP", "B-VP", "I-VP", "B-PP", "B-NP", "I-NP", "I-NP", "O"); + } +} diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LanguageDetectorAndTrainingDataTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LanguageDetectorAndTrainingDataTest.java deleted file mode 100644 index 5eb649dae1..0000000000 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LanguageDetectorAndTrainingDataTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.apache.opennlp; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Arrays; -import opennlp.tools.langdetect.Language; -import opennlp.tools.langdetect.LanguageDetector; -import opennlp.tools.langdetect.LanguageDetectorFactory; -import opennlp.tools.langdetect.LanguageDetectorME; -import opennlp.tools.langdetect.LanguageDetectorModel; -import opennlp.tools.langdetect.LanguageDetectorSampleStream; -import opennlp.tools.util.InputStreamFactory; -import opennlp.tools.util.MarkableFileInputStreamFactory; -import opennlp.tools.util.ObjectStream; -import opennlp.tools.util.PlainTextByLineStream; -import opennlp.tools.util.TrainingParameters; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.tuple; -import org.junit.Test; - -public class LanguageDetectorAndTrainingDataTest { - - @Test - public void givenLanguageDictionary_whenLanguageDetect_thenLanguageIsDetected() throws FileNotFoundException, IOException { - InputStreamFactory dataIn = new MarkableFileInputStreamFactory(new File("src/main/resources/models/DoccatSample.txt")); - ObjectStream lineStream = new PlainTextByLineStream(dataIn, "UTF-8"); - LanguageDetectorSampleStream sampleStream = new LanguageDetectorSampleStream(lineStream); - TrainingParameters params = new TrainingParameters(); - params.put(TrainingParameters.ITERATIONS_PARAM, 100); - params.put(TrainingParameters.CUTOFF_PARAM, 5); - params.put("DataIndexer", "TwoPass"); - params.put(TrainingParameters.ALGORITHM_PARAM, "NAIVEBAYES"); - - LanguageDetectorModel model = LanguageDetectorME.train(sampleStream, params, new LanguageDetectorFactory()); - - LanguageDetector ld = new LanguageDetectorME(model); - Language[] languages = ld.predictLanguages("estava em uma marcenaria na Rua Bruno"); - - assertThat(Arrays.asList(languages)).extracting("lang", "confidence").contains(tuple("pob", 0.9999999950605625), - tuple("ita", 4.939427661577956E-9), tuple("spa", 9.665954064665144E-15), - tuple("fra", 8.250349924885834E-25)); - } -} diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LanguageDetectorAndTrainingDataUnitTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LanguageDetectorAndTrainingDataUnitTest.java new file mode 100644 index 0000000000..82732809a5 --- /dev/null +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LanguageDetectorAndTrainingDataUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.apache.opennlp; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Arrays; +import opennlp.tools.langdetect.Language; +import opennlp.tools.langdetect.LanguageDetector; +import opennlp.tools.langdetect.LanguageDetectorFactory; +import opennlp.tools.langdetect.LanguageDetectorME; +import opennlp.tools.langdetect.LanguageDetectorModel; +import opennlp.tools.langdetect.LanguageDetectorSampleStream; +import opennlp.tools.util.InputStreamFactory; +import opennlp.tools.util.MarkableFileInputStreamFactory; +import opennlp.tools.util.ObjectStream; +import opennlp.tools.util.PlainTextByLineStream; +import opennlp.tools.util.TrainingParameters; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.tuple; +import org.junit.Test; + +public class LanguageDetectorAndTrainingDataUnitTest { + + @Test + public void givenLanguageDictionary_whenLanguageDetect_thenLanguageIsDetected() throws FileNotFoundException, IOException { + InputStreamFactory dataIn = new MarkableFileInputStreamFactory(new File("src/main/resources/models/DoccatSample.txt")); + ObjectStream lineStream = new PlainTextByLineStream(dataIn, "UTF-8"); + LanguageDetectorSampleStream sampleStream = new LanguageDetectorSampleStream(lineStream); + TrainingParameters params = new TrainingParameters(); + params.put(TrainingParameters.ITERATIONS_PARAM, 100); + params.put(TrainingParameters.CUTOFF_PARAM, 5); + params.put("DataIndexer", "TwoPass"); + params.put(TrainingParameters.ALGORITHM_PARAM, "NAIVEBAYES"); + + LanguageDetectorModel model = LanguageDetectorME.train(sampleStream, params, new LanguageDetectorFactory()); + + LanguageDetector ld = new LanguageDetectorME(model); + Language[] languages = ld.predictLanguages("estava em uma marcenaria na Rua Bruno"); + + assertThat(Arrays.asList(languages)).extracting("lang", "confidence").contains(tuple("pob", 0.9999999950605625), + tuple("ita", 4.939427661577956E-9), tuple("spa", 9.665954064665144E-15), + tuple("fra", 8.250349924885834E-25)); + } +} diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LemmetizerTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LemmetizerTest.java deleted file mode 100644 index bb681fb8d8..0000000000 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LemmetizerTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.apache.opennlp; - -import java.io.InputStream; -import opennlp.tools.lemmatizer.DictionaryLemmatizer; -import opennlp.tools.postag.POSModel; -import opennlp.tools.postag.POSTaggerME; -import opennlp.tools.tokenize.SimpleTokenizer; -import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; - -public class LemmetizerTest { - - @Test - public void givenEnglishDictionary_whenLemmatize_thenLemmasAreDetected() throws Exception { - - SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE; - String[] tokens = tokenizer.tokenize("John has a sister named Penny."); - - InputStream inputStreamPOSTagger = getClass().getResourceAsStream("/models/en-pos-maxent.bin"); - POSModel posModel = new POSModel(inputStreamPOSTagger); - POSTaggerME posTagger = new POSTaggerME(posModel); - String tags[] = posTagger.tag(tokens); - InputStream dictLemmatizer = getClass().getResourceAsStream("/models/en-lemmatizer.dict"); - DictionaryLemmatizer lemmatizer = new DictionaryLemmatizer(dictLemmatizer); - String[] lemmas = lemmatizer.lemmatize(tokens, tags); - - assertThat(lemmas).contains("O", "have", "a", "sister", "name", "O", "O"); - } -} diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LemmetizerUnitTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LemmetizerUnitTest.java new file mode 100644 index 0000000000..05bc6242b2 --- /dev/null +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LemmetizerUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.apache.opennlp; + +import java.io.InputStream; +import opennlp.tools.lemmatizer.DictionaryLemmatizer; +import opennlp.tools.postag.POSModel; +import opennlp.tools.postag.POSTaggerME; +import opennlp.tools.tokenize.SimpleTokenizer; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class LemmetizerUnitTest { + + @Test + public void givenEnglishDictionary_whenLemmatize_thenLemmasAreDetected() throws Exception { + + SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE; + String[] tokens = tokenizer.tokenize("John has a sister named Penny."); + + InputStream inputStreamPOSTagger = getClass().getResourceAsStream("/models/en-pos-maxent.bin"); + POSModel posModel = new POSModel(inputStreamPOSTagger); + POSTaggerME posTagger = new POSTaggerME(posModel); + String tags[] = posTagger.tag(tokens); + InputStream dictLemmatizer = getClass().getResourceAsStream("/models/en-lemmatizer.dict"); + DictionaryLemmatizer lemmatizer = new DictionaryLemmatizer(dictLemmatizer); + String[] lemmas = lemmatizer.lemmatize(tokens, tags); + + assertThat(lemmas).contains("O", "have", "a", "sister", "name", "O", "O"); + } +} diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/NamedEntityRecognitionTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/NamedEntityRecognitionTest.java deleted file mode 100644 index 94224409d6..0000000000 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/NamedEntityRecognitionTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.apache.opennlp; - -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import opennlp.tools.namefind.NameFinderME; -import opennlp.tools.namefind.TokenNameFinderModel; -import opennlp.tools.tokenize.SimpleTokenizer; -import opennlp.tools.util.Span; -import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; - -public class NamedEntityRecognitionTest { - - @Test - public void givenEnglishPersonModel_whenNER_thenPersonsAreDetected() throws Exception { - - SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE; - String[] tokens = tokenizer.tokenize("John is 26 years old. His best friend's name is Leonard. He has a sister named Penny."); - - InputStream inputStreamNameFinder = getClass().getResourceAsStream("/models/en-ner-person.bin"); - TokenNameFinderModel model = new TokenNameFinderModel(inputStreamNameFinder); - NameFinderME nameFinderME = new NameFinderME(model); - List spans = Arrays.asList(nameFinderME.find(tokens)); - assertThat(spans.toString()).isEqualTo("[[0..1) person, [13..14) person, [20..21) person]"); - List names = new ArrayList(); - int k = 0; - for (Span s : spans) { - names.add(""); - for (int index = s.getStart(); index < s.getEnd(); index++) { - names.set(k, names.get(k) + tokens[index]); - } - k++; - } - assertThat(names).contains("John","Leonard","Penny"); - } - -} diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/NamedEntityRecognitionUnitTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/NamedEntityRecognitionUnitTest.java new file mode 100644 index 0000000000..6965498e12 --- /dev/null +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/NamedEntityRecognitionUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.apache.opennlp; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import opennlp.tools.namefind.NameFinderME; +import opennlp.tools.namefind.TokenNameFinderModel; +import opennlp.tools.tokenize.SimpleTokenizer; +import opennlp.tools.util.Span; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class NamedEntityRecognitionUnitTest { + + @Test + public void givenEnglishPersonModel_whenNER_thenPersonsAreDetected() throws Exception { + + SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE; + String[] tokens = tokenizer.tokenize("John is 26 years old. His best friend's name is Leonard. He has a sister named Penny."); + + InputStream inputStreamNameFinder = getClass().getResourceAsStream("/models/en-ner-person.bin"); + TokenNameFinderModel model = new TokenNameFinderModel(inputStreamNameFinder); + NameFinderME nameFinderME = new NameFinderME(model); + List spans = Arrays.asList(nameFinderME.find(tokens)); + assertThat(spans.toString()).isEqualTo("[[0..1) person, [13..14) person, [20..21) person]"); + List names = new ArrayList(); + int k = 0; + for (Span s : spans) { + names.add(""); + for (int index = s.getStart(); index < s.getEnd(); index++) { + names.set(k, names.get(k) + tokens[index]); + } + k++; + } + assertThat(names).contains("John","Leonard","Penny"); + } + +} diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/POSTaggerTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/POSTaggerTest.java deleted file mode 100644 index 1bfebe208c..0000000000 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/POSTaggerTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.apache.opennlp; - -import java.io.InputStream; -import opennlp.tools.postag.POSModel; -import opennlp.tools.postag.POSTaggerME; -import opennlp.tools.tokenize.SimpleTokenizer; -import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; - -public class POSTaggerTest { - - @Test - public void givenPOSModel_whenPOSTagging_thenPOSAreDetected() throws Exception { - - SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE; - String[] tokens = tokenizer.tokenize("John has a sister named Penny."); - - InputStream inputStreamPOSTagger = getClass().getResourceAsStream("/models/en-pos-maxent.bin"); - POSModel posModel = new POSModel(inputStreamPOSTagger); - POSTaggerME posTagger = new POSTaggerME(posModel); - String tags[] = posTagger.tag(tokens); - assertThat(tags).contains("NNP", "VBZ", "DT", "NN", "VBN", "NNP", "."); - } -} diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/POSTaggerUnitTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/POSTaggerUnitTest.java new file mode 100644 index 0000000000..c084dcc1f2 --- /dev/null +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/POSTaggerUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.apache.opennlp; + +import java.io.InputStream; +import opennlp.tools.postag.POSModel; +import opennlp.tools.postag.POSTaggerME; +import opennlp.tools.tokenize.SimpleTokenizer; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class POSTaggerUnitTest { + + @Test + public void givenPOSModel_whenPOSTagging_thenPOSAreDetected() throws Exception { + + SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE; + String[] tokens = tokenizer.tokenize("John has a sister named Penny."); + + InputStream inputStreamPOSTagger = getClass().getResourceAsStream("/models/en-pos-maxent.bin"); + POSModel posModel = new POSModel(inputStreamPOSTagger); + POSTaggerME posTagger = new POSTaggerME(posModel); + String tags[] = posTagger.tag(tokens); + assertThat(tags).contains("NNP", "VBZ", "DT", "NN", "VBN", "NNP", "."); + } +} diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/SentenceDetectionTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/SentenceDetectionTest.java deleted file mode 100644 index 0250b12cbf..0000000000 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/SentenceDetectionTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.apache.opennlp; - -import java.io.InputStream; -import opennlp.tools.sentdetect.SentenceDetectorME; -import opennlp.tools.sentdetect.SentenceModel; -import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; - -public class SentenceDetectionTest { - - @Test - public void givenEnglishModel_whenDetect_thenSentencesAreDetected() throws Exception { - - String paragraph = "This is a statement. This is another statement. Now is an abstract word for time, " - + "that is always flying. And my email address is google@gmail.com."; - - InputStream is = getClass().getResourceAsStream("/models/en-sent.bin"); - SentenceModel model = new SentenceModel(is); - - SentenceDetectorME sdetector = new SentenceDetectorME(model); - - String sentences[] = sdetector.sentDetect(paragraph); - assertThat(sentences).contains("This is a statement.", - "This is another statement.", - "Now is an abstract word for time, that is always flying.", - "And my email address is google@gmail.com."); - } -} diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/SentenceDetectionUnitTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/SentenceDetectionUnitTest.java new file mode 100644 index 0000000000..60ee51e7ca --- /dev/null +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/SentenceDetectionUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.apache.opennlp; + +import java.io.InputStream; +import opennlp.tools.sentdetect.SentenceDetectorME; +import opennlp.tools.sentdetect.SentenceModel; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class SentenceDetectionUnitTest { + + @Test + public void givenEnglishModel_whenDetect_thenSentencesAreDetected() throws Exception { + + String paragraph = "This is a statement. This is another statement. Now is an abstract word for time, " + + "that is always flying. And my email address is google@gmail.com."; + + InputStream is = getClass().getResourceAsStream("/models/en-sent.bin"); + SentenceModel model = new SentenceModel(is); + + SentenceDetectorME sdetector = new SentenceDetectorME(model); + + String sentences[] = sdetector.sentDetect(paragraph); + assertThat(sentences).contains("This is a statement.", + "This is another statement.", + "Now is an abstract word for time, that is always flying.", + "And my email address is google@gmail.com."); + } +} diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/TokenizerTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/TokenizerTest.java deleted file mode 100644 index a4dea57cc3..0000000000 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/TokenizerTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.apache.opennlp; - -import java.io.InputStream; -import opennlp.tools.tokenize.SimpleTokenizer; -import opennlp.tools.tokenize.TokenizerME; -import opennlp.tools.tokenize.TokenizerModel; -import opennlp.tools.tokenize.WhitespaceTokenizer; -import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; - -public class TokenizerTest { - - @Test - public void givenEnglishModel_whenTokenize_thenTokensAreDetected() throws Exception { - InputStream inputStream = getClass().getResourceAsStream("/models/en-token.bin"); - TokenizerModel model = new TokenizerModel(inputStream); - TokenizerME tokenizer = new TokenizerME(model); - String[] tokens = tokenizer.tokenize("Baeldung is a Spring Resource."); - assertThat(tokens).contains("Baeldung", "is", "a", "Spring", "Resource", "."); - } - - @Test - public void givenWhitespaceTokenizer_whenTokenize_thenTokensAreDetected() throws Exception { - WhitespaceTokenizer tokenizer = WhitespaceTokenizer.INSTANCE; - String[] tokens = tokenizer.tokenize("Baeldung is a Spring Resource."); - assertThat(tokens).contains("Baeldung", "is", "a", "Spring", "Resource."); - } - - @Test - public void givenSimpleTokenizer_whenTokenize_thenTokensAreDetected() throws Exception { - SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE; - String[] tokens = tokenizer.tokenize("Baeldung is a Spring Resource."); - assertThat(tokens).contains("Baeldung", "is", "a", "Spring", "Resource", "."); - } - -} diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/TokenizerUnitTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/TokenizerUnitTest.java new file mode 100644 index 0000000000..6aa18b3bee --- /dev/null +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/TokenizerUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.apache.opennlp; + +import java.io.InputStream; +import opennlp.tools.tokenize.SimpleTokenizer; +import opennlp.tools.tokenize.TokenizerME; +import opennlp.tools.tokenize.TokenizerModel; +import opennlp.tools.tokenize.WhitespaceTokenizer; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class TokenizerUnitTest { + + @Test + public void givenEnglishModel_whenTokenize_thenTokensAreDetected() throws Exception { + InputStream inputStream = getClass().getResourceAsStream("/models/en-token.bin"); + TokenizerModel model = new TokenizerModel(inputStream); + TokenizerME tokenizer = new TokenizerME(model); + String[] tokens = tokenizer.tokenize("Baeldung is a Spring Resource."); + assertThat(tokens).contains("Baeldung", "is", "a", "Spring", "Resource", "."); + } + + @Test + public void givenWhitespaceTokenizer_whenTokenize_thenTokensAreDetected() throws Exception { + WhitespaceTokenizer tokenizer = WhitespaceTokenizer.INSTANCE; + String[] tokens = tokenizer.tokenize("Baeldung is a Spring Resource."); + assertThat(tokens).contains("Baeldung", "is", "a", "Spring", "Resource."); + } + + @Test + public void givenSimpleTokenizer_whenTokenize_thenTokensAreDetected() throws Exception { + SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE; + String[] tokens = tokenizer.tokenize("Baeldung is a Spring Resource."); + assertThat(tokens).contains("Baeldung", "is", "a", "Spring", "Resource", "."); + } + +} diff --git a/apache-poi/pom.xml b/apache-poi/pom.xml index 4874fe0b3e..a1ec626d43 100644 --- a/apache-poi/pom.xml +++ b/apache-poi/pom.xml @@ -1,5 +1,5 @@ + 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 apache-poi diff --git a/apache-poi/src/main/resources/logback.xml b/apache-poi/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-poi/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java b/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java index 5319208e85..7253238e80 100644 --- a/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java +++ b/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java @@ -1,25 +1,30 @@ package com.baeldung.poi.powerpoint; +import java.io.File; +import java.util.List; + import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xslf.usermodel.XSLFShape; import org.apache.poi.xslf.usermodel.XSLFSlide; import org.junit.After; import org.junit.Assert; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; - -import java.io.File; -import java.util.List; +import org.junit.rules.TemporaryFolder; public class PowerPointIntegrationTest { private PowerPointHelper pph; private String fileLocation; private static final String FILE_NAME = "presentation.pptx"; + + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); @Before public void setUp() throws Exception { - File currDir = new File("."); + File currDir = tempFolder.newFolder(); String path = currDir.getAbsolutePath(); fileLocation = path.substring(0, path.length() - 1) + FILE_NAME; diff --git a/apache-shiro/pom.xml b/apache-shiro/pom.xml index 73fdcab9d2..3a72804ab1 100644 --- a/apache-shiro/pom.xml +++ b/apache-shiro/pom.xml @@ -8,9 +8,10 @@ 1.0-SNAPSHOT - org.springframework.boot - spring-boot-starter-parent - ${org.springframework.boot.spring-boot-starter-parent.version} + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-1 @@ -57,10 +58,10 @@ org.apache.maven.plugins maven-compiler-plugin - 3.7.0 + ${maven-compiler-plugin.version} - 1.8 - 1.8 + ${java.version} + ${java.version} @@ -68,9 +69,10 @@ 1.4.0 + 3.7.0 + 1.8 1.2.17 1.7.25 - 1.5.2.RELEASE \ No newline at end of file diff --git a/apache-solrj/pom.xml b/apache-solrj/pom.xml index 31639c4864..9a807c2f26 100644 --- a/apache-solrj/pom.xml +++ b/apache-solrj/pom.xml @@ -1,5 +1,5 @@ + 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 apache-solrj diff --git a/apache-solrj/src/main/resources/logback.xml b/apache-solrj/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-solrj/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-solrj/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java b/apache-solrj/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java deleted file mode 100644 index 8b5fe77c6f..0000000000 --- a/apache-solrj/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.baeldung.solrjava; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import org.apache.solr.client.solrj.SolrQuery; -import org.apache.solr.client.solrj.SolrServerException; -import org.apache.solr.client.solrj.response.QueryResponse; -import org.apache.solr.common.SolrDocument; -import org.apache.solr.common.SolrDocumentList; -import org.junit.Before; -import org.junit.Test; - -public class SolrJavaIntegrationTest { - - private SolrJavaIntegration solrJavaIntegration; - - @Before - public void setUp() throws Exception { - - solrJavaIntegration = new SolrJavaIntegration("http://localhost:8983/solr/bigboxstore"); - solrJavaIntegration.addSolrDocument("123456", "Kenmore Dishwasher", "599.99"); - } - - @Test - public void whenAdd_thenVerifyAddedByQueryOnId() throws SolrServerException, IOException { - - SolrQuery query = new SolrQuery(); - query.set("q", "id:123456"); - QueryResponse response = null; - - response = solrJavaIntegration.getSolrClient().query(query); - - SolrDocumentList docList = response.getResults(); - assertEquals(1, docList.getNumFound()); - - for (SolrDocument doc : docList) { - assertEquals("Kenmore Dishwasher", (String) doc.getFieldValue("name")); - assertEquals((Double) 599.99, (Double) doc.getFieldValue("price")); - } - } - - @Test - public void whenAdd_thenVerifyAddedByQueryOnPrice() throws SolrServerException, IOException { - - SolrQuery query = new SolrQuery(); - query.set("q", "price:599.99"); - QueryResponse response = null; - - response = solrJavaIntegration.getSolrClient().query(query); - - SolrDocumentList docList = response.getResults(); - assertEquals(1, docList.getNumFound()); - - for (SolrDocument doc : docList) { - assertEquals("123456", (String) doc.getFieldValue("id")); - assertEquals((Double) 599.99, (Double) doc.getFieldValue("price")); - } - } - - @Test - public void whenAdd_thenVerifyAddedByQuery() throws SolrServerException, IOException { - - SolrDocument doc = solrJavaIntegration.getSolrClient().getById("123456"); - assertEquals("Kenmore Dishwasher", (String) doc.getFieldValue("name")); - assertEquals((Double) 599.99, (Double) doc.getFieldValue("price")); - } - - @Test - public void whenAddBean_thenVerifyAddedByQuery() throws SolrServerException, IOException { - - ProductBean pBean = new ProductBean("888", "Apple iPhone 6s", "299.99"); - solrJavaIntegration.addProductBean(pBean); - - SolrDocument doc = solrJavaIntegration.getSolrClient().getById("888"); - assertEquals("Apple iPhone 6s", (String) doc.getFieldValue("name")); - assertEquals((Double) 299.99, (Double) doc.getFieldValue("price")); - } - - @Test - public void whenDeleteById_thenVerifyDeleted() throws SolrServerException, IOException { - - solrJavaIntegration.deleteSolrDocumentById("123456"); - - SolrQuery query = new SolrQuery(); - query.set("q", "id:123456"); - QueryResponse response = solrJavaIntegration.getSolrClient().query(query); - - SolrDocumentList docList = response.getResults(); - assertEquals(0, docList.getNumFound()); - } - - @Test - public void whenDeleteByQuery_thenVerifyDeleted() throws SolrServerException, IOException { - - solrJavaIntegration.deleteSolrDocumentByQuery("name:Kenmore Dishwasher"); - - SolrQuery query = new SolrQuery(); - query.set("q", "id:123456"); - QueryResponse response = null; - - response = solrJavaIntegration.getSolrClient().query(query); - - SolrDocumentList docList = response.getResults(); - assertEquals(0, docList.getNumFound()); - } -} diff --git a/apache-solrj/src/test/java/com/baeldung/solrjava/SolrJavaLiveTest.java b/apache-solrj/src/test/java/com/baeldung/solrjava/SolrJavaLiveTest.java new file mode 100644 index 0000000000..eaf0271b55 --- /dev/null +++ b/apache-solrj/src/test/java/com/baeldung/solrjava/SolrJavaLiveTest.java @@ -0,0 +1,108 @@ +package com.baeldung.solrjava; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.apache.solr.client.solrj.SolrQuery; +import org.apache.solr.client.solrj.SolrServerException; +import org.apache.solr.client.solrj.response.QueryResponse; +import org.apache.solr.common.SolrDocument; +import org.apache.solr.common.SolrDocumentList; +import org.junit.Before; +import org.junit.Test; + +public class SolrJavaLiveTest { + + private SolrJavaIntegration solrJavaIntegration; + + @Before + public void setUp() throws Exception { + + solrJavaIntegration = new SolrJavaIntegration("http://localhost:8983/solr/bigboxstore"); + solrJavaIntegration.addSolrDocument("123456", "Kenmore Dishwasher", "599.99"); + } + + @Test + public void whenAdd_thenVerifyAddedByQueryOnId() throws SolrServerException, IOException { + + SolrQuery query = new SolrQuery(); + query.set("q", "id:123456"); + QueryResponse response = null; + + response = solrJavaIntegration.getSolrClient().query(query); + + SolrDocumentList docList = response.getResults(); + assertEquals(1, docList.getNumFound()); + + for (SolrDocument doc : docList) { + assertEquals("Kenmore Dishwasher", (String) doc.getFieldValue("name")); + assertEquals((Double) 599.99, (Double) doc.getFieldValue("price")); + } + } + + @Test + public void whenAdd_thenVerifyAddedByQueryOnPrice() throws SolrServerException, IOException { + + SolrQuery query = new SolrQuery(); + query.set("q", "price:599.99"); + QueryResponse response = null; + + response = solrJavaIntegration.getSolrClient().query(query); + + SolrDocumentList docList = response.getResults(); + assertEquals(1, docList.getNumFound()); + + for (SolrDocument doc : docList) { + assertEquals("123456", (String) doc.getFieldValue("id")); + assertEquals((Double) 599.99, (Double) doc.getFieldValue("price")); + } + } + + @Test + public void whenAdd_thenVerifyAddedByQuery() throws SolrServerException, IOException { + + SolrDocument doc = solrJavaIntegration.getSolrClient().getById("123456"); + assertEquals("Kenmore Dishwasher", (String) doc.getFieldValue("name")); + assertEquals((Double) 599.99, (Double) doc.getFieldValue("price")); + } + + @Test + public void whenAddBean_thenVerifyAddedByQuery() throws SolrServerException, IOException { + + ProductBean pBean = new ProductBean("888", "Apple iPhone 6s", "299.99"); + solrJavaIntegration.addProductBean(pBean); + + SolrDocument doc = solrJavaIntegration.getSolrClient().getById("888"); + assertEquals("Apple iPhone 6s", (String) doc.getFieldValue("name")); + assertEquals((Double) 299.99, (Double) doc.getFieldValue("price")); + } + + @Test + public void whenDeleteById_thenVerifyDeleted() throws SolrServerException, IOException { + + solrJavaIntegration.deleteSolrDocumentById("123456"); + + SolrQuery query = new SolrQuery(); + query.set("q", "id:123456"); + QueryResponse response = solrJavaIntegration.getSolrClient().query(query); + + SolrDocumentList docList = response.getResults(); + assertEquals(0, docList.getNumFound()); + } + + @Test + public void whenDeleteByQuery_thenVerifyDeleted() throws SolrServerException, IOException { + + solrJavaIntegration.deleteSolrDocumentByQuery("name:Kenmore Dishwasher"); + + SolrQuery query = new SolrQuery(); + query.set("q", "id:123456"); + QueryResponse response = null; + + response = solrJavaIntegration.getSolrClient().query(query); + + SolrDocumentList docList = response.getResults(); + assertEquals(0, docList.getNumFound()); + } +} diff --git a/apache-spark/pom.xml b/apache-spark/pom.xml index 3627f58147..290b63a14d 100644 --- a/apache-spark/pom.xml +++ b/apache-spark/pom.xml @@ -1,5 +1,5 @@ + 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 apache-spark @@ -21,16 +21,9 @@ spark-core_2.10 ${org.apache.spark.spark-core.version} - - junit - junit - ${junit.version} - test - - UTF-8 2.2.0 diff --git a/apache-spark/src/main/resources/logback.xml b/apache-spark/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-spark/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-thrift/pom.xml b/apache-thrift/pom.xml index 272bbb98d7..b22364cb19 100644 --- a/apache-thrift/pom.xml +++ b/apache-thrift/pom.xml @@ -1,5 +1,5 @@ + 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 apache-thrift @@ -39,6 +39,7 @@ org.codehaus.mojo build-helper-maven-plugin + ${build-helper-maven-plugin.version} generate-sources @@ -60,6 +61,7 @@ 0.10.0 0.1.11 1.7.12 + 3.0.0 diff --git a/apache-thrift/src/main/resources/logback.xml b/apache-thrift/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-thrift/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-tika/pom.xml b/apache-tika/pom.xml index 27bb851174..5a76fdeeda 100644 --- a/apache-tika/pom.xml +++ b/apache-tika/pom.xml @@ -1,5 +1,5 @@ + 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 apache-tika diff --git a/apache-tika/src/main/resources/logback.xml b/apache-tika/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-tika/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-velocity/pom.xml b/apache-velocity/pom.xml index efacdff25a..19cf77d945 100644 --- a/apache-velocity/pom.xml +++ b/apache-velocity/pom.xml @@ -60,7 +60,6 @@ 1.2 - 2.6 4.5.2 1.7 2.0 diff --git a/apache-velocity/src/main/resources/logback.xml b/apache-velocity/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/apache-velocity/src/main/resources/logback.xml +++ b/apache-velocity/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/apache-zookeeper/pom.xml b/apache-zookeeper/pom.xml index 7e1960ebb0..0b29186ccc 100644 --- a/apache-zookeeper/pom.xml +++ b/apache-zookeeper/pom.xml @@ -1,5 +1,5 @@ + 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 apache-zookeeper diff --git a/apache-zookeeper/src/main/resources/logback.xml b/apache-zookeeper/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-zookeeper/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/asciidoctor/pom.xml b/asciidoctor/pom.xml index 6843b4da42..15de5ac913 100644 --- a/asciidoctor/pom.xml +++ b/asciidoctor/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 asciidoctor asciidoctor diff --git a/asciidoctor/src/main/resources/logback.xml b/asciidoctor/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/asciidoctor/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/asm/pom.xml b/asm/pom.xml index 8c3aa379db..7bbaa2a8f1 100644 --- a/asm/pom.xml +++ b/asm/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.examples asm @@ -54,10 +54,8 @@ - UTF-8 5.2 2.4 - 2.9 \ No newline at end of file diff --git a/asm/src/main/resources/logback.xml b/asm/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/asm/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/atomix/pom.xml b/atomix/pom.xml index e41e60138d..f85d2d7484 100644 --- a/atomix/pom.xml +++ b/atomix/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.atomix.io atomix @@ -17,12 +17,6 @@ atomix-all ${atomix-all.version} - - junit - junit - ${junit.version} - test - log4j log4j @@ -32,7 +26,6 @@ 1.0.0-rc9 - 1.2.17 diff --git a/atomix/src/main/resources/logback.xml b/atomix/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/atomix/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/autovalue/README.md b/autovalue/README.md index 2385e82847..c6a08359ef 100644 --- a/autovalue/README.md +++ b/autovalue/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: - [Introduction to AutoValue](http://www.baeldung.com/introduction-to-autovalue) +- [Introduction to AutoFactory](http://www.baeldung.com/autofactory) diff --git a/autovalue/pom.xml b/autovalue/pom.xml index 3aa645002b..3ec2d26b35 100644 --- a/autovalue/pom.xml +++ b/autovalue/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung autovalue diff --git a/autovalue/src/main/resources/logback.xml b/autovalue/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/autovalue/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/aws-lambda/README.md b/aws-lambda/README.md new file mode 100644 index 0000000000..921b699bdd --- /dev/null +++ b/aws-lambda/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Using AWS Lambda with API Gateway](http://www.baeldung.com/aws-lambda-api-gateway) +- [Introduction to AWS Serverless Application Model](http://www.baeldung.com/aws-serverless) diff --git a/aws-lambda/pom.xml b/aws-lambda/pom.xml new file mode 100644 index 0000000000..c47c3cd86f --- /dev/null +++ b/aws-lambda/pom.xml @@ -0,0 +1,100 @@ + + + 4.0.0 + com.baeldung + aws-lambda + 0.1.0-SNAPSHOT + jar + aws-lambda + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + + com.amazonaws + aws-java-sdk-dynamodb + ${aws-java-sdk.version} + + + com.amazonaws + aws-java-sdk-core + ${aws-java-sdk.version} + + + com.amazonaws + aws-lambda-java-core + ${aws-lambda-java-core.version} + + + commons-logging + commons-logging + + + + + com.amazonaws + aws-lambda-java-events + ${aws-lambda-java-events.version} + + + commons-logging + commons-logging + + + + + com.google.code.gson + gson + ${gson.version} + + + commons-io + commons-io + ${commons-io.version} + + + com.googlecode.json-simple + json-simple + ${json-simple.version} + + + + + + + org.apache.maven.plugins + maven-shade-plugin + ${maven-shade-plugin.version} + + false + + + + package + + shade + + + + + + + + + 1.1.1 + 20180130 + 2.5 + 1.3.0 + 1.2.0 + 2.8.2 + 1.11.241 + 3.0.0 + + + \ No newline at end of file diff --git a/aws-lambda/sam-templates/template-implicit.yaml b/aws-lambda/sam-templates/template-implicit.yaml new file mode 100644 index 0000000000..3e5b12763e --- /dev/null +++ b/aws-lambda/sam-templates/template-implicit.yaml @@ -0,0 +1,60 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: 'AWS::Serverless-2016-10-31' +Description: Baeldung Serverless Application Model Example with Implicit API Definition +Globals: + Api: + EndpointConfiguration: REGIONAL + Name: "TestAPI" +Resources: + PersonTable: + Type: AWS::Serverless::SimpleTable + Properties: + PrimaryKey: + Name: id + Type: Number + TableName: Person + StorePersonFunction: + Type: AWS::Serverless::Function + Properties: + Handler: com.baeldung.lambda.apigateway.APIDemoHandler::handleRequest + Runtime: java8 + Timeout: 15 + MemorySize: 512 + CodeUri: ../target/aws-lambda-0.1.0-SNAPSHOT.jar + Policies: + - DynamoDBCrudPolicy: + TableName: !Ref PersonTable + Environment: + Variables: + TABLE_NAME: !Ref PersonTable + Events: + StoreApi: + Type: Api + Properties: + Path: /persons + Method: PUT + GetPersonByHTTPParamFunction: + Type: AWS::Serverless::Function + Properties: + Handler: com.baeldung.lambda.apigateway.APIDemoHandler::handleGetByParam + Runtime: java8 + Timeout: 15 + MemorySize: 512 + CodeUri: ../target/aws-lambda-0.1.0-SNAPSHOT.jar + Policies: + - DynamoDBReadPolicy: + TableName: !Ref PersonTable + Environment: + Variables: + TABLE_NAME: !Ref PersonTable + Events: + GetByPathApi: + Type: Api + Properties: + Path: /persons/{id} + Method: GET + GetByQueryApi: + Type: Api + Properties: + Path: /persons + Method: GET \ No newline at end of file diff --git a/aws-lambda/sam-templates/template-inline-swagger.yaml b/aws-lambda/sam-templates/template-inline-swagger.yaml new file mode 100644 index 0000000000..8422bcead2 --- /dev/null +++ b/aws-lambda/sam-templates/template-inline-swagger.yaml @@ -0,0 +1,112 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: 'AWS::Serverless-2016-10-31' +Description: Baeldung Serverless Application Model Example with Inline Swagger API Definition +Resources: + PersonTable: + Type: AWS::Serverless::SimpleTable + Properties: + PrimaryKey: + Name: id + Type: Number + TableName: Person + StorePersonFunction: + Type: AWS::Serverless::Function + Properties: + Handler: com.baeldung.lambda.apigateway.APIDemoHandler::handleRequest + Runtime: java8 + Timeout: 15 + MemorySize: 512 + CodeUri: ../target/aws-lambda-0.1.0-SNAPSHOT.jar + Policies: + - DynamoDBCrudPolicy: + TableName: !Ref PersonTable + Environment: + Variables: + TABLE_NAME: !Ref PersonTable + Events: + StoreApi: + Type: Api + Properties: + Path: /persons + Method: PUT + RestApiId: + Ref: MyApi + GetPersonByHTTPParamFunction: + Type: AWS::Serverless::Function + Properties: + Handler: com.baeldung.lambda.apigateway.APIDemoHandler::handleGetByParam + Runtime: java8 + Timeout: 15 + MemorySize: 512 + CodeUri: ../target/aws-lambda-0.1.0-SNAPSHOT.jar + Policies: + - DynamoDBReadPolicy: + TableName: !Ref PersonTable + Environment: + Variables: + TABLE_NAME: !Ref PersonTable + Events: + GetByPathApi: + Type: Api + Properties: + Path: /persons/{id} + Method: GET + RestApiId: + Ref: MyApi + GetByQueryApi: + Type: Api + Properties: + Path: /persons + Method: GET + RestApiId: + Ref: MyApi + MyApi: + Type: AWS::Serverless::Api + Properties: + StageName: test + EndpointConfiguration: REGIONAL + DefinitionBody: + swagger: "2.0" + info: + title: "TestAPI" + paths: + /persons: + get: + parameters: + - name: "id" + in: "query" + required: true + type: "string" + x-amazon-apigateway-request-validator: "Validate query string parameters and\ + \ headers" + x-amazon-apigateway-integration: + uri: + Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${GetPersonByHTTPParamFunction.Arn}/invocations + responses: {} + httpMethod: "POST" + type: "aws_proxy" + put: + x-amazon-apigateway-integration: + uri: + Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${StorePersonFunction.Arn}/invocations + responses: {} + httpMethod: "POST" + type: "aws_proxy" + /persons/{id}: + get: + parameters: + - name: "id" + in: "path" + required: true + type: "string" + responses: {} + x-amazon-apigateway-integration: + uri: + Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${GetPersonByHTTPParamFunction.Arn}/invocations + responses: {} + httpMethod: "POST" + type: "aws_proxy" + x-amazon-apigateway-request-validators: + Validate query string parameters and headers: + validateRequestParameters: true + validateRequestBody: false \ No newline at end of file diff --git a/aws/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java b/aws-lambda/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java similarity index 100% rename from aws/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java rename to aws-lambda/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java diff --git a/aws/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java b/aws-lambda/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java similarity index 100% rename from aws/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java rename to aws-lambda/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java diff --git a/aws/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java b/aws-lambda/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java similarity index 100% rename from aws/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java rename to aws-lambda/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java diff --git a/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/APIDemoHandler.java b/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/APIDemoHandler.java new file mode 100644 index 0000000000..31bcd0b952 --- /dev/null +++ b/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/APIDemoHandler.java @@ -0,0 +1,121 @@ +package com.baeldung.lambda.apigateway; + +import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; +import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; +import com.amazonaws.services.dynamodbv2.document.*; +import com.amazonaws.services.dynamodbv2.document.spec.PutItemSpec; +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestStreamHandler; +import com.baeldung.lambda.apigateway.model.Person; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.io.*; + +public class APIDemoHandler implements RequestStreamHandler { + + private JSONParser parser = new JSONParser(); + private static final String DYNAMODB_TABLE_NAME = System.getenv("TABLE_NAME"); + + @Override + public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException { + + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + JSONObject responseJson = new JSONObject(); + + AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient(); + DynamoDB dynamoDb = new DynamoDB(client); + + try { + JSONObject event = (JSONObject) parser.parse(reader); + + if (event.get("body") != null) { + + Person person = new Person((String) event.get("body")); + + dynamoDb.getTable(DYNAMODB_TABLE_NAME) + .putItem(new PutItemSpec().withItem(new Item().withNumber("id", person.getId()) + .withString("name", person.getName()))); + } + + JSONObject responseBody = new JSONObject(); + responseBody.put("message", "New item created"); + + JSONObject headerJson = new JSONObject(); + headerJson.put("x-custom-header", "my custom header value"); + + responseJson.put("statusCode", 200); + responseJson.put("headers", headerJson); + responseJson.put("body", responseBody.toString()); + + } catch (ParseException pex) { + responseJson.put("statusCode", 400); + responseJson.put("exception", pex); + } + + OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); + writer.write(responseJson.toString()); + writer.close(); + } + + public void handleGetByParam(InputStream inputStream, OutputStream outputStream, Context context) throws IOException { + + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + JSONObject responseJson = new JSONObject(); + + AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient(); + DynamoDB dynamoDb = new DynamoDB(client); + + Item result = null; + try { + JSONObject event = (JSONObject) parser.parse(reader); + JSONObject responseBody = new JSONObject(); + + if (event.get("pathParameters") != null) { + + JSONObject pps = (JSONObject) event.get("pathParameters"); + if (pps.get("id") != null) { + + int id = Integer.parseInt((String) pps.get("id")); + result = dynamoDb.getTable(DYNAMODB_TABLE_NAME) + .getItem("id", id); + } + + } else if (event.get("queryStringParameters") != null) { + + JSONObject qps = (JSONObject) event.get("queryStringParameters"); + if (qps.get("id") != null) { + + int id = Integer.parseInt((String) qps.get("id")); + result = dynamoDb.getTable(DYNAMODB_TABLE_NAME) + .getItem("id", id); + } + } + if (result != null) { + + Person person = new Person(result.toJSON()); + responseBody.put("Person", person); + responseJson.put("statusCode", 200); + } else { + + responseBody.put("message", "No item found"); + responseJson.put("statusCode", 404); + } + + JSONObject headerJson = new JSONObject(); + headerJson.put("x-custom-header", "my custom header value"); + + responseJson.put("headers", headerJson); + responseJson.put("body", responseBody.toString()); + + } catch (ParseException pex) { + responseJson.put("statusCode", 400); + responseJson.put("exception", pex); + } + + OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); + writer.write(responseJson.toString()); + writer.close(); + } +} diff --git a/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/model/Person.java b/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/model/Person.java new file mode 100644 index 0000000000..9d5a371ab5 --- /dev/null +++ b/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/model/Person.java @@ -0,0 +1,38 @@ +package com.baeldung.lambda.apigateway.model; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class Person { + + private int id; + private String name; + + public Person(String json) { + Gson gson = new Gson(); + Person request = gson.fromJson(json, Person.class); + this.id = request.getId(); + this.name = request.getName(); + } + + public String toString() { + final Gson gson = new GsonBuilder().setPrettyPrinting().create(); + return gson.toJson(this); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/aws/src/main/java/com/baeldung/lambda/dynamodb/SavePersonHandler.java b/aws-lambda/src/main/java/com/baeldung/lambda/dynamodb/SavePersonHandler.java similarity index 100% rename from aws/src/main/java/com/baeldung/lambda/dynamodb/SavePersonHandler.java rename to aws-lambda/src/main/java/com/baeldung/lambda/dynamodb/SavePersonHandler.java diff --git a/aws/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonRequest.java b/aws-lambda/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonRequest.java similarity index 100% rename from aws/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonRequest.java rename to aws-lambda/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonRequest.java diff --git a/aws/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonResponse.java b/aws-lambda/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonResponse.java similarity index 100% rename from aws/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonResponse.java rename to aws-lambda/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonResponse.java diff --git a/aws-lambda/src/main/resources/logback.xml b/aws-lambda/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/aws-lambda/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/aws/.gitignore b/aws/.gitignore index b83d22266a..bf11a4cc38 100644 --- a/aws/.gitignore +++ b/aws/.gitignore @@ -1 +1,2 @@ /target/ +.idea/ \ No newline at end of file diff --git a/aws/pom.xml b/aws/pom.xml index 7cd16db802..ab63f6afa1 100644 --- a/aws/pom.xml +++ b/aws/pom.xml @@ -1,5 +1,5 @@ + 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 aws @@ -19,13 +19,7 @@ aws-java-sdk ${aws-java-sdk.version} - - junit - junit - ${junit.version} - test - - + org.mockito mockito-core ${mockito-core.version} @@ -106,26 +100,6 @@ - - - org.apache.maven.plugins - maven-dependency-plugin - ${maven-dependency-plugin.version} - - - copy-dependencies - test-compile - - copy-dependencies - - - test - so,dll,dylib - ${project.basedir}/native-libs - - - - @@ -143,15 +117,13 @@ 1.1.0 2.8.0 1.11.290 - 4.12 - 2.8.9 + 2.21.0 3.8.0 1.11.86 https://s3-us-west-2.amazonaws.com/dynamodb-local/release 1.10.L001 0.9.4.0006L 3.0.0 - 2.10 \ No newline at end of file diff --git a/aws/src/main/java/com/baeldung/rds/AWSRDSService.java b/aws/src/main/java/com/baeldung/rds/AWSRDSService.java new file mode 100644 index 0000000000..d4da92f30f --- /dev/null +++ b/aws/src/main/java/com/baeldung/rds/AWSRDSService.java @@ -0,0 +1,184 @@ +package com.baeldung.rds; + +import com.amazonaws.auth.AWSCredentialsProvider; +import com.amazonaws.auth.AWSStaticCredentialsProvider; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.regions.Regions; +import com.amazonaws.services.rds.AmazonRDS; +import com.amazonaws.services.rds.AmazonRDSClientBuilder; +import com.amazonaws.services.rds.model.*; + +import java.io.IOException; +import java.io.InputStream; +import java.sql.*; +import java.util.List; +import java.util.Properties; +import java.util.UUID; +import java.util.logging.Logger; + +public class AWSRDSService { + + + final static Logger logger = Logger.getLogger(AWSRDSService.class.getName()); + private AWSCredentialsProvider credentials; + private AmazonRDS amazonRDS; + private String db_username; + private String db_password; + private String db_database; + private String db_hostname; + + /* + * User access key and secret key must be set before execute any operation. + * Follow the link on how to get the user access and secret key + * https://aws.amazon.com/blogs/security/wheres-my-secret-access-key/ + * **/ + public AWSRDSService() throws IOException { + //Init RDS client with credentials and region. + credentials = new + AWSStaticCredentialsProvider(new + BasicAWSCredentials("", + "")); + amazonRDS = AmazonRDSClientBuilder.standard().withCredentials(credentials) + .withRegion(Regions.AP_SOUTHEAST_2).build(); + Properties prop = new Properties(); + InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties"); + prop.load(input); + db_username = prop.getProperty("db_username"); + db_password = prop.getProperty("db_password"); + db_database = prop.getProperty("db_database"); + } + + public AWSRDSService(AmazonRDS amazonRDS){ + this.amazonRDS = amazonRDS; + } + + /** + * create the RDS instance. + * After instance creation, update the db_hostname with endpoint in db.properties. + * */ + + public String launchInstance() { + + String identifier = ""; + CreateDBInstanceRequest request = new CreateDBInstanceRequest(); + // RDS instance name + request.setDBInstanceIdentifier("Sydney"); + request.setEngine("postgres"); + request.setMultiAZ(false); + request.setMasterUsername(db_username); + request.setMasterUserPassword(db_password); + request.setDBName(db_database); + request.setStorageType("gp2"); + request.setAllocatedStorage(10); + + DBInstance instance = amazonRDS.createDBInstance(request); + + // Information about the new RDS instance + identifier = instance.getDBInstanceIdentifier(); + String status = instance.getDBInstanceStatus(); + Endpoint endpoint = instance.getEndpoint(); + String endpoint_url = "Endpoint URL not available yet."; + if (endpoint != null) { + endpoint_url = endpoint.toString(); + } + logger.info(identifier + "\t" + status); + logger.info(endpoint_url); + + return identifier; + + } + + // Describe DB instances + public void listInstances() { + DescribeDBInstancesResult result = amazonRDS.describeDBInstances(); + List instances = result.getDBInstances(); + for (DBInstance instance : instances) { + // Information about each RDS instance + String identifier = instance.getDBInstanceIdentifier(); + String engine = instance.getEngine(); + String status = instance.getDBInstanceStatus(); + Endpoint endpoint = instance.getEndpoint(); + String endpoint_url = "Endpoint URL not available yet."; + if (endpoint != null) { + endpoint_url = endpoint.toString(); + } + logger.info(identifier + "\t" + engine + "\t" + status); + logger.info("\t" + endpoint_url); + } + + } + + //Delete RDS instance + public void terminateInstance(String identifier) { + + DeleteDBInstanceRequest request = new DeleteDBInstanceRequest(); + request.setDBInstanceIdentifier(identifier); + request.setSkipFinalSnapshot(true); + + // Delete the RDS instance + DBInstance instance = amazonRDS.deleteDBInstance(request); + + // Information about the RDS instance being deleted + String status = instance.getDBInstanceStatus(); + Endpoint endpoint = instance.getEndpoint(); + String endpoint_url = "Endpoint URL not available yet."; + if (endpoint != null) { + endpoint_url = endpoint.toString(); + } + + logger.info(identifier + "\t" + status); + logger.info(endpoint_url); + + } + + + public void runJdbcTests() throws SQLException, IOException { + + // Getting database properties from db.properties + Properties prop = new Properties(); + InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties"); + prop.load(input); + db_hostname = prop.getProperty("db_hostname"); + String jdbc_url = "jdbc:postgresql://" + db_hostname + ":5432/" + db_database; + + // Create a connection using the JDBC driver + try (Connection conn = DriverManager.getConnection(jdbc_url, db_username, db_password)) { + + // Create the test table if not exists + Statement statement = conn.createStatement(); + String sql = "CREATE TABLE IF NOT EXISTS jdbc_test (id SERIAL PRIMARY KEY, content VARCHAR(80))"; + statement.executeUpdate(sql); + + // Do some INSERT + PreparedStatement preparedStatement = conn.prepareStatement("INSERT INTO jdbc_test (content) VALUES (?)"); + String content = "" + UUID.randomUUID(); + preparedStatement.setString(1, content); + preparedStatement.executeUpdate(); + logger.info("INSERT: " + content); + + // Do some SELECT + sql = "SELECT * FROM jdbc_test"; + ResultSet resultSet = statement.executeQuery(sql); + while (resultSet.next()) { + String count = resultSet.getString("content"); + logger.info("Total Records: " + count); + } + } + + + } + + public static void main(String[] args) throws IOException, SQLException { + AWSRDSService awsrdsService = new AWSRDSService(); + + String instanceName = awsrdsService.launchInstance(); + + //Add some wait for instance creation. + + awsrdsService.listInstances(); + + awsrdsService.runJdbcTests(); + + awsrdsService.terminateInstance(instanceName); + } +} diff --git a/aws/src/main/resources/db.properties b/aws/src/main/resources/db.properties new file mode 100644 index 0000000000..e934611a2b --- /dev/null +++ b/aws/src/main/resources/db.properties @@ -0,0 +1,4 @@ +db_hostname= +db_username=username +db_password=password +db_database=mydb \ No newline at end of file diff --git a/aws/src/main/resources/logback.xml b/aws/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/aws/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/axon/pom.xml b/axon/pom.xml index 8d5636277a..915a04feb5 100644 --- a/axon/pom.xml +++ b/axon/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 axon diff --git a/axon/src/main/resources/logback.xml b/axon/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/axon/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/azure/.gitignore b/azure/.gitignore new file mode 100644 index 0000000000..82eca336e3 --- /dev/null +++ b/azure/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/azure/README.md b/azure/README.md new file mode 100644 index 0000000000..c60186e1ce --- /dev/null +++ b/azure/README.md @@ -0,0 +1,4 @@ +### Relevant Articles: + +- [Deploy Spring Boot App to Azure](http://www.baeldung.com/spring-boot-azure) + diff --git a/azure/docker/Dockerfile b/azure/docker/Dockerfile new file mode 100644 index 0000000000..f865518330 --- /dev/null +++ b/azure/docker/Dockerfile @@ -0,0 +1,6 @@ +FROM frolvlad/alpine-oraclejdk8:slim +VOLUME /tmp +ADD azure-0.1.jar app.jar +RUN sh -c 'touch /app.jar' +EXPOSE 8080 +ENTRYPOINT [ "sh", "-c", "java -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ] diff --git a/azure/pom.xml b/azure/pom.xml new file mode 100644 index 0000000000..555efeef70 --- /dev/null +++ b/azure/pom.xml @@ -0,0 +1,133 @@ + + + 4.0.0 + com.baeldung + azure + 0.1 + war + azure + Demo project for Spring Boot on Azure + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + runtime + + + + mysql + mysql-connector-java + runtime + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.spotify + docker-maven-plugin + {docker-maven-plugin.version} + + ${docker.image.prefix}/${project.artifactId} + https://${docker.image.prefix} + ${azure.containerRegistry} + docker + + + / + ${project.build.directory} + ${project.build.finalName}.jar + + + + + + com.microsoft.azure + azure-webapp-maven-plugin + ${azure-webapp-maven-plugin.version} + + + azure-auth + + baeldung-group + baeldung-webapp + baeldung-plan + {java.version} + + + + + + + + + + spring.datasource.url + jdbc:h2:file:~/test + + + + spring.datasource.username + sa + + + + spring.datasource.password + + + + + + + + + + + + + + + + + + + + + baeldungadr + ${azure.containerRegistry}.azurecr.io + 1.1.0 + 1.1.0 + 1.8 + + + diff --git a/azure/src/main/java/com/baeldung/springboot/azure/AzureApplication.java b/azure/src/main/java/com/baeldung/springboot/azure/AzureApplication.java new file mode 100644 index 0000000000..5233f6bdf4 --- /dev/null +++ b/azure/src/main/java/com/baeldung/springboot/azure/AzureApplication.java @@ -0,0 +1,19 @@ +package com.baeldung.springboot.azure; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +@SpringBootApplication +public class AzureApplication extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(AzureApplication.class); + } + + public static void main(String[] args) { + SpringApplication.run(AzureApplication.class, args); + } +} diff --git a/azure/src/main/java/com/baeldung/springboot/azure/TestController.java b/azure/src/main/java/com/baeldung/springboot/azure/TestController.java new file mode 100644 index 0000000000..9a18bf4d65 --- /dev/null +++ b/azure/src/main/java/com/baeldung/springboot/azure/TestController.java @@ -0,0 +1,34 @@ +package com.baeldung.springboot.azure; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import static com.baeldung.springboot.azure.User.userNamed; + +/** + * @author aiet + */ +@RestController +public class TestController { + + @GetMapping("/hello") + public String hello() { + return "hello azure!"; + } + + @Autowired private UserRepository userRepository; + + @PostMapping("/user") + public String register(@RequestParam String name) { + userRepository.save(userNamed(name)); + return "registered"; + } + + @GetMapping("/user") + public Iterable userlist() { + return userRepository.findAll(); + } +} diff --git a/azure/src/main/java/com/baeldung/springboot/azure/User.java b/azure/src/main/java/com/baeldung/springboot/azure/User.java new file mode 100644 index 0000000000..d7a25aa246 --- /dev/null +++ b/azure/src/main/java/com/baeldung/springboot/azure/User.java @@ -0,0 +1,43 @@ +package com.baeldung.springboot.azure; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +/** + * @author aiet + */ +@Entity +public class User { + + public User() { + } + + public static User userNamed(String name) { + User u = new User(); + u.setName(name); + return u; + } + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Integer id; + private String name; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/azure/src/main/java/com/baeldung/springboot/azure/UserRepository.java b/azure/src/main/java/com/baeldung/springboot/azure/UserRepository.java new file mode 100644 index 0000000000..74a23f3180 --- /dev/null +++ b/azure/src/main/java/com/baeldung/springboot/azure/UserRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.springboot.azure; + +import org.springframework.data.repository.CrudRepository; + +/** + * @author aiet + */ +public interface UserRepository extends CrudRepository { +} diff --git a/azure/src/main/resources/application.properties b/azure/src/main/resources/application.properties new file mode 100644 index 0000000000..32ee873194 --- /dev/null +++ b/azure/src/main/resources/application.properties @@ -0,0 +1,16 @@ +server.port=8080 +server.address=0.0.0.0 +spring.jpa.hibernate.ddl-auto=create + +logging.file=azure.log +logging.level.root=info + +spring.datasource.url=jdbc:h2:file:~/test +spring.datasource.username=sa +spring.datasource.password= + +#spring.datasource.url=jdbc:mysql://localhost:3306/localdb +#spring.datasource.username=your-db-username +#spring.datasource.password=your-db-password + + diff --git a/azure/src/main/resources/logback.xml b/azure/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/azure/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/azure/src/test/java/com/baeldung/springboot/azure/AzureApplicationIntegrationTest.java b/azure/src/test/java/com/baeldung/springboot/azure/AzureApplicationIntegrationTest.java new file mode 100644 index 0000000000..7c3084446f --- /dev/null +++ b/azure/src/test/java/com/baeldung/springboot/azure/AzureApplicationIntegrationTest.java @@ -0,0 +1,16 @@ +package com.baeldung.springboot.azure; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class AzureApplicationIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/baeldung-pmd-rules.xml b/baeldung-pmd-rules.xml index 7625d68242..8175e80e19 100644 --- a/baeldung-pmd-rules.xml +++ b/baeldung-pmd-rules.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd" xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd"> Baeldung custom PMD rules - + Test does not follow Baeldung naming convention 3 - \ No newline at end of file + diff --git a/bootique/pom.xml b/bootique/pom.xml index 89ef2b4b5b..880b9a516f 100644 --- a/bootique/pom.xml +++ b/bootique/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung.bootique bootique @@ -52,16 +52,21 @@ + org.apache.maven.plugins maven-shade-plugin + ${maven-shade-plugin.version} + com.baeldung.bootique.App 0.23 + + 2.4.3 \ No newline at end of file diff --git a/bootique/src/main/resources/logback.xml b/bootique/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/bootique/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/bootique/src/test/java/com/baeldung/bootique/AppTest.java b/bootique/src/test/java/com/baeldung/bootique/AppTest.java deleted file mode 100644 index 8856780ed4..0000000000 --- a/bootique/src/test/java/com/baeldung/bootique/AppTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.bootique; - -import com.baeldung.bootique.service.HelloService; -import io.bootique.BQRuntime; -import io.bootique.test.junit.BQDaemonTestFactory; -import io.bootique.test.junit.BQTestFactory; -import org.junit.Rule; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class AppTest { - - @Rule - public BQTestFactory bqTestFactory = new BQTestFactory(); - - @Rule - public BQDaemonTestFactory bqDaemonTestFactory = new BQDaemonTestFactory(); - - @Test - public void givenService_expectBoolen() { - BQRuntime runtime = bqTestFactory.app("--server").autoLoadModules().createRuntime(); - HelloService service = runtime.getInstance(HelloService.class); - assertEquals(true, service.save()); - } - -} diff --git a/bootique/src/test/java/com/baeldung/bootique/AppUnitTest.java b/bootique/src/test/java/com/baeldung/bootique/AppUnitTest.java new file mode 100644 index 0000000000..2a113cd1ee --- /dev/null +++ b/bootique/src/test/java/com/baeldung/bootique/AppUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.bootique; + +import com.baeldung.bootique.service.HelloService; +import io.bootique.BQRuntime; +import io.bootique.test.junit.BQDaemonTestFactory; +import io.bootique.test.junit.BQTestFactory; +import org.junit.Rule; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class AppUnitTest { + + @Rule + public BQTestFactory bqTestFactory = new BQTestFactory(); + + @Rule + public BQDaemonTestFactory bqDaemonTestFactory = new BQDaemonTestFactory(); + + @Test + public void givenService_expectBoolen() { + BQRuntime runtime = bqTestFactory.app("--server").autoLoadModules().createRuntime(); + HelloService service = runtime.getInstance(HelloService.class); + assertEquals(true, service.save()); + } + +} diff --git a/camel-api/pom.xml b/camel-api/pom.xml deleted file mode 100644 index 86f6713cd6..0000000000 --- a/camel-api/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - 4.0.0 - com.example - spring-boot-camel - 0.0.1-SNAPSHOT - Spring-Boot - Camel API - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - org.apache.camel - camel-servlet-starter - ${camel.version} - - - org.apache.camel - camel-jackson-starter - ${camel.version} - - - org.apache.camel - camel-swagger-java-starter - ${camel.version} - - - org.apache.camel - camel-spring-boot-starter - ${camel.version} - - - org.springframework.boot - spring-boot-starter-web - ${spring-boot-starter.version} - - - - - spring-boot:run - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot-starter.version} - - - - repackage - - - - - - - - - UTF-8 - 3.7.0 - 2.19.1 - 1.5.4.RELEASE - - - diff --git a/cas/cas-secured-app/pom.xml b/cas/cas-secured-app/pom.xml index 1a9176ff3e..22d1522fbe 100644 --- a/cas/cas-secured-app/pom.xml +++ b/cas/cas-secured-app/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung cas-secured-app @@ -10,10 +10,10 @@ Demo project for Spring Boot - org.springframework.boot - spring-boot-starter-parent - 2.0.0.M7 - + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-1 @@ -60,28 +60,6 @@ - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - UTF-8 UTF-8 diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java index 7faccbb125..2c88b74a83 100644 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java @@ -1,7 +1,7 @@ package com.baeldung.cassecuredapp.controllers; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler; diff --git a/cas/cas-secured-app/src/main/resources/logback.xml b/cas/cas-secured-app/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/cas/cas-secured-app/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/cas/cas-server/.factorypath b/cas/cas-server/.factorypath new file mode 100644 index 0000000000..006c761796 --- /dev/null +++ b/cas/cas-server/.factorypath @@ -0,0 +1,228 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cas/cas-server/README.md b/cas/cas-server/README.md index bae8b648e5..bacf45a2a1 100644 --- a/cas/cas-server/README.md +++ b/cas/cas-server/README.md @@ -6,10 +6,11 @@ Generic CAS WAR overlay to exercise the latest versions of CAS. This overlay cou # Versions ```xml -5.1.x +5.3.x ``` # Requirements + * JDK 1.8+ # Configuration @@ -64,20 +65,23 @@ Run the CAS web application as an executable WAR via Spring Boot. This is most u ### Warning! -Be careful with this method of deployment. `bootRun` is not designed to work with already executable WAR artifacts such that CAS server web application. YMMV. Today, uses of this mode ONLY work when there is **NO OTHER** dependency added to the build script and the `cas-server-webapp` is the only present module. See [this issue](https://github.com/apereo/cas/issues/2334) and [this issue](https://github.com/spring-projects/spring-boot/issues/8320) for more info. +Be careful with this method of deployment. `bootRun` is not designed to work with already executable WAR artifacts such that CAS server web application. YMMV. Today, uses of this mode ONLY work when there is **NO OTHER** dependency added to the build script and the `cas-server-webapp` is the only present module. See [this issue](https://github.com/spring-projects/spring-boot/issues/8320) for more info. ## Spring Boot App Server Selection -There is an app.server property in the pom.xml that can be used to select a spring boot application server. -It defaults to "-tomcat" but "-jetty" and "-undertow" are supported. -It can also be set to an empty value (nothing) if you want to deploy CAS to an external application server of your choice and you don't want the spring boot libraries included. + +There is an app.server property in the `pom.xml` that can be used to select a spring boot application server. +It defaults to `-tomcat` but `-jetty` and `-undertow` are supported. + +It can also be set to an empty value (nothing) if you want to deploy CAS to an external application server of your choice. ```xml -tomcat ``` ## Windows Build -If you are building on windows, try build.cmd instead of build.sh. Arguments are similar but for usage, run: + +If you are building on windows, try `build.cmd` instead of `build.sh`. Arguments are similar but for usage, run: ``` build.cmd help @@ -86,3 +90,12 @@ build.cmd help ## External Deploy resultant `target/cas.war` to a servlet container of choice. + + +## Command Line Shell + +Invokes the CAS Command Line Shell. For a list of commands either use no arguments or use `-h`. To enter the interactive shell use `-sh`. + +```bash +./build.sh cli +``` \ No newline at end of file diff --git a/cas/cas-server/build.cmd b/cas/cas-server/build.cmd index f907dcb388..2cf9262afe 100644 --- a/cas/cas-server/build.cmd +++ b/cas/cas-server/build.cmd @@ -23,8 +23,10 @@ @if "%1" == "bootrun" call:bootrun %2 %3 %4 @if "%1" == "debug" call:debug %2 %3 %4 @if "%1" == "run" call:run %2 %3 %4 +@if "%1" == "runalone" call:runalone %2 %3 %4 @if "%1" == "help" call:help @if "%1" == "gencert" call:gencert +@if "%1" == "cli" call:runcli %2 %3 %4 @rem function section starts here @goto:eof @@ -38,7 +40,7 @@ @goto:eof :help - @echo "Usage: build.bat [copy|clean|package|run|debug|bootrun|gencert] [optional extra args for maven]" + @echo "Usage: build.bat [copy|clean|package|run|debug|bootrun|gencert|cli] [optional extra args for maven or cli]" @echo "To get started on a clean system, run "build.bat copy" and "build.bat gencert", then "build.bat run" @echo "Note that using the copy or gencert arguments will create and/or overwrite the %CAS_DIR% which is outside this project" @goto:eof @@ -66,6 +68,10 @@ call:package %1 %2 %3 & java %JAVA_ARGS% -jar target/cas.war @goto:eof +:runalone + call:package %1 %2 %3 & target/cas.war +@goto:eof + :gencert where /q keytool if ERRORLEVEL 1 ( @@ -80,3 +86,17 @@ keytool -exportcert -alias cas -storepass changeit -keystore %CAS_DIR%\thekeystore -file %CAS_DIR%\cas.cer ) @goto:eof + +:runcli + for /f %%i in ('call %MAVEN_CMD% -q --non-recursive "-Dexec.executable=cmd" "-Dexec.args=/C echo ${cas.version}" "org.codehaus.mojo:exec-maven-plugin:1.3.1:exec"') do set CAS_VERSION=%%i + @set CAS_VERSION=%CAS_VERSION: =% + @set DOWNLOAD_DIR=target + @set COMMAND_FILE=cas-server-support-shell-%CAS_VERSION%.jar + @if not exist %DOWNLOAD_DIR% mkdir %DOWNLOAD_DIR% + @if not exist %DOWNLOAD_DIR%\%COMMAND_FILE% ( + @call mvn org.apache.maven.plugins:maven-dependency-plugin:3.0.2:get -DgroupId=org.apereo.cas -DartifactId=cas-server-support-shell -Dversion=%CAS_VERSION% -Dpackaging=jar -DartifactItem.outputDirectory=%DOWNLOAD_DIR% -DartifactItem.destFileName=%COMMAND_FILE% -DremoteRepositories=central::default::http://repo1.maven.apache.org/maven2,snapshots::::https://oss.sonatype.org/content/repositories/snapshots -Dtransitive=false + @call mvn org.apache.maven.plugins:maven-dependency-plugin:3.0.2:copy -Dmdep.useBaseVersion=true -Dartifact=org.apereo.cas:cas-server-support-shell:%CAS_VERSION%:jar -DoutputDirectory=%DOWNLOAD_DIR% + ) + @call java %JAVA_ARGS% -jar %DOWNLOAD_DIR%\%COMMAND_FILE% %1 %2 %3 + +@goto:eof \ No newline at end of file diff --git a/cas/cas-server/build.sh b/cas/cas-server/build.sh index e33f7de854..4d80aa2593 100644 --- a/cas/cas-server/build.sh +++ b/cas/cas-server/build.sh @@ -13,24 +13,31 @@ function help() { echo "Usage: build.sh [copy|clean|package|run|debug|bootrun|gencert]" echo " copy: Copy config from ./etc/cas/config to /etc/cas/config" echo " clean: Clean Maven build directory" - echo " package: Clean and build CAS war, also call copy" - echo " run: Build and run CAS.war via spring boot (java -jar target/cas.war)" + echo " package: Clean and build CAS war" + echo " run: Build and run cas.war via Java (i.e. java -jar target/cas.war)" + echo " runalone: Build and run cas.war on its own as a standalone executable (target/cas.war)" echo " debug: Run CAS.war and listen for Java debugger on port 5000" - echo " bootrun: Run with maven spring boot plugin, doesn't work with multiple dependencies" + echo " bootrun: Run with maven spring boot plugin" + echo " listviews: List all CAS views that ship with the web application and can be customized in the overlay" + echo " getview: Ask for a view name to be included in the overlay for customizations" echo " gencert: Create keystore with SSL certificate in location where CAS looks by default" + echo " cli: Run the CAS command line shell and pass commands" } function clean() { + shift ./mvnw clean "$@" } function package() { + shift ./mvnw clean package -T 5 "$@" - copy + # copy } function bootrun() { - ./mvnw clean package spring-boot:run -T 5 "$@" + shift + ./mvnw clean package spring-boot:run -P bootiful -T 5 "$@" } function debug() { @@ -41,14 +48,59 @@ function run() { package && java -jar target/cas.war } +function runalone() { + shift + ./mvnw clean package -P default,exec "$@" + chmod +x target/cas.war + target/cas.war +} + +function listviews() { + shift + explodeapp + find $PWD/target/cas -type f -name "*.html" | xargs -n 1 basename | sort | more +} + +function explodeapp() { + if [ ! -d $PWD/target/cas ];then + echo "Building the CAS web application and exploding the final war file..." + ./mvnw clean package war:exploded "$@" + fi + echo "Exploded the CAS web application file." +} + +function getview() { + shift + explodeapp + echo "Searching for view name $@..." + results=`find $PWD/target/cas -type f -name "*.html" | grep -i "$@"` + echo -e "Found view(s): \n$results" + count=`wc -w <<< "$results"` + if [ "$count" -eq 1 ];then + # echo "Found view $results to include in the overlay" + firststring="target/cas/WEB-INF/classes" + secondstring="src/main/resources" + overlayfile=`echo "${results/$firststring/$secondstring}"` + overlaypath=`dirname "${overlayfile}"` + # echo "Overlay file is $overlayfile to be created at $overlaypath" + mkdir -p $overlaypath + cp $results $overlaypath + echo "Created view at $overlayfile" + ls $overlayfile + else + echo "More than one view file is found. Narrow down the search query..." + fi +} + + function gencert() { - if [[ ! -d /etc/cas ]] ; then + if [[ ! -d /etc/cas ]] ; then copy fi which keytool if [[ $? -ne 0 ]] ; then - echo Error: Java JDK \'keytool\' is not installed or is not in the path - exit 1 + echo Error: Java JDK \'keytool\' is not installed or is not in the path + exit 1 fi # override DNAME and CERT_SUBJ_ALT_NAMES before calling or use dummy values DNAME="${DNAME:-CN=cas.example.org,OU=Example,OU=Org,C=US}" @@ -58,21 +110,49 @@ function gencert() { keytool -exportcert -alias cas -storepass changeit -keystore /etc/cas/thekeystore -file /etc/cas/cas.cer } +function cli() { + + CAS_VERSION=$(./mvnw -q -Dexec.executable="echo" -Dexec.args='${cas.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec 2>/dev/null) + # echo "CAS version: $CAS_VERSION" + JAR_FILE_NAME="cas-server-support-shell-${CAS_VERSION}.jar" + # echo "JAR name: $JAR_FILE_NAME" + JAR_PATH="org/apereo/cas/cas-server-support-shell/${CAS_VERSION}/${JAR_FILE_NAME}" + # echo "JAR path: $JAR_PATH" + + JAR_FILE_LOCAL="$HOME/.m2/repository/$JAR_PATH"; + # echo "Local JAR file path: $JAR_FILE_LOCAL"; + if [ -f "$JAR_FILE_LOCAL" ]; then + # echo "Using JAR file locally at $JAR_FILE_LOCAL" + java -jar $JAR_FILE_LOCAL "$@" + exit 0; + fi + + DOWNLOAD_DIR=./target + COMMAND_FILE="${DOWNLOAD_DIR}/${JAR_FILE_NAME}" + if [ ! -f "$COMMAND_FILE" ]; then + mkdir -p $DOWNLOAD_DIR + ./mvnw org.apache.maven.plugins:maven-dependency-plugin:3.0.2:get -DgroupId=org.apereo.cas -DartifactId=cas-server-support-shell -Dversion=$CAS_VERSION -Dpackaging=jar -DartifactItem.outputDirectory=$DOWNLOAD_DIR -DremoteRepositories=central::default::http://repo1.maven.apache.org/maven2,snapshots::::https://oss.sonatype.org/content/repositories/snapshots -Dtransitive=false + ./mvnw org.apache.maven.plugins:maven-dependency-plugin:3.0.2:copy -Dmdep.useBaseVersion=true -Dartifact=org.apereo.cas:cas-server-support-shell:$CAS_VERSION:jar -DoutputDirectory=$DOWNLOAD_DIR + fi + java -jar $COMMAND_FILE "$@" + exit 0; + +} + if [ $# -eq 0 ]; then echo -e "No commands provided. Defaulting to [run]\n" run exit 0 fi - case "$1" in "copy") - copy + copy ;; "clean") shift clean "$@" - ;; + ;; "package") shift package "$@" @@ -87,11 +167,23 @@ case "$1" in "run") run "$@" ;; +"runalone") + runalone "$@" + ;; +"listviews") + listviews "$@" + ;; "gencert") gencert "$@" ;; +"getview") + getview "$@" + ;; +"cli") + shift + cli "$@" + ;; *) help ;; esac - diff --git a/cas/cas-server/etc/cas/config/log4j2.xml b/cas/cas-server/etc/cas/config/log4j2.xml index 53b30b4228..e688cc0350 100644 --- a/cas/cas-server/etc/cas/config/log4j2.xml +++ b/cas/cas-server/etc/cas/config/log4j2.xml @@ -92,7 +92,7 @@ - + diff --git a/cas/cas-server/maven/maven-wrapper.jar b/cas/cas-server/maven/maven-wrapper.jar new file mode 100644 index 0000000000..18ba302c65 Binary files /dev/null and b/cas/cas-server/maven/maven-wrapper.jar differ diff --git a/cas/cas-server/maven/maven-wrapper.properties b/cas/cas-server/maven/maven-wrapper.properties index b368e4609a..97a946225a 100644 --- a/cas/cas-server/maven/maven-wrapper.properties +++ b/cas/cas-server/maven/maven-wrapper.properties @@ -1 +1,3 @@ -distributionUrl=https\://repository.apache.org/content/repositories/releases/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip +#Maven download properties +#Fri Dec 01 21:35:11 MST 2017 +distributionUrl=https\://repository.apache.org/content/repositories/releases/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip diff --git a/cas/cas-server/pom.xml b/cas/cas-server/pom.xml index 30e29b155f..a15b4b58d5 100644 --- a/cas/cas-server/pom.xml +++ b/cas/cas-server/pom.xml @@ -1,28 +1,13 @@ - + 4.0.0 com.baeldung cas-server war 1.0 - - org.springframework.boot - spring-boot-starter-parent - ${org.springframework.boot.spring-boot-starter-parent.version} - - - - - org.apereo.cas - cas-server-webapp${app.server} - ${cas.version} - war - runtime - org.apereo.cas cas-server-support-json-service-registry @@ -56,9 +41,18 @@ spring-boot-maven-plugin ${springboot.version} - org.springframework.boot.loader.WarLauncher + ${mainClassName} true + ${isExecutable} + WAR + + + + repackage + + + org.apache.maven.plugins @@ -70,8 +64,7 @@ false false - ${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF - + ${manifestFileToUse} @@ -85,16 +78,110 @@ org.apache.maven.plugins maven-compiler-plugin ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - cas + + + sonatype-releases + http://oss.sonatype.org/content/repositories/releases/ + + false + + + true + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + + true + + + false + + + + shibboleth-releases + https://build.shibboleth.net/nexus/content/repositories/releases + + + + + + true + + default + + + org.apereo.cas + cas-server-webapp${app.server} + ${cas.version} + war + runtime + + + + + + + + false + + exec + + org.apereo.cas.web.CasWebApplication + true + + + + + + com.soebes.maven.plugins + echo-maven-plugin + ${echo-maven-plugin.version} + + + prepare-package + + echo + + + + + + Executable profile to make the generated CAS web application executable. + + + + + + + + + + false + + bootiful + + -tomcat + false + + + + org.apereo.cas + cas-server-webapp${app.server} + ${cas.version} + war + runtime + + + + false @@ -126,49 +213,23 @@ - - - sonatype-releases - http://oss.sonatype.org/content/repositories/releases/ - - false - - - true - - - - sonatype-snapshots - https://oss.sonatype.org/content/repositories/snapshots/ - - true - - - false - - - - shibboleth-releases - https://build.shibboleth.net/nexus/content/repositories/releases - - - spring-milestones - https://repo.spring.io/milestone - - - - 5.1.4 - 1.5.3.RELEASE + 5.3.0-SNAPSHOT + 1.5.13.RELEASE -tomcat + + org.springframework.boot.loader.WarLauncher + false + ${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF + 1.8 1.8 UTF-8 - 2.0.0.M7 0.0.4 2.6 - 3.7.0 + 3.3 + 0.3.0 1.1.0 diff --git a/cas/cas-server/src/main/resources/application.properties b/cas/cas-server/src/main/resources/application.properties index 018fd351ff..7735fcabdc 100644 --- a/cas/cas-server/src/main/resources/application.properties +++ b/cas/cas-server/src/main/resources/application.properties @@ -43,7 +43,7 @@ spring.http.encoding.force=true ## #CAS CONFIG LOCATION # -cas.standalone.config=classpath:/etc/cas/config +standalone.config=classpath:/etc/cas/config ## @@ -109,7 +109,7 @@ cas.authn.jdbc.query[0].sql=SELECT * FROM users WHERE email = ? cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect cas.authn.jdbc.query[0].user=root -cas.authn.jdbc.query[0].password=root +cas.authn.jdbc.query[0].password=1234 cas.authn.jdbc.query[0].ddlAuto=none #cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver cas.authn.jdbc.query[0].driverClass=com.mysql.cj.jdbc.Driver diff --git a/cas/cas-server/src/main/resources/cas.properties b/cas/cas-server/src/main/resources/cas.properties index f80f22fc11..e39d68f312 100644 --- a/cas/cas-server/src/main/resources/cas.properties +++ b/cas/cas-server/src/main/resources/cas.properties @@ -3,38 +3,7 @@ cas.server.prefix: https://localhost:643/cas cas.adminPagesSecurity.ip=127\.0\.0\.1 +logging.config: file:/etc/cas/config/log4j2.xml + cas.serviceRegistry.initFromJson=true -cas.serviceRegistry.config.location=classpath:/services - -cas.authn.accept.users= -cas.authn.accept.name= - - -#CAS Database Authentication Property - -# cas.authn.jdbc.query[0].healthQuery= -# cas.authn.jdbc.query[0].isolateInternalQueries=false -# cas.authn.jdbc.query[0].failFast=true -# cas.authn.jdbc.query[0].isolationLevelName=ISOLATION_READ_COMMITTED -# cas.authn.jdbc.query[0].leakThreshold=10 -# cas.authn.jdbc.query[0].propagationBehaviorName=PROPAGATION_REQUIRED -# cas.authn.jdbc.query[0].batchSize=1 -# cas.authn.jdbc.query[0].maxAgeDays=180 -# cas.authn.jdbc.query[0].autocommit=false -# cas.authn.jdbc.query[0].idleTimeout=5000 -# cas.authn.jdbc.query[0].credentialCriteria= -# cas.authn.jdbc.query[0].name= -# cas.authn.jdbc.query[0].order=0 -# cas.authn.jdbc.query[0].dataSourceName= -# cas.authn.jdbc.query[0].dataSourceProxy=false -# cas.authn.jdbc.query[0].fieldExpired= -# cas.authn.jdbc.query[0].fieldDisabled= -# cas.authn.jdbc.query[0].principalAttributeList=sn,cn:commonName,givenName -# cas.authn.jdbc.query[0].passwordEncoder.type=NONE|DEFAULT|STANDARD|BCRYPT|SCRYPT|PBKDF2|com.example.CustomPasswordEncoder -# cas.authn.jdbc.query[0].passwordEncoder.characterEncoding= -# cas.authn.jdbc.query[0].passwordEncoder.encodingAlgorithm= -# cas.authn.jdbc.query[0].passwordEncoder.secret= -# cas.authn.jdbc.query[0].passwordEncoder.strength=16 -# cas.authn.jdbc.query[0].principalTransformation.suffix= -# cas.authn.jdbc.query[0].principalTransformation.caseConversion=NONE|UPPERCASE|LOWERCASE -# cas.authn.jdbc.query[0].principalTransformation.prefix= \ No newline at end of file +cas.serviceRegistry.config.location=classpath:/services \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml b/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml index 53b30b4228..e688cc0350 100644 --- a/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml +++ b/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml @@ -92,7 +92,7 @@ - + diff --git a/cas/cas-server/src/main/resources/etc/cas/thekeystore b/cas/cas-server/src/main/resources/etc/cas/thekeystore index 86170dff16..77bf895249 100644 Binary files a/cas/cas-server/src/main/resources/etc/cas/thekeystore and b/cas/cas-server/src/main/resources/etc/cas/thekeystore differ diff --git a/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt b/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt index 5bd9d5baba..12ef688a08 100644 Binary files a/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt and b/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt differ diff --git a/cas/cas-server/src/main/resources/log4j2.xml b/cas/cas-server/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..e688cc0350 --- /dev/null +++ b/cas/cas-server/src/main/resources/log4j2.xml @@ -0,0 +1,117 @@ + + + + + + . + + warn + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cas/cas-server/src/main/resources/services/casSecuredApp.json b/cas/cas-server/src/main/resources/services/casSecuredApp-19991.json similarity index 100% rename from cas/cas-server/src/main/resources/services/casSecuredApp.json rename to cas/cas-server/src/main/resources/services/casSecuredApp-19991.json diff --git a/cdi/README.md b/cdi/README.md index a27c35772a..0477ce85bd 100644 --- a/cdi/README.md +++ b/cdi/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: - [CDI Interceptor vs Spring AspectJ](http://www.baeldung.com/cdi-interceptor-vs-spring-aspectj) +- [An Introduction to CDI (Contexts and Dependency Injection) in Java](http://www.baeldung.com/java-ee-cdi) diff --git a/cdi/pom.xml b/cdi/pom.xml index 00cc96a7ed..2c719c1d7f 100644 --- a/cdi/pom.xml +++ b/cdi/pom.xml @@ -8,12 +8,30 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 + + org.hamcrest + hamcrest-core + ${hamcrest-core.version} + test + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + junit + junit + ${junit.version} + test + org.springframework spring-context @@ -38,9 +56,11 @@ - 4.3.4.RELEASE 1.8.9 2.4.1.Final + 1.3 + 3.10.0 + 4.12 - \ No newline at end of file + diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/application/FileApplication.java b/cdi/src/main/java/com/baeldung/dependencyinjection/application/FileApplication.java new file mode 100644 index 0000000000..2ae8ac9621 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/application/FileApplication.java @@ -0,0 +1,18 @@ +package com.baeldung.dependencyinjection.application; + +import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor; +import org.jboss.weld.environment.se.Weld; +import org.jboss.weld.environment.se.WeldContainer; + +public class FileApplication { + + public static void main(String[] args) { + Weld weld = new Weld(); + WeldContainer container = weld.initialize(); + ImageFileProcessor imageFileProcessor = container.select(ImageFileProcessor.class).get(); + System.out.println(imageFileProcessor.openFile("file1.png")); + System.out.println(imageFileProcessor.writeFile("file1.png")); + System.out.println(imageFileProcessor.saveFile("file1.png")); + container.shutdown(); + } +} \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/factories/TimeLoggerFactory.java b/cdi/src/main/java/com/baeldung/dependencyinjection/factories/TimeLoggerFactory.java new file mode 100644 index 0000000000..86916fa8c4 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/factories/TimeLoggerFactory.java @@ -0,0 +1,14 @@ +package com.baeldung.dependencyinjection.factories; + +import com.baeldung.dependencyinjection.loggers.TimeLogger; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import javax.enterprise.inject.Produces; + +public class TimeLoggerFactory { + + @Produces + public TimeLogger getTimeLogger() { + return new TimeLogger(new SimpleDateFormat("HH:mm"), Calendar.getInstance()); + } +} \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/GifFileEditor.java b/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/GifFileEditor.java new file mode 100644 index 0000000000..6b51d64a33 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/GifFileEditor.java @@ -0,0 +1,27 @@ +package com.baeldung.dependencyinjection.imagefileeditors; + +import com.baeldung.dependencyinjection.qualifiers.GifFileEditorQualifier; + +@GifFileEditorQualifier +public class GifFileEditor implements ImageFileEditor { + + @Override + public String openFile(String fileName) { + return "Opening GIF file " + fileName; + } + + @Override + public String editFile(String fileName) { + return "Editing GIF file " + fileName; + } + + @Override + public String writeFile(String fileName) { + return "Writing GIF file " + fileName; + } + + @Override + public String saveFile(String fileName) { + return "Saving GIF file " + fileName; + } +} \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/ImageFileEditor.java b/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/ImageFileEditor.java new file mode 100644 index 0000000000..d524a5160a --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/ImageFileEditor.java @@ -0,0 +1,12 @@ +package com.baeldung.dependencyinjection.imagefileeditors; + +public interface ImageFileEditor { + + String openFile(String fileName); + + String editFile(String fileName); + + String writeFile(String fileName); + + String saveFile(String fileName); +} \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/JpgFileEditor.java b/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/JpgFileEditor.java new file mode 100644 index 0000000000..97adebc1af --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/JpgFileEditor.java @@ -0,0 +1,27 @@ +package com.baeldung.dependencyinjection.imagefileeditors; + +import com.baeldung.dependencyinjection.qualifiers.JpgFileEditorQualifier; + +@JpgFileEditorQualifier +public class JpgFileEditor implements ImageFileEditor { + + @Override + public String openFile(String fileName) { + return "Opening JPG file " + fileName; + } + + @Override + public String editFile(String fileName) { + return "Editing JPG file " + fileName; + } + + @Override + public String writeFile(String fileName) { + return "Writing JPG file " + fileName; + } + + @Override + public String saveFile(String fileName) { + return "Saving JPG file " + fileName; + } +} \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/PngFileEditor.java b/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/PngFileEditor.java new file mode 100644 index 0000000000..5db608539c --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/PngFileEditor.java @@ -0,0 +1,27 @@ +package com.baeldung.dependencyinjection.imagefileeditors; + +import com.baeldung.dependencyinjection.qualifiers.PngFileEditorQualifier; + +@PngFileEditorQualifier +public class PngFileEditor implements ImageFileEditor { + + @Override + public String openFile(String fileName) { + return "Opening PNG file " + fileName; + } + + @Override + public String editFile(String fileName) { + return "Editing PNG file " + fileName; + } + + @Override + public String writeFile(String fileName) { + return "Writing PNG file " + fileName; + } + + @Override + public String saveFile(String fileName) { + return "Saving PNG file " + fileName; + } +} \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/imageprocessors/ImageFileProcessor.java b/cdi/src/main/java/com/baeldung/dependencyinjection/imageprocessors/ImageFileProcessor.java new file mode 100644 index 0000000000..1527108568 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/imageprocessors/ImageFileProcessor.java @@ -0,0 +1,42 @@ +package com.baeldung.dependencyinjection.imageprocessors; + +import com.baeldung.dependencyinjection.loggers.TimeLogger; +import com.baeldung.dependencyinjection.qualifiers.PngFileEditorQualifier; +import javax.inject.Inject; +import com.baeldung.dependencyinjection.imagefileeditors.ImageFileEditor; + +public class ImageFileProcessor { + + private final ImageFileEditor imageFileEditor; + private final TimeLogger timeLogger; + + @Inject + public ImageFileProcessor(@PngFileEditorQualifier ImageFileEditor imageFileEditor, TimeLogger timeLogger) { + this.imageFileEditor = imageFileEditor; + this.timeLogger = timeLogger; + } + + public ImageFileEditor getImageFileditor() { + return imageFileEditor; + } + + public TimeLogger getTimeLogger() { + return timeLogger; + } + + public String openFile(String fileName) { + return imageFileEditor.openFile(fileName) + " at: " + timeLogger.getTime(); + } + + public String editFile(String fileName) { + return imageFileEditor.editFile(fileName) + " at: " + timeLogger.getTime(); + } + + public String writeFile(String fileName) { + return imageFileEditor.writeFile(fileName) + " at: " + timeLogger.getTime(); + } + + public String saveFile(String fileName) { + return imageFileEditor.saveFile(fileName)+ " at: " + timeLogger.getTime(); + } +} \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/loggers/TimeLogger.java b/cdi/src/main/java/com/baeldung/dependencyinjection/loggers/TimeLogger.java new file mode 100644 index 0000000000..44223d7e5d --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/loggers/TimeLogger.java @@ -0,0 +1,19 @@ +package com.baeldung.dependencyinjection.loggers; + +import java.text.SimpleDateFormat; +import java.util.Calendar; + +public class TimeLogger { + + private final SimpleDateFormat dateFormat; + private final Calendar calendar; + + public TimeLogger(SimpleDateFormat dateFormat, Calendar calendar) { + this.dateFormat = dateFormat; + this.calendar = calendar; + } + + public String getTime() { + return dateFormat.format(calendar.getTime()); + } +} \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/qualifiers/GifFileEditorQualifier.java b/cdi/src/main/java/com/baeldung/dependencyinjection/qualifiers/GifFileEditorQualifier.java new file mode 100644 index 0000000000..3660aad15e --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/qualifiers/GifFileEditorQualifier.java @@ -0,0 +1,12 @@ +package com.baeldung.dependencyinjection.qualifiers; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import javax.inject.Qualifier; + +@Qualifier +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER}) +public @interface GifFileEditorQualifier {} \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/qualifiers/JpgFileEditorQualifier.java b/cdi/src/main/java/com/baeldung/dependencyinjection/qualifiers/JpgFileEditorQualifier.java new file mode 100644 index 0000000000..c8a007bcab --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/qualifiers/JpgFileEditorQualifier.java @@ -0,0 +1,12 @@ +package com.baeldung.dependencyinjection.qualifiers; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import javax.inject.Qualifier; + +@Qualifier +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER}) +public @interface JpgFileEditorQualifier {} diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/qualifiers/PngFileEditorQualifier.java b/cdi/src/main/java/com/baeldung/dependencyinjection/qualifiers/PngFileEditorQualifier.java new file mode 100644 index 0000000000..51d2fba315 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/qualifiers/PngFileEditorQualifier.java @@ -0,0 +1,12 @@ +package com.baeldung.dependencyinjection.qualifiers; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import javax.inject.Qualifier; + +@Qualifier +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER}) +public @interface PngFileEditorQualifier {} diff --git a/cdi/src/main/resources/logback.xml b/cdi/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/cdi/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/cdi/src/test/java/com/baeldung/test/dependencyinjection/GifFileEditorUnitTest.java b/cdi/src/test/java/com/baeldung/test/dependencyinjection/GifFileEditorUnitTest.java new file mode 100644 index 0000000000..3b148049b5 --- /dev/null +++ b/cdi/src/test/java/com/baeldung/test/dependencyinjection/GifFileEditorUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.test.dependencyinjection; + +import com.baeldung.dependencyinjection.imagefileeditors.GifFileEditor; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +public class GifFileEditorUnitTest { + + private static GifFileEditor gifFileEditor; + + + @BeforeClass + public static void setGifFileEditorInstance() { + gifFileEditor = new GifFileEditor(); + } + + @Test + public void givenGifFileEditorlInstance_whenCalledopenFile_thenOneAssertion() { + assertThat(gifFileEditor.openFile("file1.gif")).isEqualTo("Opening GIF file file1.gif"); + } + + @Test + public void givenGifFileEditorlInstance_whenCallededitFile_thenOneAssertion() { + assertThat(gifFileEditor.editFile("file1.gif")).isEqualTo("Editing GIF file file1.gif"); + } + + @Test + public void givenGifFileEditorInstance_whenCalledwriteFile_thenOneAssertion() { + assertThat(gifFileEditor.writeFile("file1.gif")).isEqualTo("Writing GIF file file1.gif"); + } + + @Test + public void givenGifFileEditorInstance_whenCalledsaveFile_thenOneAssertion() { + assertThat(gifFileEditor.saveFile("file1.gif")).isEqualTo("Saving GIF file file1.gif"); + } +} \ No newline at end of file diff --git a/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java b/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java new file mode 100644 index 0000000000..930e913109 --- /dev/null +++ b/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java @@ -0,0 +1,91 @@ +package com.baeldung.test.dependencyinjection; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.within; + +import java.text.ParseException; +import java.time.LocalTime; +import java.time.temporal.ChronoUnit; + +import org.jboss.weld.environment.se.Weld; +import org.jboss.weld.environment.se.WeldContainer; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor; +import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor; +import com.baeldung.dependencyinjection.loggers.TimeLogger; + +public class ImageProcessorUnitTest { + + private static ImageFileProcessor imageFileProcessor; + + @BeforeClass + public static void setImageProcessorInstance() { + Weld weld = new Weld(); + WeldContainer container = weld.initialize(); + imageFileProcessor = container.select(ImageFileProcessor.class) + .get(); + container.shutdown(); + } + + @Test + public void givenImageProcessorInstance_whenInjectedPngFileEditorandTimeLoggerInstances_thenTwoAssertions() { + assertThat(imageFileProcessor.getImageFileditor()).isInstanceOf(PngFileEditor.class); + assertThat(imageFileProcessor.getTimeLogger()).isInstanceOf(TimeLogger.class); + } + + @Test + public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() throws ParseException { + LocalTime currentTime = LocalTime.now(); + + String openFileLog = imageFileProcessor.openFile("file1.png"); + assertThat(openFileLog).contains("Opening PNG file file1.png at: "); + + LocalTime loggedTime = getLoggedTime(openFileLog); + assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES)); + } + + @Test + public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() throws ParseException { + LocalTime currentTime = LocalTime.now(); + + String editFileLog = imageFileProcessor.editFile("file1.png"); + assertThat(editFileLog).contains("Editing PNG file file1.png at: "); + + LocalTime loggedTime = getLoggedTime(editFileLog); + assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES)); + } + + @Test + public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() throws ParseException { + LocalTime currentTime = LocalTime.now(); + + String writeFileLog = imageFileProcessor.writeFile("file1.png"); + assertThat(writeFileLog).contains("Writing PNG file file1.png at: "); + + LocalTime loggedTime = getLoggedTime(writeFileLog); + assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES)); + } + + @Test + public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() throws ParseException { + LocalTime currentTime = LocalTime.now(); + + String saveFileLog = imageFileProcessor.saveFile("file1.png"); + assertThat(saveFileLog).contains("Saving PNG file file1.png at: "); + + LocalTime loggedTime = getLoggedTime(saveFileLog); + assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES)); + } + + private LocalTime getLoggedTime(String log) throws ParseException { + String logTimeString = log.split("at: ")[1]; + + int hour = Integer.valueOf(logTimeString.split(":")[0]); + int minutes = Integer.valueOf(logTimeString.split(":")[1]); + + LocalTime loggedTime = LocalTime.of(hour, minutes); + return loggedTime; + } +} \ No newline at end of file diff --git a/cdi/src/test/java/com/baeldung/test/dependencyinjection/JpgFileEditorUnitTest.java b/cdi/src/test/java/com/baeldung/test/dependencyinjection/JpgFileEditorUnitTest.java new file mode 100644 index 0000000000..4f3954c0bc --- /dev/null +++ b/cdi/src/test/java/com/baeldung/test/dependencyinjection/JpgFileEditorUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.test.dependencyinjection; + +import com.baeldung.dependencyinjection.imagefileeditors.JpgFileEditor; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +public class JpgFileEditorUnitTest { + + private static JpgFileEditor jpgFileUtil; + + + @BeforeClass + public static void setJpgFileEditorInstance() { + jpgFileUtil = new JpgFileEditor(); + } + + @Test + public void givenJpgFileEditorInstance_whenCalledopenFile_thenOneAssertion() { + assertThat(jpgFileUtil.openFile("file1.jpg")).isEqualTo("Opening JPG file file1.jpg"); + } + + @Test + public void givenJpgFileEditorlInstance_whenCallededitFile_thenOneAssertion() { + assertThat(jpgFileUtil.editFile("file1.gif")).isEqualTo("Editing JPG file file1.gif"); + } + + @Test + public void givenJpgFileEditorInstance_whenCalledwriteFile_thenOneAssertion() { + assertThat(jpgFileUtil.writeFile("file1.jpg")).isEqualTo("Writing JPG file file1.jpg"); + } + + @Test + public void givenJpgFileEditorInstance_whenCalledsaveFile_thenOneAssertion() { + assertThat(jpgFileUtil.saveFile("file1.jpg")).isEqualTo("Saving JPG file file1.jpg"); + } +} \ No newline at end of file diff --git a/cdi/src/test/java/com/baeldung/test/dependencyinjection/PngFileEditorUnitTest.java b/cdi/src/test/java/com/baeldung/test/dependencyinjection/PngFileEditorUnitTest.java new file mode 100644 index 0000000000..d16f6d576e --- /dev/null +++ b/cdi/src/test/java/com/baeldung/test/dependencyinjection/PngFileEditorUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.test.dependencyinjection; + +import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor; +import com.baeldung.dependencyinjection.qualifiers.PngFileEditorQualifier; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +@PngFileEditorQualifier +public class PngFileEditorUnitTest { + + private static PngFileEditor pngFileEditor; + + + @BeforeClass + public static void setPngFileEditorInstance() { + pngFileEditor = new PngFileEditor(); + } + + @Test + public void givenPngFileEditorInstance_whenCalledopenFile_thenOneAssertion() { + assertThat(pngFileEditor.openFile("file1.png")).isEqualTo("Opening PNG file file1.png"); + } + + @Test + public void givenPngFileEditorInstance_whenCallededitFile_thenOneAssertion() { + assertThat(pngFileEditor.editFile("file1.png")).isEqualTo("Editing PNG file file1.png"); + } + + @Test + public void givenPngFileEditorInstance_whenCalledwriteFile_thenOneAssertion() { + assertThat(pngFileEditor.writeFile("file1.png")).isEqualTo("Writing PNG file file1.png"); + } + + @Test + public void givenPngFileEditorInstance_whenCalledsaveFile_thenOneAssertion() { + assertThat(pngFileEditor.saveFile("file1.png")).isEqualTo("Saving PNG file file1.png"); + } +} diff --git a/cdi/src/test/java/com/baeldung/test/dependencyinjection/TimeLoggerFactoryUnitTest.java b/cdi/src/test/java/com/baeldung/test/dependencyinjection/TimeLoggerFactoryUnitTest.java new file mode 100644 index 0000000000..caf2ed32b5 --- /dev/null +++ b/cdi/src/test/java/com/baeldung/test/dependencyinjection/TimeLoggerFactoryUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.test.dependencyinjection; + +import com.baeldung.dependencyinjection.factories.TimeLoggerFactory; +import com.baeldung.dependencyinjection.loggers.TimeLogger; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class TimeLoggerFactoryUnitTest { + + @Test + public void givenTimeLoggerFactory_whenCalledgetTimeLogger_thenOneAssertion() { + TimeLoggerFactory timeLoggerFactory = new TimeLoggerFactory(); + assertThat(timeLoggerFactory.getTimeLogger()).isInstanceOf(TimeLogger.class); + } +} diff --git a/cdi/src/test/java/com/baeldung/test/dependencyinjection/TimeLoggerUnitTest.java b/cdi/src/test/java/com/baeldung/test/dependencyinjection/TimeLoggerUnitTest.java new file mode 100644 index 0000000000..222de251fe --- /dev/null +++ b/cdi/src/test/java/com/baeldung/test/dependencyinjection/TimeLoggerUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.test.dependencyinjection; + +import com.baeldung.dependencyinjection.loggers.TimeLogger; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class TimeLoggerUnitTest { + + + @Test + public void givenTimeLoggerInstance_whenCalledgetLogTime_thenOneAssertion() { + SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm"); + Calendar calendar = Calendar.getInstance(); + TimeLogger timeLogger = new TimeLogger(dateFormat, calendar); + String currentTime = dateFormat.format(calendar.getTime()); + assertThat(timeLogger.getTime()).isEqualTo(currentTime); + } +} \ No newline at end of file diff --git a/checker-plugin/pom.xml b/checker-plugin/pom.xml index 01d7a30bfd..45f0939e77 100644 --- a/checker-plugin/pom.xml +++ b/checker-plugin/pom.xml @@ -41,33 +41,12 @@ - - - org.apache.maven.plugins - maven-dependency-plugin - - - - - properties - - - - - maven-compiler-plugin ${maven-compiler-plugin.version} - ${maven.compiler.source} - ${maven.compiler.target} + ${java.version} + ${java.version} @@ -113,8 +92,6 @@ 2.3.1 2.3.1 2.3.1 - 1.8 - 1.8 diff --git a/checker-plugin/src/main/resources/logback.xml b/checker-plugin/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/checker-plugin/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/core-groovy/pom.xml b/core-groovy/pom.xml index 9076e63642..909250710e 100644 --- a/core-groovy/pom.xml +++ b/core-groovy/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-groovy 1.0-SNAPSHOT @@ -101,24 +101,13 @@ - UTF-8 - 1.1.2 - 1.1.2 - 1.1.2 - 1.1.2 - 0.15 - 1.5.0 - 5.0.0 1.0.0 - 4.12.0 - 4.12 2.4.13 2.4.13 2.4.13 2.4.0 1.1-groovy-2.4 1.6 - 2.19.1 diff --git a/core-groovy/src/main/resources/logback.xml b/core-groovy/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/core-groovy/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/core-java-10/README.md b/core-java-10/README.md new file mode 100644 index 0000000000..84fa381a26 --- /dev/null +++ b/core-java-10/README.md @@ -0,0 +1,6 @@ + +### Relevant Articles: + +- [Java 10 LocalVariable Type-Inference](http://www.baeldung.com/java-10-local-variable-type-inference) +- [Guide to Java 10](http://www.baeldung.com/java-10-overview) +- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another) diff --git a/core-java-10/pom.xml b/core-java-10/pom.xml index 8a19893b13..9fcdd9a162 100644 --- a/core-java-10/pom.xml +++ b/core-java-10/pom.xml @@ -1,45 +1,36 @@ - 4.0.0 - com.baeldung - core-java-10 - jar - 0.1.0-SNAPSHOT - core-java-10 - http://maven.apache.org + 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 + core-java-10 + jar + 0.1.0-SNAPSHOT + core-java-10 + http://maven.apache.org - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - - junit - junit - ${junit.version} - test - - + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source.version} + ${maven.compiler.target.version} + + + + - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source.version} - ${maven.compiler.target.version} - - - - - - - 10 - 10 - + + 10 + 10 + diff --git a/core-java-10/src/main/resources/logback.xml b/core-java-10/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/core-java-10/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java b/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java new file mode 100644 index 0000000000..f529e219a6 --- /dev/null +++ b/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java @@ -0,0 +1,14 @@ +package com.baeldung.java10.list; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +public class CopyListServiceUnitTest { + + @Test(expected = UnsupportedOperationException.class) + public void whenModifyCopyOfList_thenThrowsException() { + List copyList = List.copyOf(Arrays.asList(1, 2, 3, 4)); + } +} diff --git a/core-java-11/pom.xml b/core-java-11/pom.xml index 5cdb5c0640..4dcab49867 100644 --- a/core-java-11/pom.xml +++ b/core-java-11/pom.xml @@ -1,45 +1,36 @@ - 4.0.0 - com.baeldung - core-java-11 - jar - 0.1.0-SNAPSHOT - core-java-11 - http://maven.apache.org + 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 + core-java-11 + jar + 0.1.0-SNAPSHOT + core-java-11 + http://maven.apache.org - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - - junit - junit - ${junit.version} - test - - + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source.version} + ${maven.compiler.target.version} + + + + - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source.version} - ${maven.compiler.target.version} - - - - - - - 11 - 11 - + + 11 + 11 + diff --git a/core-java-11/src/main/resources/logback.xml b/core-java-11/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/core-java-11/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/core-java-8/README.md b/core-java-8/README.md index f0d7818f5b..64d423aafe 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -9,45 +9,26 @@ - [Java 8 New Features](http://www.baeldung.com/java-8-new-features) - [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) - [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator) -- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams) -- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction) - [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector) - [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern) -- [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams) -- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings) - [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions) -- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany) - [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing) -- [How to Get the Last Element of a Stream in Java?](http://www.baeldung.com/java-stream-last-element) -- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro) -- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api) - [Guide To Java 8 Optional](http://www.baeldung.com/java-optional) - [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java) -- [Get the Current Date, Time and Timestamp in Java 8](http://www.baeldung.com/current-date-time-and-timestamp-in-java-8) -- [TemporalAdjuster in Java](http://www.baeldung.com/java-temporal-adjuster) -- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max) - [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode) - [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap) -- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams) -- [“Stream has already been operated upon or closed†Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception) -- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones) -- [Copy a File with Java](http://www.baeldung.com/java-copy-file) -- [Generating Prime Numbers in Java](http://www.baeldung.com/java-generate-prime-numbers) - [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods) -- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream) -- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream) -- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices) - [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency) -- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams) -- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator) -- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection) -- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner) - [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator) - [Java 8 Math New Methods](http://www.baeldung.com/java-8-math) - [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations) - [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max) - [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization) -- [Filtering Kotlin Collections](http://www.baeldung.com/kotlin-filter-collection) -- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java) -- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time) - +- [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get) +- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection) +- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic) +- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference) +- [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time) +- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone) +- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance) +- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects) diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index aab349781a..18bdaa15f4 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -1,5 +1,5 @@ + 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 core-java-8 @@ -10,8 +10,8 @@ com.baeldung parent-java - 0.0.1-SNAPSHOT - ../parent-java + 0.0.1-SNAPSHOT + ../parent-java @@ -90,9 +90,19 @@ ${vavr.version} - one.util - streamex - ${streamex.version} + joda-time + joda-time + ${joda.version} + + + org.aspectj + aspectjrt + ${asspectj.version} + + + org.aspectj + aspectjweaver + ${asspectj.version} @@ -108,96 +118,18 @@ org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - prepare-package - - copy-dependencies - - - ${project.build.directory}/libs - - - - - - - org.apache.maven.plugins - maven-jar-plugin + maven-compiler-plugin + 3.1 - - - true - libs/ - org.baeldung.executable.ExecutableMavenJar - - + 1.8 + 1.8 + -parameters - - org.apache.maven.plugins - maven-assembly-plugin - - - package - - single - - - ${project.basedir} - - - org.baeldung.executable.ExecutableMavenJar - - - - jar-with-dependencies - - - - - - - org.apache.maven.plugins - maven-shade-plugin - - - - shade - - - true - - - org.baeldung.executable.ExecutableMavenJar - - - - - - - - com.jolira - onejar-maven-plugin - - - - org.baeldung.executable.ExecutableMavenJar - true - ${project.build.finalName}-onejar.${project.packaging} - - - one-jar - - - - org.springframework.boot spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} @@ -215,22 +147,21 @@ - 21.0 3.5 3.6.1 - 2.5 4.1 4.01 1.10 1.16.12 0.9.0 1.13 - 0.6.5 + 2.10 3.6.1 + 1.8.9 1.7.0 1.19 1.19 + 2.0.4.RELEASE - - \ No newline at end of file + diff --git a/core-java-8/src/main/java/com/baeldung/aspect/ChangeCallsToCurrentTimeInMillisMethod.aj b/core-java-8/src/main/java/com/baeldung/aspect/ChangeCallsToCurrentTimeInMillisMethod.aj new file mode 100644 index 0000000000..b28bebfdaf --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/aspect/ChangeCallsToCurrentTimeInMillisMethod.aj @@ -0,0 +1,9 @@ +package com.baeldung.aspect; + +public aspect ChangeCallsToCurrentTimeInMillisMethod { + long around(): + call(public static native long java.lang.System.currentTimeMillis()) + && within(user.code.base.pckg.*) { + return 0; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java deleted file mode 100644 index 0d727cf0b5..0000000000 --- a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.datetime; - -import java.time.DayOfWeek; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.temporal.ChronoUnit; -import java.time.temporal.TemporalAdjusters; - -class UseLocalDate { - - LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) { - return LocalDate.of(year, month, dayOfMonth); - } - - LocalDate getLocalDateUsingParseMethod(String representation) { - return LocalDate.parse(representation); - } - - LocalDate getLocalDateFromClock() { - LocalDate localDate = LocalDate.now(); - return localDate; - } - - LocalDate getNextDay(LocalDate localDate) { - return localDate.plusDays(1); - } - - LocalDate getPreviousDay(LocalDate localDate) { - return localDate.minus(1, ChronoUnit.DAYS); - } - - DayOfWeek getDayOfWeek(LocalDate localDate) { - DayOfWeek day = localDate.getDayOfWeek(); - return day; - } - - LocalDate getFirstDayOfMonth() { - LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()); - return firstDayOfMonth; - } - - LocalDateTime getStartOfDay(LocalDate localDate) { - LocalDateTime startofDay = localDate.atStartOfDay(); - return startofDay; - } -} diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java b/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java deleted file mode 100644 index f5e1af0a06..0000000000 --- a/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.datetime; - -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZonedDateTime; - -class UseZonedDateTime { - - ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) { - return ZonedDateTime.of(localDateTime, zoneId); - } -} diff --git a/core-java-8/src/main/java/com/baeldung/list/Flower.java b/core-java-8/src/main/java/com/baeldung/list/Flower.java new file mode 100644 index 0000000000..29c6a78326 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/list/Flower.java @@ -0,0 +1,28 @@ +package com.baeldung.list; + +public class Flower { + + private String name; + private int petals; + + public Flower(String name, int petals) { + this.name = name; + this.petals = petals; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getPetals() { + return petals; + } + + public void setPetals(int petals) { + this.petals = petals; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java new file mode 100644 index 0000000000..7587cc6834 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java @@ -0,0 +1,19 @@ +package com.baeldung.nullsafecollectionstreams; + +import java.util.Collection; +import java.util.stream.Stream; +import static org.apache.commons.collections4.CollectionUtils.emptyIfNull; + +public class NullSafeCollectionStreamsUsingCommonsEmptyIfNull { + + /** + * This method shows how to make a null safe stream from a collection through the use of + * emptyIfNull() method from Apache Commons CollectionUtils library + * + * @param collection The collection that is to be converted into a stream + * @return The stream that has been created from the collection or an empty stream if the collection is null + */ + public Stream collectionAsStream(Collection collection) { + return emptyIfNull(collection).stream(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java new file mode 100644 index 0000000000..ae8e399d53 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java @@ -0,0 +1,21 @@ +package com.baeldung.nullsafecollectionstreams; + +import java.util.Collection; +import java.util.Optional; +import java.util.stream.Stream; + +public class NullSafeCollectionStreamsUsingJava8OptionalContainer { + + /** + * This method shows how to make a null safe stream from a collection through the use of + * Java SE 8’s Optional Container + * + * @param collection The collection that is to be converted into a stream + * @return The stream that has been created from the collection or an empty stream if the collection is null + */ + public Stream collectionAsStream(Collection collection) { + return Optional.ofNullable(collection) + .map(Collection::stream) + .orElseGet(Stream::empty); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java new file mode 100644 index 0000000000..63b6d34f11 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java @@ -0,0 +1,20 @@ +package com.baeldung.nullsafecollectionstreams; + +import java.util.Collection; +import java.util.stream.Stream; + +public class NullSafeCollectionStreamsUsingNullDereferenceCheck { + + /** + * This method shows how to make a null safe stream from a collection through the use of a check + * to prevent null dereferences + * + * @param collection The collection that is to be converted into a stream + * @return The stream that has been created from the collection or an empty stream if the collection is null + */ + public Stream collectionAsStream(Collection collection) { + return collection == null ? Stream.empty() : collection.stream(); + } + + +} diff --git a/core-java-8/src/main/java/com/baeldung/optional/PersonRepository.java b/core-java-8/src/main/java/com/baeldung/optional/PersonRepository.java new file mode 100644 index 0000000000..46018faf80 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/optional/PersonRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.optional; + +public class PersonRepository { + + public String findNameById(String id) { + return id == null ? null : "Name"; + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BenchmarkRunner.java b/core-java-8/src/main/java/com/baeldung/primitive/BenchmarkRunner.java new file mode 100644 index 0000000000..2513ec0d03 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/BenchmarkRunner.java @@ -0,0 +1,23 @@ +package com.baeldung.primitive; + +public class BenchmarkRunner { + + public static void main(String[] args) throws Exception { + new IntPrimitiveLookup().run(); + new IntegerWrapperLookup().run(); + new FloatPrimitiveLookup().run(); + new FloatWrapperLookup().run(); + new DoublePrimitiveLookup().run(); + new DoubleWrapperLookup().run(); + new ShortPrimitiveLookup().run(); + new ShortWrapperLookup().run(); + new BooleanPrimitiveLookup().run(); + new BooleanWrapperLookup().run(); + new CharPrimitiveLookup().run(); + new CharacterWrapperLookup().run(); + new BytePrimitiveLookup().run(); + new ByteWrapperLookup().run(); + new LongPrimitiveLookup().run(); + new LongWrapperLookup().run(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BooleanPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/BooleanPrimitiveLookup.java new file mode 100644 index 0000000000..2ad698eba4 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/BooleanPrimitiveLookup.java @@ -0,0 +1,45 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class BooleanPrimitiveLookup extends Lookup { + + private boolean[] elements; + private final boolean pivot = false; + + @Setup + @Override + public void prepare() { + elements = new boolean[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = true; + } + elements[s - 1] = pivot; + } + + @TearDown + @Override + public void clean() { + elements = null; + } + + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + while (pivot != elements[index]) { + index++; + } + return index; + } + + @Override + public String getSimpleClassName() { + return BooleanPrimitiveLookup.class.getSimpleName(); + } + + + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BooleanWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/BooleanWrapperLookup.java new file mode 100644 index 0000000000..8d996739a8 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/BooleanWrapperLookup.java @@ -0,0 +1,45 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class BooleanWrapperLookup extends Lookup { + private Boolean[] elements; + private final boolean pivot = false; + + @Override + @Setup + public void prepare() { + elements = new Boolean[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = true; + } + elements[s - 1] = pivot; + } + + @Override + @TearDown + public void clean() { + elements = null; + } + + @Override + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + Boolean pivotWrapper = pivot; + while (!pivotWrapper.equals(elements[index])) { + index++; + } + return index; + + } + + @Override + public String getSimpleClassName() { + return BooleanWrapperLookup.class.getSimpleName(); + } + + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BytePrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/BytePrimitiveLookup.java new file mode 100644 index 0000000000..73eda5cf5b --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/BytePrimitiveLookup.java @@ -0,0 +1,46 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class BytePrimitiveLookup extends Lookup { + + private byte[] elements; + private final byte pivot = 2; + + @Setup + @Override + public void prepare() { + byte common = 1; + elements = new byte[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @TearDown + @Override + public void clean() { + elements = null; + } + + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + while (pivot != elements[index]) { + index++; + } + return index; + } + + @Override + public String getSimpleClassName() { + return BytePrimitiveLookup.class.getSimpleName(); + } + + + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/ByteWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/ByteWrapperLookup.java new file mode 100644 index 0000000000..23e02315a6 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/ByteWrapperLookup.java @@ -0,0 +1,46 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class ByteWrapperLookup extends Lookup { + private Byte[] elements; + private final byte pivot = 2; + + @Override + @Setup + public void prepare() { + byte common = 1; + elements = new Byte[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @Override + @TearDown + public void clean() { + elements = null; + } + + @Override + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + Byte pivotWrapper = pivot; + while (!pivotWrapper.equals(elements[index])) { + index++; + } + return index; + + } + + @Override + public String getSimpleClassName() { + return ByteWrapperLookup.class.getSimpleName(); + } + + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/CharPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/CharPrimitiveLookup.java new file mode 100644 index 0000000000..a6d4be6206 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/CharPrimitiveLookup.java @@ -0,0 +1,46 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class CharPrimitiveLookup extends Lookup { + + private char[] elements; + private final char pivot = 'b'; + + @Setup + @Override + public void prepare() { + char common = 'a'; + elements = new char[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @TearDown + @Override + public void clean() { + elements = null; + } + + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + while (pivot != elements[index]) { + index++; + } + return index; + } + + @Override + public String getSimpleClassName() { + return CharPrimitiveLookup.class.getSimpleName(); + } + + + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/CharacterWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/CharacterWrapperLookup.java new file mode 100644 index 0000000000..9509b4a156 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/CharacterWrapperLookup.java @@ -0,0 +1,46 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class CharacterWrapperLookup extends Lookup { + private Character[] elements; + private final char pivot = 'b'; + + @Override + @Setup + public void prepare() { + char common = 'a'; + elements = new Character[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @Override + @TearDown + public void clean() { + elements = null; + } + + @Override + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + Character pivotWrapper = pivot; + while (!pivotWrapper.equals(elements[index])) { + index++; + } + return index; + + } + + @Override + public String getSimpleClassName() { + return CharacterWrapperLookup.class.getSimpleName(); + } + + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/DoublePrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/DoublePrimitiveLookup.java new file mode 100644 index 0000000000..f95515a02d --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/DoublePrimitiveLookup.java @@ -0,0 +1,42 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class DoublePrimitiveLookup extends Lookup { + private double[] elements; + private final double pivot = 2; + + @Setup + @Override + public void prepare() { + double common = 1; + elements = new double[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @TearDown + @Override + public void clean() { + elements = null; + } + + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + while (pivot != elements[index]) { + index++; + } + return index; + } + + @Override + public String getSimpleClassName() { + return DoublePrimitiveLookup.class.getSimpleName(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/DoubleWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/DoubleWrapperLookup.java new file mode 100644 index 0000000000..671c2ccc29 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/DoubleWrapperLookup.java @@ -0,0 +1,45 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class DoubleWrapperLookup extends Lookup { + private Double[] elements; + private final double pivot = 2d; + + @Override + @Setup + public void prepare() { + double common = 1; + elements = new Double[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @Override + @TearDown + public void clean() { + elements = null; + } + + @Override + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + Double pivotWrapper = pivot; + while (!pivotWrapper.equals(elements[index])) { + index++; + } + return index; + + } + + @Override + public String getSimpleClassName() { + return DoubleWrapperLookup.class.getSimpleName(); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/FloatPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/FloatPrimitiveLookup.java new file mode 100644 index 0000000000..26b58f0053 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/FloatPrimitiveLookup.java @@ -0,0 +1,42 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class FloatPrimitiveLookup extends Lookup { + private float[] elements; + private final float pivot = 2; + + @Setup + @Override + public void prepare() { + int common = 1; + elements = new float[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @TearDown + @Override + public void clean() { + elements = null; + } + + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + while (pivot != elements[index]) { + index++; + } + return index; + } + + @Override + public String getSimpleClassName() { + return FloatPrimitiveLookup.class.getSimpleName(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/FloatWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/FloatWrapperLookup.java new file mode 100644 index 0000000000..8e75eae3e3 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/FloatWrapperLookup.java @@ -0,0 +1,43 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class FloatWrapperLookup extends Lookup { + private Float[] elements; + private final float pivot = 2; + + @Override + @Setup + public void prepare() { + float common = 1; + elements = new Float[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @Override + @TearDown + public void clean() { + elements = null; + } + + @Override + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + Float pivotWrapper = pivot; + while (!pivotWrapper.equals(elements[index])) { + index++; + } + return index; + } + + @Override + public String getSimpleClassName() { + return FloatWrapperLookup.class.getSimpleName(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/IntPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/IntPrimitiveLookup.java new file mode 100644 index 0000000000..551163dba2 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/IntPrimitiveLookup.java @@ -0,0 +1,45 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class IntPrimitiveLookup extends Lookup { + + private int[] elements; + private final int pivot = 2; + + @Setup + @Override + public void prepare() { + int common = 1; + elements = new int[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @TearDown + @Override + public void clean() { + elements = null; + } + + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + while (pivot != elements[index]) { + index++; + } + return index; + } + + @Override + public String getSimpleClassName() { + return IntPrimitiveLookup.class.getSimpleName(); + } + + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/IntegerWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/IntegerWrapperLookup.java new file mode 100644 index 0000000000..f39fb80a0b --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/IntegerWrapperLookup.java @@ -0,0 +1,45 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class IntegerWrapperLookup extends Lookup { + private Integer[] elements; + private final int pivot = 2; + + @Override + @Setup + public void prepare() { + int common = 1; + elements = new Integer[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @Override + @TearDown + public void clean() { + elements = null; + } + + @Override + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + Integer pivotWrapper = pivot; + while (!pivotWrapper.equals(elements[index])) { + index++; + } + return index; + + } + + @Override + public String getSimpleClassName() { + return IntegerWrapperLookup.class.getSimpleName(); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/LongPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/LongPrimitiveLookup.java new file mode 100644 index 0000000000..2f414577da --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/LongPrimitiveLookup.java @@ -0,0 +1,42 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class LongPrimitiveLookup extends Lookup { + private long[] elements; + private final long pivot = 2; + + @Setup + @Override + public void prepare() { + long common = 1; + elements = new long[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @TearDown + @Override + public void clean() { + elements = null; + } + + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + while (pivot != elements[index]) { + index++; + } + return index; + } + + @Override + public String getSimpleClassName() { + return LongPrimitiveLookup.class.getSimpleName(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/LongWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/LongWrapperLookup.java new file mode 100644 index 0000000000..692a9fd15c --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/LongWrapperLookup.java @@ -0,0 +1,45 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class LongWrapperLookup extends Lookup{ + private Long[] elements; + private final long pivot = 2; + + @Override + @Setup + public void prepare() { + long common = 1; + elements = new Long[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @Override + @TearDown + public void clean() { + elements = null; + } + + @Override + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + Long pivotWrapper = pivot; + while (!pivotWrapper.equals(elements[index])) { + index++; + } + return index; + + } + + @Override + public String getSimpleClassName() { + return LongWrapperLookup.class.getSimpleName(); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/Lookup.java b/core-java-8/src/main/java/com/baeldung/primitive/Lookup.java new file mode 100644 index 0000000000..3dc7b7655e --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/Lookup.java @@ -0,0 +1,56 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.results.RunResult; +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; + +import java.util.Collection; + +/** + * An abstract class that is to be extended by the classes that + * perform lookup in the arrays either of Java primitive types or their wrappers. + */ +public abstract class Lookup { + /** + * the array size + */ + final protected int s = 50000000; + + /** + * Initialize the array: fill in the array with the same + * elements except for the last one. + */ + abstract public void prepare(); + + /** + * Free the array's reference. + */ + abstract public void clean(); + + /** + * Find the position of the element that is different from the others. + * By construction, it is the last array element. + * + * @return array's last element index + */ + abstract public int findPosition(); + + /** + * Get the name of the class that extends this one. It is needed in order + * to set up the benchmark. + * + * @return + */ + abstract public String getSimpleClassName(); + + Collection run() throws RunnerException { + Options opt = new OptionsBuilder() + .include(getSimpleClassName()) + .forks(1) + .build(); + return new Runner(opt).run(); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/ShortPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/ShortPrimitiveLookup.java new file mode 100644 index 0000000000..2d2ffbd67b --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/ShortPrimitiveLookup.java @@ -0,0 +1,45 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class ShortPrimitiveLookup extends Lookup { + + private short[] elements; + private final short pivot = 2; + + @Setup + @Override + public void prepare() { + short common = 1; + elements = new short[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @TearDown + @Override + public void clean() { + elements = null; + } + + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + while (pivot != elements[index]) { + index++; + } + return index; + } + + @Override + public String getSimpleClassName() { + return ShortPrimitiveLookup.class.getSimpleName(); + } + + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/ShortWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/ShortWrapperLookup.java new file mode 100644 index 0000000000..1c1cd4a345 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/ShortWrapperLookup.java @@ -0,0 +1,46 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class ShortWrapperLookup extends Lookup { + private Short[] elements; + private final short pivot = 2; + + @Override + @Setup + public void prepare() { + short common = 1; + elements = new Short[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @Override + @TearDown + public void clean() { + elements = null; + } + + @Override + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + Short pivotWrapper = pivot; + while (!pivotWrapper.equals(elements[index])) { + index++; + } + return index; + + } + + @Override + public String getSimpleClassName() { + return ShortWrapperLookup.class.getSimpleName(); + } + + +} diff --git a/core-java-8/src/main/java/com/baeldung/reflect/Person.java b/core-java-8/src/main/java/com/baeldung/reflect/Person.java new file mode 100644 index 0000000000..fba25aca8b --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/reflect/Person.java @@ -0,0 +1,18 @@ +package com.baeldung.reflect; + +public class Person { + + private String fullName; + + public Person(String fullName) { + this.fullName = fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getFullName() { + return fullName; + } +} diff --git a/core-java-8/src/main/resources/logback.xml b/core-java-8/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/core-java-8/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/counter/CounterTest.java b/core-java-8/src/test/java/com/baeldung/counter/CounterTest.java deleted file mode 100644 index 657b510452..0000000000 --- a/core-java-8/src/test/java/com/baeldung/counter/CounterTest.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.counter; - -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import com.baeldung.counter.CounterUtil.MutableInteger; - -public class CounterTest { - - @Test - public void whenMapWithWrapperAsCounter_runsSuccessfully() { - Map counterMap = new HashMap<>(); - CounterUtil.counterWithWrapperObject(counterMap); - - assertEquals(3, counterMap.get("China") - .intValue()); - assertEquals(2, counterMap.get("India") - .intValue()); - } - - @Test - public void whenMapWithLambdaAndWrapperCounter_runsSuccessfully() { - Map counterMap = new HashMap<>(); - CounterUtil.counterWithLambdaAndWrapper(counterMap); - - assertEquals(3l, counterMap.get("China") - .longValue()); - assertEquals(2l, counterMap.get("India") - .longValue()); - } - - @Test - public void whenMapWithMutableIntegerCounter_runsSuccessfully() { - Map counterMap = new HashMap<>(); - CounterUtil.counterWithMutableInteger(counterMap); - assertEquals(3, counterMap.get("China") - .getCount()); - assertEquals(2, counterMap.get("India") - .getCount()); - } - - @Test - public void whenMapWithPrimitiveArray_runsSuccessfully() { - Map counterMap = new HashMap<>(); - CounterUtil.counterWithPrimitiveArray(counterMap); - assertEquals(3, counterMap.get("China")[0]); - assertEquals(2, counterMap.get("India")[0]); - } -} diff --git a/core-java-8/src/test/java/com/baeldung/counter/CounterUnitTest.java b/core-java-8/src/test/java/com/baeldung/counter/CounterUnitTest.java new file mode 100644 index 0000000000..ef57fc2c6e --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/counter/CounterUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.counter; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.baeldung.counter.CounterUtil.MutableInteger; + +public class CounterUnitTest { + + @Test + public void whenMapWithWrapperAsCounter_runsSuccessfully() { + Map counterMap = new HashMap<>(); + CounterUtil.counterWithWrapperObject(counterMap); + + assertEquals(3, counterMap.get("China") + .intValue()); + assertEquals(2, counterMap.get("India") + .intValue()); + } + + @Test + public void whenMapWithLambdaAndWrapperCounter_runsSuccessfully() { + Map counterMap = new HashMap<>(); + CounterUtil.counterWithLambdaAndWrapper(counterMap); + + assertEquals(3l, counterMap.get("China") + .longValue()); + assertEquals(2l, counterMap.get("India") + .longValue()); + } + + @Test + public void whenMapWithMutableIntegerCounter_runsSuccessfully() { + Map counterMap = new HashMap<>(); + CounterUtil.counterWithMutableInteger(counterMap); + assertEquals(3, counterMap.get("China") + .getCount()); + assertEquals(2, counterMap.get("India") + .getCount()); + } + + @Test + public void whenMapWithPrimitiveArray_runsSuccessfully() { + Map counterMap = new HashMap<>(); + CounterUtil.counterWithPrimitiveArray(counterMap); + assertEquals(3, counterMap.get("China")[0]); + assertEquals(2, counterMap.get("India")[0]); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java deleted file mode 100644 index 6fb6d21b19..0000000000 --- a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.datetime; - -import java.time.LocalDate; -import java.time.LocalTime; -import java.time.Month; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class UseLocalDateTimeUnitTest { - - UseLocalDateTime useLocalDateTime = new UseLocalDateTime(); - - @Test - public void givenString_whenUsingParse_thenLocalDateTime() { - assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30") - .toLocalDate()); - assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30") - .toLocalTime()); - } -} diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java deleted file mode 100644 index 834179febd..0000000000 --- a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.datetime; - -import java.time.DayOfWeek; -import java.time.LocalDate; -import java.time.LocalDateTime; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class UseLocalDateUnitTest { - - UseLocalDate useLocalDate = new UseLocalDate(); - - @Test - public void givenValues_whenUsingFactoryOf_thenLocalDate() { - assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10) - .toString()); - } - - @Test - public void givenString_whenUsingParse_thenLocalDate() { - assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10") - .toString()); - } - - @Test - public void whenUsingClock_thenLocalDate() { - assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock()); - } - - @Test - public void givenDate_whenUsingPlus_thenNextDay() { - assertEquals(LocalDate.now() - .plusDays(1), useLocalDate.getNextDay(LocalDate.now())); - } - - @Test - public void givenDate_whenUsingMinus_thenPreviousDay() { - assertEquals(LocalDate.now() - .minusDays(1), useLocalDate.getPreviousDay(LocalDate.now())); - } - - @Test - public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek() { - assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22"))); - } - - @Test - public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() { - assertEquals(1, useLocalDate.getFirstDayOfMonth() - .getDayOfMonth()); - } - - @Test - public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight() { - assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22"))); - } - -} diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java deleted file mode 100644 index 5fb079b94c..0000000000 --- a/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.datetime; - -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZonedDateTime; - -import org.junit.Assert; -import org.junit.Test; - -public class UseZonedDateTimeUnitTest { - - UseZonedDateTime zonedDateTime = new UseZonedDateTime(); - - @Test - public void givenZoneId_thenZonedDateTime() { - ZoneId zoneId = ZoneId.of("Europe/Paris"); - ZonedDateTime zonedDatetime = zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId); - Assert.assertEquals(zoneId, ZoneId.from(zonedDatetime)); - } -} diff --git a/core-java-8/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListTest.java b/core-java-8/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListTest.java deleted file mode 100644 index 45ee6eda33..0000000000 --- a/core-java-8/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListTest.java +++ /dev/null @@ -1,158 +0,0 @@ -package com.baeldung.findanelement; - -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -public class FindACustomerInGivenListTest { - - private static List customers = new ArrayList<>(); - - static { - customers.add(new Customer(1, "Jack")); - customers.add(new Customer(2, "James")); - customers.add(new Customer(3, "Sam")); - } - - private static FindACustomerInGivenList findACustomerInGivenList = new FindACustomerInGivenList(); - - @Test - public void givenAnIndex_whenFoundUsingGivenIndex_thenReturnCustomer() { - Customer customer = findACustomerInGivenList.findUsingGivenIndex(0, customers); - - assertEquals(1, customer.getId()); - } - - @Test - public void givenAnIndex_whenNotFoundUsingGivenIndex_thenReturnNull() { - Customer customer = findACustomerInGivenList.findUsingGivenIndex(5, customers); - - assertNull(customer); - } - - @Test - public void givenACustomer_whenFoundUsingContains_thenReturnTrue() { - Customer james = new Customer(2, "James"); - boolean isJamesPresent = findACustomerInGivenList.findUsingContains(james, customers); - - assertEquals(true, isJamesPresent); - } - - @Test - public void givenACustomer_whenNotFoundUsingContains_thenReturnFalse() { - Customer john = new Customer(5, "John"); - boolean isJohnPresent = findACustomerInGivenList.findUsingContains(john, customers); - - assertEquals(false, isJohnPresent); - } - - @Test - public void givenACustomer_whenFoundUsingIndexOf_thenReturnItsIndex() { - Customer james = new Customer(2, "James"); - int indexOfJames = findACustomerInGivenList.findUsingIndexOf(james, customers); - - assertEquals(1, indexOfJames); - } - - @Test - public void givenACustomer_whenNotFoundUsingIndexOf_thenReturnMinus1() { - Customer john = new Customer(5, "John"); - int indexOfJohn = findACustomerInGivenList.findUsingIndexOf(john, customers); - - assertEquals(-1, indexOfJohn); - } - - @Test - public void givenName_whenCustomerWithNameFoundUsingIterator_thenReturnCustomer() { - Customer james = findACustomerInGivenList.findUsingIterator("James", customers); - - assertEquals("James", james.getName()); - assertEquals(2, james.getId()); - } - - @Test - public void givenName_whenCustomerWithNameNotFoundUsingIterator_thenReturnNull() { - Customer john = findACustomerInGivenList.findUsingIterator("John", customers); - - assertNull(john); - } - - @Test - public void givenName_whenCustomerWithNameFoundUsingEnhancedFor_thenReturnCustomer() { - Customer james = findACustomerInGivenList.findUsingEnhancedForLoop("James", customers); - - assertEquals("James", james.getName()); - assertEquals(2, james.getId()); - } - - @Test - public void givenName_whenCustomerWithNameNotFoundUsingEnhancedFor_thenReturnNull() { - Customer john = findACustomerInGivenList.findUsingEnhancedForLoop("John", customers); - - assertNull(john); - } - - @Test - public void givenName_whenCustomerWithNameFoundUsingStream_thenReturnCustomer() { - Customer james = findACustomerInGivenList.findUsingStream("James", customers); - - assertEquals("James", james.getName()); - assertEquals(2, james.getId()); - } - - @Test - public void givenName_whenCustomerWithNameNotFoundUsingStream_thenReturnNull() { - Customer john = findACustomerInGivenList.findUsingStream("John", customers); - - assertNull(john); - } - - @Test - public void givenName_whenCustomerWithNameFoundUsingParallelStream_thenReturnCustomer() { - Customer james = findACustomerInGivenList.findUsingParallelStream("James", customers); - - assertEquals("James", james.getName()); - assertEquals(2, james.getId()); - } - - @Test - public void givenName_whenCustomerWithNameNotFoundUsingParallelStream_thenReturnNull() { - Customer john = findACustomerInGivenList.findUsingParallelStream("John", customers); - - assertNull(john); - } - - @Test - public void givenName_whenCustomerWithNameFoundUsingApacheCommon_thenReturnCustomer() { - Customer james = findACustomerInGivenList.findUsingApacheCommon("James", customers); - - assertEquals("James", james.getName()); - assertEquals(2, james.getId()); - } - - @Test - public void givenName_whenCustomerWithNameNotFoundUsingApacheCommon_thenReturnNull() { - Customer john = findACustomerInGivenList.findUsingApacheCommon("John", customers); - - assertNull(john); - } - - @Test - public void givenName_whenCustomerWithNameFoundUsingGuava_thenReturnCustomer() { - Customer james = findACustomerInGivenList.findUsingGuava("James", customers); - - assertEquals("James", james.getName()); - assertEquals(2, james.getId()); - } - - @Test - public void givenName_whenCustomerWithNameNotFoundUsingGuava_thenReturnNull() { - Customer john = findACustomerInGivenList.findUsingGuava("John", customers); - - assertNull(john); - } - -} diff --git a/core-java-8/src/test/java/com/baeldung/iterators/IteratorsTest.java b/core-java-8/src/test/java/com/baeldung/iterators/IteratorsTest.java deleted file mode 100644 index 73793da7ae..0000000000 --- a/core-java-8/src/test/java/com/baeldung/iterators/IteratorsTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.iterators; - -import static com.baeldung.iterators.Iterators.failFast1; -import static com.baeldung.iterators.Iterators.failFast2; -import static com.baeldung.iterators.Iterators.failSafe1; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.ConcurrentModificationException; - -import org.junit.Test; - -/** - * Source code https://github.com/eugenp/tutorials - * - * @author Santosh Thakur - */ - -public class IteratorsTest { - - @Test - public void whenFailFast_ThenThrowsException() { - assertThatThrownBy(() -> { - failFast1(); - }).isInstanceOf(ConcurrentModificationException.class); - } - - @Test - public void whenFailFast_ThenThrowsExceptionInSecondIteration() { - assertThatThrownBy(() -> { - failFast2(); - }).isInstanceOf(ConcurrentModificationException.class); - } - - @Test - public void whenFailSafe_ThenDoesNotThrowException() { - assertThat(failSafe1()).isGreaterThanOrEqualTo(0); - } - -} diff --git a/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java new file mode 100644 index 0000000000..4f1e54ec2c --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.java8; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.junit.Assert.assertEquals; + +public class UnsignedArithmeticUnitTest { + @Test + public void whenDoublingALargeByteNumber_thenOverflow() { + byte b1 = 100; + byte b2 = (byte) (b1 << 1); + + assertEquals(-56, b2); + } + + @Test + public void whenComparingNumbers_thenNegativeIsInterpretedAsUnsigned() { + int positive = Integer.MAX_VALUE; + int negative = Integer.MIN_VALUE; + + int signedComparison = Integer.compare(positive, negative); + assertEquals(1, signedComparison); + + int unsignedComparison = Integer.compareUnsigned(positive, negative); + assertEquals(-1, unsignedComparison); + + assertEquals(negative, positive + 1); + } + + @Test + public void whenDividingNumbers_thenNegativeIsInterpretedAsUnsigned() { + int positive = Integer.MAX_VALUE; + int negative = Integer.MIN_VALUE; + + assertEquals(-1, negative / positive); + assertEquals(1, Integer.divideUnsigned(negative, positive)); + + assertEquals(-1, negative % positive); + assertEquals(1, Integer.remainderUnsigned(negative, positive)); + } + + @Test + public void whenParsingNumbers_thenNegativeIsInterpretedAsUnsigned() { + Throwable thrown = catchThrowable(() -> Integer.parseInt("2147483648")); + assertThat(thrown).isInstanceOf(NumberFormatException.class); + + assertEquals(Integer.MAX_VALUE + 1, Integer.parseUnsignedInt("2147483648")); + } + + @Test + public void whenFormattingNumbers_thenNegativeIsInterpretedAsUnsigned() { + String signedString = Integer.toString(Integer.MIN_VALUE); + assertEquals("-2147483648", signedString); + + String unsignedString = Integer.toUnsignedString(Integer.MIN_VALUE); + assertEquals("2147483648", unsignedString); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/java8/optional/OrElseAndOrElseGetTest.java b/core-java-8/src/test/java/com/baeldung/java8/optional/OrElseAndOrElseGetTest.java deleted file mode 100644 index 2519a77f1f..0000000000 --- a/core-java-8/src/test/java/com/baeldung/java8/optional/OrElseAndOrElseGetTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.java8.optional; - -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.*; - -import com.baeldung.optional.OrElseAndOrElseGet; - -public class OrElseAndOrElseGetTest { - - private OrElseAndOrElseGet orElsevsOrElseGet = new OrElseAndOrElseGet(); - - private static final Logger LOG = LoggerFactory.getLogger(OrElseAndOrElseGetTest.class); - - @Test - public void givenNonEmptyOptional_whenOrElseUsed_thenGivenStringReturned() { - LOG.info("In givenNonEmptyOptional_whenOrElseUsed_thenGivenStringReturned()"); - String name = orElsevsOrElseGet.getNameUsingOrElse("baeldung"); - assertEquals(name, "baeldung"); - } - - @Test - public void givenEmptyOptional_whenOrElseUsed_thenRandomStringReturned() { - LOG.info("In givenEmptyOptional_whenOrElseUsed_thenRandomStringReturned()"); - String name = orElsevsOrElseGet.getNameUsingOrElse(null); - assertTrue(orElsevsOrElseGet.names.contains(name)); - } - - @Test - public void givenNonEmptyOptional_whenOrElseGetUsed_thenGivenStringReturned() { - LOG.info("In givenNonEmptyOptional_whenOrElseGetUsed_thenGivenStringReturned()"); - String name = orElsevsOrElseGet.getNameUsingOrElseGet("baeldung"); - assertEquals(name, "baeldung"); - } - - @Test - public void givenEmptyOptional_whenOrElseGetUsed_thenRandomStringReturned() { - LOG.info("In givenEmptyOptional_whenOrElseGetUsed_thenRandomStringReturned()"); - String name = orElsevsOrElseGet.getNameUsingOrElseGet(null); - assertTrue(orElsevsOrElseGet.names.contains(name)); - } -} diff --git a/core-java-8/src/test/java/com/baeldung/java8/optional/OrElseAndOrElseGetUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/optional/OrElseAndOrElseGetUnitTest.java new file mode 100644 index 0000000000..c8a631d9f0 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/java8/optional/OrElseAndOrElseGetUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.java8.optional; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.junit.Assert.*; + +import com.baeldung.optional.OrElseAndOrElseGet; + +public class OrElseAndOrElseGetUnitTest { + + private OrElseAndOrElseGet orElsevsOrElseGet = new OrElseAndOrElseGet(); + + private static final Logger LOG = LoggerFactory.getLogger(OrElseAndOrElseGetUnitTest.class); + + @Test + public void givenNonEmptyOptional_whenOrElseUsed_thenGivenStringReturned() { + LOG.info("In givenNonEmptyOptional_whenOrElseUsed_thenGivenStringReturned()"); + String name = orElsevsOrElseGet.getNameUsingOrElse("baeldung"); + assertEquals(name, "baeldung"); + } + + @Test + public void givenEmptyOptional_whenOrElseUsed_thenRandomStringReturned() { + LOG.info("In givenEmptyOptional_whenOrElseUsed_thenRandomStringReturned()"); + String name = orElsevsOrElseGet.getNameUsingOrElse(null); + assertTrue(orElsevsOrElseGet.names.contains(name)); + } + + @Test + public void givenNonEmptyOptional_whenOrElseGetUsed_thenGivenStringReturned() { + LOG.info("In givenNonEmptyOptional_whenOrElseGetUsed_thenGivenStringReturned()"); + String name = orElsevsOrElseGet.getNameUsingOrElseGet("baeldung"); + assertEquals(name, "baeldung"); + } + + @Test + public void givenEmptyOptional_whenOrElseGetUsed_thenRandomStringReturned() { + LOG.info("In givenEmptyOptional_whenOrElseGetUsed_thenRandomStringReturned()"); + String name = orElsevsOrElseGet.getNameUsingOrElseGet(null); + assertTrue(orElsevsOrElseGet.names.contains(name)); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/list/AddElementsUnitTest.java b/core-java-8/src/test/java/com/baeldung/list/AddElementsUnitTest.java new file mode 100644 index 0000000000..93c28812bd --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/list/AddElementsUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.list; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.*; + +import static org.junit.Assert.*; + +public class AddElementsUnitTest { + + List flowers; + + @Before + public void init() { + this.flowers = new ArrayList<>(Arrays.asList( + new Flower("Poppy", 12), + new Flower("Anemone", 8), + new Flower("Catmint", 12))); + } + + @Test + public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithNewItems() { + List anotherList = new ArrayList<>(); + anotherList.addAll(flowers); + + assertEquals(anotherList.size(), flowers.size()); + Assert.assertTrue(anotherList.containsAll(flowers)); + } + + @Test + public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithOneModifiedElementByConstructor() { + List anotherList = new ArrayList<>(); + anotherList.addAll(flowers); + + Flower flower = anotherList.get(0); + flower.setPetals(flowers.get(0).getPetals() * 3); + + assertEquals(anotherList.size(), flowers.size()); + Assert.assertTrue(anotherList.containsAll(flowers)); + } + + @Test + public void givenAListAndElements_whenUseCollectionsAddAll_thenAddElementsToTargetList() { + List target = new ArrayList<>(); + + Collections.addAll(target, flowers.get(0), flowers.get(1), flowers.get(2), flowers.get(0)); + + assertEquals(target.size(), 4); + } + + @Test + public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListSkipFirstElementByStreamProcess() { + List flowerVase = new ArrayList<>(); + + flowers.stream() + .skip(1) + .forEachOrdered(flowerVase::add); + + assertEquals(flowerVase.size() + 1, flowers.size()); + assertFalse(flowerVase.containsAll(flowers)); + } + + @Test + public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListFilteringElementsByStreamProcess() { + List flowerVase = new ArrayList<>(); + + flowers.stream() + .filter(f -> f.getPetals() > 10) + .forEachOrdered(flowerVase::add); + + assertEquals(flowerVase.size() + 1, flowers.size()); + assertFalse(flowerVase.containsAll(flowers)); + } + + @Test + public void givenAList_whenListIsNotNull_thenAddElementsToListByStreamProcessWihtOptional() { + List target = new ArrayList<>(); + + Optional.ofNullable(flowers) + .ifPresent(target::addAll); + + assertNotNull(target); + assertEquals(target.size(), 3); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java new file mode 100644 index 0000000000..f68df2c821 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.nullsafecollectionstreams; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.stream.Stream; +import org.junit.Test; +import static org.junit.Assert.*; + + +public class NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest { + + private final NullSafeCollectionStreamsUsingCommonsEmptyIfNull instance = + new NullSafeCollectionStreamsUsingCommonsEmptyIfNull(); + + @Test + public void whenCollectionIsNull_thenExpectAnEmptyStream() { + Collection collection = null; + Stream expResult = Stream.empty(); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + + } + + @Test + public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() { + + Collection collection = Arrays.asList("a", "b", "c"); + Stream expResult = Arrays.stream(new String[] { "a", "b", "c" }); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + } + + private static void assertStreamEquals(Stream s1, Stream s2) { + Iterator iter1 = s1.iterator(), iter2 = s2.iterator(); + while (iter1.hasNext() && iter2.hasNext()) + assertEquals(iter1.next(), iter2.next()); + assert !iter1.hasNext() && !iter2.hasNext(); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java new file mode 100644 index 0000000000..df6c72d346 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java @@ -0,0 +1,50 @@ +/* + * 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.nullsafecollectionstreams; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.stream.Stream; + +import org.junit.Test; + +/** + * + * @author Kwaje Anthony + */ +public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest { + + private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = new NullSafeCollectionStreamsUsingJava8OptionalContainer(); + + @Test + public void whenCollectionIsNull_thenExpectAnEmptyStream() { + Collection collection = null; + Stream expResult = Stream.empty(); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + + } + + @Test + public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() { + + Collection collection = Arrays.asList("a", "b", "c"); + Stream expResult = Arrays.stream(new String[] { "a", "b", "c" }); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + } + + private static void assertStreamEquals(Stream s1, Stream s2) { + Iterator iter1 = s1.iterator(), iter2 = s2.iterator(); + while (iter1.hasNext() && iter2.hasNext()) + assertEquals(iter1.next(), iter2.next()); + assert !iter1.hasNext() && !iter2.hasNext(); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java new file mode 100644 index 0000000000..ddb4dcdc12 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java @@ -0,0 +1,45 @@ + +package com.baeldung.nullsafecollectionstreams; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.stream.Stream; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Kwaje Anthony + */ +public class NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest { + + private final NullSafeCollectionStreamsUsingNullDereferenceCheck instance = + new NullSafeCollectionStreamsUsingNullDereferenceCheck(); + + @Test + public void whenCollectionIsNull_thenExpectAnEmptyStream() { + Collection collection = null; + Stream expResult = Stream.empty(); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + + } + + @Test + public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() { + + Collection collection = Arrays.asList("a", "b", "c"); + Stream expResult = Arrays.stream(new String[] { "a", "b", "c" }); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + } + + private static void assertStreamEquals(Stream s1, Stream s2) { + Iterator iter1 = s1.iterator(), iter2 = s2.iterator(); + while (iter1.hasNext() && iter2.hasNext()) + assertEquals(iter1.next(), iter2.next()); + assert !iter1.hasNext() && !iter2.hasNext(); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/optional/PersonRepositoryUnitTest.java b/core-java-8/src/test/java/com/baeldung/optional/PersonRepositoryUnitTest.java new file mode 100644 index 0000000000..4efa625ccd --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/optional/PersonRepositoryUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.optional; + +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class PersonRepositoryUnitTest { + + PersonRepository personRepository = new PersonRepository(); + + @Test + public void whenIdIsNull_thenExceptionIsThrown() { + assertThrows(IllegalArgumentException.class, + () -> + Optional + .ofNullable(personRepository.findNameById(null)) + .orElseThrow(IllegalArgumentException::new)); + } + + @Test + public void whenIdIsNonNull_thenNoExceptionIsThrown() { + assertAll( + () -> + Optional + .ofNullable(personRepository.findNameById("id")) + .orElseThrow(RuntimeException::new)); + } + + @Test + public void whenIdNonNull_thenReturnsNameUpperCase() { + String name = Optional + .ofNullable(personRepository.findNameById("id")) + .map(String::toUpperCase) + .orElseThrow(RuntimeException::new); + + assertEquals("NAME", name); + } + +} \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorTest.java b/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorTest.java deleted file mode 100644 index e53e1c183e..0000000000 --- a/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.prime; - -import static com.baeldung.prime.PrimeGenerator.*; - -import java.util.Arrays; -import java.util.List; -import org.junit.Test; -import static org.junit.Assert.*; - -public class PrimeGeneratorTest { - @Test - public void whenBruteForced_returnsSuccessfully() { - final List primeNumbers = primeNumbersBruteForce(20); - assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); - } - - @Test - public void whenOptimized_returnsSuccessfully() { - final List primeNumbers = primeNumbersTill(20); - assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); - } - - @Test - public void whenSieveOfEratosthenes_returnsSuccessfully() { - final List primeNumbers = sieveOfEratosthenes(20); - assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); - } -} diff --git a/core-java-8/src/test/java/com/baeldung/reflect/MethodParamNameUnitTest.java b/core-java-8/src/test/java/com/baeldung/reflect/MethodParamNameUnitTest.java new file mode 100644 index 0000000000..b191c94826 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/reflect/MethodParamNameUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.reflect; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.lang.reflect.Parameter; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import org.junit.Test; + +public class MethodParamNameUnitTest { + + @Test + public void whenGetConstructorParams_thenOk() + throws NoSuchMethodException, SecurityException { + List parameters + = Arrays.asList(Person.class.getConstructor(String.class).getParameters()); + Optional parameter + = parameters.stream().filter(Parameter::isNamePresent).findFirst(); + assertThat(parameter.get().getName()).isEqualTo("fullName"); + } + + @Test + public void whenGetMethodParams_thenOk() + throws NoSuchMethodException, SecurityException { + List parameters + = Arrays.asList( + Person.class.getMethod("setFullName", String.class).getParameters()); + Optional parameter + = parameters.stream().filter(Parameter::isNamePresent).findFirst(); + assertThat(parameter.get().getName()).isEqualTo("fullName"); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorTest.java b/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorTest.java deleted file mode 100644 index 64dd65cf5e..0000000000 --- a/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.spliteratorAPI; - -import java.util.Arrays; -import java.util.Spliterator; -import java.util.stream.Stream; -import java.util.stream.StreamSupport; - -import static org.assertj.core.api.Assertions.*; -import org.junit.Before; -import org.junit.Test; - -public class ExecutorTest { - Article article; - Stream stream; - Spliterator spliterator; - Spliterator
split1; - Spliterator
split2; - - @Before - public void init() { - article = new Article(Arrays.asList(new Author("Ahmad", 0), new Author("Eugen", 0), new Author("Alice", 1), - new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), - new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), - new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), - new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), - new Author("Mike", 0), new Author("Michał", 0), new Author("Loredana", 1)), 0); - stream = article.getListOfAuthors().stream(); - split1 = Executor.generateElements().spliterator(); - split2 = split1.trySplit(); - spliterator = new RelatedAuthorSpliterator(article.getListOfAuthors()); - } - - @Test - public void givenAstreamOfAuthors_whenProcessedInParallelWithCustomSpliterator_coubtProducessRightOutput() { - Stream stream2 = StreamSupport.stream(spliterator, true); - assertThat(Executor.countAutors(stream2.parallel())).isEqualTo(9); - } - - @Test - public void givenSpliterator_whenAppliedToAListOfArticle_thenSplittedInHalf() { - assertThat(new Task(split1).call()).containsSequence(Executor.generateElements().size() / 2 + ""); - assertThat(new Task(split2).call()).containsSequence(Executor.generateElements().size() / 2 + ""); - } -} diff --git a/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorUnitTest.java b/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorUnitTest.java new file mode 100644 index 0000000000..81fad12eb0 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.spliteratorAPI; + +import java.util.Arrays; +import java.util.Spliterator; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + +import static org.assertj.core.api.Assertions.*; +import org.junit.Before; +import org.junit.Test; + +public class ExecutorUnitTest { + Article article; + Stream stream; + Spliterator spliterator; + Spliterator
split1; + Spliterator
split2; + + @Before + public void init() { + article = new Article(Arrays.asList(new Author("Ahmad", 0), new Author("Eugen", 0), new Author("Alice", 1), + new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), + new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), + new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), + new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), + new Author("Mike", 0), new Author("MichaÅ‚", 0), new Author("Loredana", 1)), 0); + stream = article.getListOfAuthors().stream(); + split1 = Executor.generateElements().spliterator(); + split2 = split1.trySplit(); + spliterator = new RelatedAuthorSpliterator(article.getListOfAuthors()); + } + + @Test + public void givenAstreamOfAuthors_whenProcessedInParallelWithCustomSpliterator_coubtProducessRightOutput() { + Stream stream2 = StreamSupport.stream(spliterator, true); + assertThat(Executor.countAutors(stream2.parallel())).isEqualTo(9); + } + + @Test + public void givenSpliterator_whenAppliedToAListOfArticle_thenSplittedInHalf() { + assertThat(new Task(split1).call()).containsSequence(Executor.generateElements().size() / 2 + ""); + assertThat(new Task(split2).call()).containsSequence(Executor.generateElements().size() / 2 + ""); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/stream/StreamApiTest.java b/core-java-8/src/test/java/com/baeldung/stream/StreamApiTest.java deleted file mode 100644 index f4d0ac6b08..0000000000 --- a/core-java-8/src/test/java/com/baeldung/stream/StreamApiTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.stream; - -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -public class StreamApiTest { - - @Test - public void givenList_whenGetLastElementUsingReduce_thenReturnLastElement() { - List valueList = new ArrayList<>(); - valueList.add("Joe"); - valueList.add("John"); - valueList.add("Sean"); - - String last = StreamApi.getLastElementUsingReduce(valueList); - - assertEquals("Sean", last); - } - - @Test - public void givenInfiniteStream_whenGetInfiniteStreamLastElementUsingReduce_thenReturnLastElement() { - int last = StreamApi.getInfiniteStreamLastElementUsingReduce(); - assertEquals(19, last); - } - - @Test - public void givenListAndCount_whenGetLastElementUsingSkip_thenReturnLastElement() { - List valueList = new ArrayList<>(); - valueList.add("Joe"); - valueList.add("John"); - valueList.add("Sean"); - - String last = StreamApi.getLastElementUsingSkip(valueList); - - assertEquals("Sean", last); - } - -} diff --git a/core-java-8/src/test/java/com/baeldung/stream/StreamIndicesTest.java b/core-java-8/src/test/java/com/baeldung/stream/StreamIndicesTest.java deleted file mode 100644 index a02ef4031e..0000000000 --- a/core-java-8/src/test/java/com/baeldung/stream/StreamIndicesTest.java +++ /dev/null @@ -1,70 +0,0 @@ -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-8/src/test/java/com/baeldung/stream/StreamToImmutableTest.java b/core-java-8/src/test/java/com/baeldung/stream/StreamToImmutableTest.java deleted file mode 100644 index 69b0b6d3ef..0000000000 --- a/core-java-8/src/test/java/com/baeldung/stream/StreamToImmutableTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.baeldung.stream; - -import static java.util.stream.Collectors.collectingAndThen; -import static java.util.stream.Collectors.toList; -import static java.util.stream.Collectors.toSet; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.stream.IntStream; - -import org.junit.Test; - -import com.baeldung.stream.mycollectors.MyImmutableListCollector; -import com.google.common.collect.ImmutableList; - -public class StreamToImmutableTest { - - @Test - public void whenUsingCollectingToImmutableSet_thenSuccess() { - List givenList = Arrays.asList("a", "b", "c"); - List result = givenList.stream() - .collect(collectingAndThen(toSet(), ImmutableList::copyOf)); - - System.out.println(result.getClass()); - } - - @Test - public void whenUsingCollectingToUnmodifiableList_thenSuccess() { - List givenList = new ArrayList<>(Arrays.asList("a", "b", "c")); - List result = givenList.stream() - .collect(collectingAndThen(toList(), Collections::unmodifiableList)); - - System.out.println(result.getClass()); - } - - @Test - public void whenCollectToImmutableList_thenSuccess() { - List list = IntStream.range(0, 9) - .boxed() - .collect(ImmutableList.toImmutableList()); - - System.out.println(list.getClass()); - } - - @Test - public void whenCollectToMyImmutableListCollector_thenSuccess() { - List givenList = Arrays.asList("a", "b", "c", "d"); - List result = givenList.stream() - .collect(MyImmutableListCollector.toImmutableList()); - - System.out.println(result.getClass()); - } - - @Test - public void whenPassingSupplier_thenSuccess() { - List givenList = Arrays.asList("a", "b", "c", "d"); - List result = givenList.stream() - .collect(MyImmutableListCollector.toImmutableList(LinkedList::new)); - - System.out.println(result.getClass()); - } -} 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 deleted file mode 100644 index d78c9fca35..0000000000 --- a/core-java-8/src/test/java/com/baeldung/stream/SupplierStreamTest.java +++ /dev/null @@ -1,35 +0,0 @@ -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-8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java b/core-java-8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java deleted file mode 100644 index 513f163da8..0000000000 --- a/core-java-8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.temporaladjusters; - -import com.baeldung.temporaladjuster.CustomTemporalAdjuster; -import org.junit.Test; - -import java.time.LocalDate; -import java.time.Period; -import java.time.temporal.TemporalAdjuster; - -import static org.junit.Assert.assertEquals; - -public class CustomTemporalAdjusterTest { - - private static final TemporalAdjuster NEXT_WORKING_DAY = new CustomTemporalAdjuster(); - - @Test - public void whenAdjustAndImplementInterface_thenNextWorkingDay() { - LocalDate localDate = LocalDate.of(2017, 07, 8); - CustomTemporalAdjuster temporalAdjuster = new CustomTemporalAdjuster(); - LocalDate nextWorkingDay = localDate.with(temporalAdjuster); - - assertEquals("2017-07-10", nextWorkingDay.toString()); - } - - @Test - public void whenAdjust_thenNextWorkingDay() { - LocalDate localDate = LocalDate.of(2017, 07, 8); - LocalDate date = localDate.with(NEXT_WORKING_DAY); - - assertEquals("2017-07-10", date.toString()); - } - - @Test - public void whenAdjust_thenFourteenDaysAfterDate() { - LocalDate localDate = LocalDate.of(2017, 07, 8); - TemporalAdjuster temporalAdjuster = (t) -> t.plus(Period.ofDays(14)); - LocalDate result = localDate.with(temporalAdjuster); - - String fourteenDaysAfterDate = "2017-07-22"; - - assertEquals(fourteenDaysAfterDate, result.toString()); - } -} \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersTest.java b/core-java-8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersTest.java deleted file mode 100644 index d06da5a782..0000000000 --- a/core-java-8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.temporaladjusters; - -import java.time.DayOfWeek; -import java.time.LocalDate; -import java.time.temporal.TemporalAdjusters; - -import org.junit.Assert; -import org.junit.Test; - -public class TemporalAdjustersTest { - - @Test - public void whenAdjust_thenNextSunday() { - LocalDate localDate = LocalDate.of(2017, 07, 8); - LocalDate nextSunday = localDate.with(TemporalAdjusters.next(DayOfWeek.SUNDAY)); - - String expected = "2017-07-09"; - - Assert.assertEquals(expected, nextSunday.toString()); - } - -} diff --git a/core-java-8/src/test/java/com/baeldung/typeinference/TypeInferenceUnitTest.java b/core-java-8/src/test/java/com/baeldung/typeinference/TypeInferenceUnitTest.java new file mode 100644 index 0000000000..b9600a18cb --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/typeinference/TypeInferenceUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.typeinference; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; + +public class TypeInferenceUnitTest { + + @Test + public void givenNoTypeInference_whenInvokingGenericMethodsWithTypeParameters_ObjectsAreCreated() { + // Without type inference. code is verbose. + Map> mapOfMaps = new HashMap>(); + List strList = Collections. emptyList(); + List intList = Collections. emptyList(); + + assertTrue(mapOfMaps.isEmpty()); + assertTrue(strList.isEmpty()); + assertTrue(intList.isEmpty()); + } + + @Test + public void givenTypeInference_whenInvokingGenericMethodsWithoutTypeParameters_ObjectsAreCreated() { + // With type inference. code is concise. + List strListInferred = Collections.emptyList(); + List intListInferred = Collections.emptyList(); + + assertTrue(strListInferred.isEmpty()); + assertTrue(intListInferred.isEmpty()); + } + + @Test + public void givenJava7_whenInvokingCostructorWithoutTypeParameters_ObjectsAreCreated() { + // Type Inference for constructor using diamond operator. + Map> mapOfMapsInferred = new HashMap<>(); + + assertTrue(mapOfMapsInferred.isEmpty()); + assertEquals("public class java.util.HashMap", mapOfMapsInferred.getClass() + .toGenericString()); + } + + static List add(List list, T a, T b) { + list.add(a); + list.add(b); + return list; + } + + @Test + public void givenGenericMethod_WhenInvokedWithoutExplicitTypes_TypesAreInferred() { + // Generalized target-type inference + List strListGeneralized = add(new ArrayList<>(), "abc", "def"); + List intListGeneralized = add(new ArrayList<>(), 1, 2); + List numListGeneralized = add(new ArrayList<>(), 1, 2.0); + + assertEquals("public class java.util.ArrayList", strListGeneralized.getClass() + .toGenericString()); + assertFalse(intListGeneralized.isEmpty()); + assertEquals(2, numListGeneralized.size()); + } + + @Test + public void givenLambdaExpressions_whenParameterTypesNotSpecified_ParameterTypesAreInferred() { + // Type Inference and Lambda Expressions. + List intList = Arrays.asList(5, 3, 4, 2, 1); + Collections.sort(intList, (a, b) -> { + assertEquals("java.lang.Integer", a.getClass().getName()); + return a.compareTo(b); + }); + assertEquals("[1, 2, 3, 4, 5]", Arrays.toString(intList.toArray())); + + List strList = Arrays.asList("Red", "Blue", "Green"); + Collections.sort(strList, (a, b) -> { + assertEquals("java.lang.String", a.getClass().getName()); + return a.compareTo(b); + }); + assertEquals("[Blue, Green, Red]", Arrays.toString(strList.toArray())); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java index 3ad3deb548..ec20b7794b 100644 --- a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java @@ -39,5 +39,4 @@ public class CurrentDateTimeUnitTest { assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond()); } - } diff --git a/core-java-9/README.md b/core-java-9/README.md index 59b0929871..bf07cfcc86 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -15,12 +15,14 @@ - [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity) - [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) -- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string) -- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime) - [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles) - [Exploring the New HTTP Client in Java 9](http://www.baeldung.com/java-9-http-client) - [Method Handles in Java](http://www.baeldung.com/java-method-handles) - [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue) - [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity) +- [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional) +- [Java 9 java.lang.Module API](http://www.baeldung.com/java-9-module-api) +- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range) +- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) +- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api) diff --git a/core-java-9/pom.xml b/core-java-9/pom.xml index 1f92ee71f8..f22d0a3ed9 100644 --- a/core-java-9/pom.xml +++ b/core-java-9/pom.xml @@ -1,5 +1,5 @@ + 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 core-java-9 @@ -13,40 +13,29 @@ - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${ch.qos.logback.version} - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - - - junit - junit - ${junit.version} - test - - - org.mockito - mockito-core - ${mockito.version} - test - com.jayway.awaitility awaitility ${awaitility.version} test + + org.assertj + assertj-core + ${assertj.version} + test + + + com.google.guava + guava + ${guava.version} + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + @@ -72,23 +61,13 @@ - - UTF-8 - - - 1.7.21 - 1.2.1 - - 3.7.0 - 2.19.1 - - 1.3 - 4.12 - 1.10.19 + 3.10.0 + 1.2.0 1.7.0 1.9 1.9 + 25.1-jre diff --git a/core-java-9/src/main/java/com/baeldung/java9/language/stream/StreamsGroupingCollectionFilter.java b/core-java-9/src/main/java/com/baeldung/java9/language/stream/StreamsGroupingCollectionFilter.java new file mode 100644 index 0000000000..84d2e63c6c --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/language/stream/StreamsGroupingCollectionFilter.java @@ -0,0 +1,27 @@ +package com.baeldung.java9.language.stream; + +import static java.util.stream.Collectors.filtering; +import static java.util.stream.Collectors.groupingBy; +import static java.util.stream.Collectors.toList; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +public class StreamsGroupingCollectionFilter { + + static public Map> findEvenNumbersAfterGroupingByQuantityOfDigits(Collection baseCollection) { + Function getQuantityOfDigits = item -> (int) Math.log10(item) + 1; + + return baseCollection.stream() + .collect(groupingBy(getQuantityOfDigits, filtering(item -> item % 2 == 0, toList()))); + } + + static public Map> findEvenNumbersBeforeGroupingByQuantityOfDigits(Collection baseCollection) { + + return baseCollection.stream() + .filter(item -> item % 2 == 0) + .collect(groupingBy(item -> (int) Math.log10(item) + 1, toList())); + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/maps/initialize/MapsInitializer.java b/core-java-9/src/main/java/com/baeldung/java9/maps/initialize/MapsInitializer.java new file mode 100644 index 0000000000..2a8ce588bb --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/maps/initialize/MapsInitializer.java @@ -0,0 +1,33 @@ +package com.baeldung.java9.maps.initialize; + +import java.util.AbstractMap; +import java.util.HashMap; +import java.util.Map; + +public class MapsInitializer { + + @SuppressWarnings("unused") + public void createMapWithMapOf() { + Map emptyMap = Map.of(); + Map singletonMap = Map.of("key1", "value"); + Map map = Map.of("key1","value1", "key2", "value2"); + } + + public void createMapWithMapEntries() { + Map map = Map.ofEntries( + new AbstractMap.SimpleEntry("name", "John"), + new AbstractMap.SimpleEntry("city", "budapest"), + new AbstractMap.SimpleEntry("zip", "000000"), + new AbstractMap.SimpleEntry("home", "1231231231") + ); + } + + @SuppressWarnings("unused") + public void createMutableMaps() { + Map map = new HashMap (Map.of("key1","value1", "key2", "value2")); + Map map2 = new HashMap ( Map.ofEntries( + new AbstractMap.SimpleEntry("name", "John"), + new AbstractMap.SimpleEntry("city", "budapest"))); + + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java b/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java new file mode 100644 index 0000000000..46c2e688ce --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java @@ -0,0 +1,15 @@ +package com.baeldung.java9.process; + +import java.util.Scanner; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class ChildProcess { + + public static void main(String[] args) { + @SuppressWarnings("resource") + Scanner input = new Scanner(System.in); + Logger log = Logger.getLogger(ChildProcess.class.getName()); + log.log(Level.INFO, input.nextLine()); + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java b/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java new file mode 100644 index 0000000000..443847916a --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java @@ -0,0 +1,16 @@ +package com.baeldung.java9.process; + +import java.util.logging.Level; +import java.util.logging.Logger; + +public class OutputStreamExample { + + public static void main(String[] args) { + Logger log = Logger.getLogger(OutputStreamExample.class.getName()); + log.log(Level.INFO, Integer.toString(sum(1,2))); + } + + public static int sum(int a, int b) { + return a + b; + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java new file mode 100644 index 0000000000..8b6ae0b441 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java @@ -0,0 +1,7 @@ +package com.baeldung.java9.process; + +public class ProcessCompilationError { + //This method has been written to generate error to display + //how process errorStream() can consume error + public static void(); +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java new file mode 100644 index 0000000000..74101ba3da --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java @@ -0,0 +1,110 @@ +package com.baeldung.java9.process; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.util.Optional; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class ProcessUnderstanding { + + public static int compileAndRunJavaProgram() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java"); + process = Runtime.getRuntime() + .exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample"); + BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream())); + int value = Integer.parseInt(output.readLine()); + return value; + } + + public static String getErrorStreamExample() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java"); + BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream())); + String errorString = error.readLine(); + return errorString; + } + + public static void creatingNewProcess() throws IOException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + } + + public static int filterProcessWithStreamsInSpecificRangeReturnCount() { + return (int) ProcessHandle.allProcesses() + .filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000)) + .count(); + } + + public static void destroyingProcessCreatedBySameProcess() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + } + + public static void destroyingProcessCreatedByDifferentProcess() { + // find out the process id of current running task by checking + // task manager in windows and enter the integer value + Optional optionalProcessHandle = ProcessHandle.of(5232); + ProcessHandle processHandle = optionalProcessHandle.get(); + processHandle.destroy(); + } + + public static int waitForExample() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + return process.waitFor(); + } + + public static int exitValueExample() throws IOException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + process.destroy(); + return process.exitValue(); + } + + public static void destroyExample() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + } + + public static void destroyForciblyExample() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + if (process.isAlive()) { + process.destroyForcibly(); + } + } + + public static void outputStreamDemo() throws IOException, InterruptedException { + Logger log = Logger.getLogger(ProcessUnderstanding.class.getName()); + Process pr = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ChildProcess.java"); + final Process process = Runtime.getRuntime() + .exec("java -cp src/main/java com.baeldung.java9.process.ChildProcess"); + try (Writer w = new OutputStreamWriter(process.getOutputStream(), "UTF-8")) { + w.write("send to child\n"); + } + new Thread(() -> { + try { + int c; + while ((c = process.getInputStream() + .read()) != -1) + System.out.write((byte) c); + } catch (Exception e) { + e.printStackTrace(); + } + }).start(); + // send to child + log.log(Level.INFO, "rc=" + process.waitFor()); + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/rangedates/DatesCollectionIteration.java b/core-java-9/src/main/java/com/baeldung/java9/rangedates/DatesCollectionIteration.java new file mode 100644 index 0000000000..f5ec5d29dc --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/rangedates/DatesCollectionIteration.java @@ -0,0 +1,24 @@ +package com.baeldung.java9.rangedates; + +import java.util.Collection; +import java.util.Date; + +public class DatesCollectionIteration { + + public void iteratingRangeOfDatesJava7(Collection dates) { + + for (Date date : dates) { + processDate(date); + } + } + + public void iteratingRangeOfDatesJava8(Collection dates) { + dates.stream() + .forEach(this::processDate); + } + + private void processDate(Date date) { + System.out.println(date); + } + +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/rangedates/RangeDatesIteration.java b/core-java-9/src/main/java/com/baeldung/java9/rangedates/RangeDatesIteration.java new file mode 100644 index 0000000000..4972036c91 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/rangedates/RangeDatesIteration.java @@ -0,0 +1,43 @@ +package com.baeldung.java9.rangedates; + +import java.time.LocalDate; +import java.util.Calendar; +import java.util.Date; + +public class RangeDatesIteration { + + public void iterateBetweenDatesJava9(LocalDate startDate, LocalDate endDate) { + + startDate.datesUntil(endDate) + .forEach(this::processDate); + } + + public void iterateBetweenDatesJava8(LocalDate start, LocalDate end) { + for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1)) { + processDate(date); + } + } + + public void iterateBetweenDatesJava7(Date start, Date end) { + Date current = start; + + while (current.before(end)) { + processDate(current); + + Calendar calendar = Calendar.getInstance(); + calendar.setTime(current); + + calendar.add(Calendar.DATE, 1); + + current = calendar.getTime(); + } + } + + private void processDate(LocalDate date) { + System.out.println(date); + } + + private void processDate(Date date) { + System.out.println(date); + } +} diff --git a/core-java-9/src/main/java/com/baeldung/optionals/Optionals.java b/core-java-9/src/main/java/com/baeldung/optionals/Optionals.java new file mode 100644 index 0000000000..5efa607f94 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/optionals/Optionals.java @@ -0,0 +1,26 @@ +package com.baeldung.optionals; + +import java.util.Optional; + +public class Optionals { + + public static Optional or(Optional optional, Optional fallback) { + return optional.isPresent() ? optional : fallback; + } + + public static Optional getName(Optional name) { + return name.or(() -> getCustomMessage()); + } + + public static com.google.common.base.Optional getOptionalGuavaName(com.google.common.base.Optional name) { + return name.or(getCustomMessageGuava()); + } + + private static Optional getCustomMessage() { + return Optional.of("Name not provided"); + } + + private static com.google.common.base.Optional getCustomMessageGuava() { + return com.google.common.base.Optional.of("Name not provided"); + } +} \ No newline at end of file diff --git a/core-java-9/src/main/resources/logback.xml b/core-java-9/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/core-java-9/src/main/resources/logback.xml +++ b/core-java-9/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java deleted file mode 100644 index ab69bba359..0000000000 --- a/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * - */ -package com.baeldung.java9.datetime; - -import static org.junit.Assert.assertEquals; - -import java.time.LocalDate; -import java.time.temporal.ChronoField; -import java.util.Calendar; -import java.util.Date; - -import org.junit.Test; - -import com.baeldung.java9.datetime.DateToLocalDateConverter; - -/** - * JUnits for {@link DateToLocalDateConverter} class. - * - * @author abialas - * - */ -public class DateToLocalDateConverterTest { - - @Test - public void shouldReturn10thNovember2010WhenConvertViaInstant() { - // given - Calendar calendar = Calendar.getInstance(); - calendar.set(2010, 10, 10); - Date dateToConvert = calendar.getTime(); - - // when - LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaInstant(dateToConvert); - - // then - assertEquals(2010, localDate.get(ChronoField.YEAR)); - assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); - assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); - } - - @Test - public void shouldReturn10thNovember2010WhenConvertViaMiliseconds() { - // given - Calendar calendar = Calendar.getInstance(); - calendar.set(2010, 10, 10); - Date dateToConvert = calendar.getTime(); - - // when - LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaMilisecond(dateToConvert); - - // then - assertEquals(2010, localDate.get(ChronoField.YEAR)); - assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); - assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); - } - - @Test - public void shouldReturn10thNovember2010WhenConvertViaSqlDate() { - // given - Calendar calendar = Calendar.getInstance(); - calendar.set(2010, 10, 10); - Date dateToConvert = calendar.getTime(); - - // when - LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaSqlDate(dateToConvert); - - // then - assertEquals(2010, localDate.get(ChronoField.YEAR)); - assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); - assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); - } - - @Test - public void shouldReturn10thNovember2010WhenConvertToLocalDate() { - // given - Calendar calendar = Calendar.getInstance(); - calendar.set(2010, 10, 10); - Date dateToConvert = calendar.getTime(); - - // when - LocalDate localDateTime = DateToLocalDateConverter.convertToLocalDate(dateToConvert); - - // then - assertEquals(2010, localDateTime.get(ChronoField.YEAR)); - assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); - assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); - } - -} diff --git a/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java deleted file mode 100644 index 97c70ee5ac..0000000000 --- a/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * - */ -package com.baeldung.java9.datetime; - -import static org.junit.Assert.assertEquals; - -import java.time.LocalDateTime; -import java.time.temporal.ChronoField; -import java.util.Calendar; -import java.util.Date; - -import org.junit.Test; - -import com.baeldung.java9.datetime.DateToLocalDateTimeConverter; - -/** - * JUnits for {@link DateToLocalDateTimeConverter} class. - * - * @author abialas - * - */ -public class DateToLocalDateTimeConverterTest { - - @Test - public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() { - // given - Calendar calendar = Calendar.getInstance(); - calendar.set(2010, 10, 10, 8, 20); - Date dateToConvert = calendar.getTime(); - - // when - LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaInstant(dateToConvert); - - // then - assertEquals(2010, localDateTime.get(ChronoField.YEAR)); - assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); - assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); - assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); - assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); - } - - @Test - public void shouldReturn10thNovember2010time8hour20minWhenConvertViaMiliseconds() { - // given - Calendar calendar = Calendar.getInstance(); - calendar.set(2010, 10, 10, 8, 20); - Date dateToConvert = calendar.getTime(); - - // when - LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaMilisecond(dateToConvert); - - // then - assertEquals(2010, localDateTime.get(ChronoField.YEAR)); - assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); - assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); - assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); - assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); - } - - @Test - public void shouldReturn10thNovember2010time8hour20minWhenConvertViaSqlTimestamp() { - // given - Calendar calendar = Calendar.getInstance(); - calendar.set(2010, 10, 10, 8, 20); - Date dateToConvert = calendar.getTime(); - - // when - LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaSqlTimestamp(dateToConvert); - - // then - assertEquals(2010, localDateTime.get(ChronoField.YEAR)); - assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); - assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); - assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); - assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); - } - - @Test - public void shouldReturn10thNovember2010time8hour20minWhenConvertToLocalDateTime() { - // given - Calendar calendar = Calendar.getInstance(); - calendar.set(2010, 10, 10, 8, 20); - Date dateToConvert = calendar.getTime(); - - // when - LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTime(dateToConvert); - - // then - assertEquals(2010, localDateTime.get(ChronoField.YEAR)); - assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); - assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); - assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); - assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); - } - -} diff --git a/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterTest.java b/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterTest.java deleted file mode 100644 index 2c6898381f..0000000000 --- a/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * - */ -package com.baeldung.java9.datetime; - -import static org.junit.Assert.assertEquals; - -import java.time.LocalDateTime; -import java.util.Calendar; -import java.util.Date; - -import org.junit.Test; - -/** - * - * JUnits for {@link LocalDateTimeToDateConverter} class. - * - * @author abialas - * - */ -public class LocalDateTimeToDateConverterTest { - - @Test - public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() { - // given - LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20); - - // when - Date date = LocalDateTimeToDateConverter.convertToDateViaInstant(dateToConvert); - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - - // then - assertEquals(2010, calendar.get(Calendar.YEAR)); - assertEquals(10, calendar.get(Calendar.MONTH)); - assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); - assertEquals(8, calendar.get(Calendar.HOUR)); - assertEquals(20, calendar.get(Calendar.MINUTE)); - assertEquals(0, calendar.get(Calendar.SECOND)); - } - - @Test - public void shouldReturn10thNovember2010WhenConvertViaSqlTimestamp() { - // given - LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20); - - // when - Date date = LocalDateTimeToDateConverter.convertToDateViaSqlTimestamp(dateToConvert); - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - - // then - assertEquals(2010, calendar.get(Calendar.YEAR)); - assertEquals(10, calendar.get(Calendar.MONTH)); - assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); - assertEquals(8, calendar.get(Calendar.HOUR)); - assertEquals(20, calendar.get(Calendar.MINUTE)); - assertEquals(0, calendar.get(Calendar.SECOND)); - } - -} diff --git a/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterTest.java b/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterTest.java deleted file mode 100644 index 7f20d5d2d2..0000000000 --- a/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * - */ -package com.baeldung.java9.datetime; - -import static org.junit.Assert.assertEquals; - -import java.time.LocalDate; -import java.util.Calendar; -import java.util.Date; - -import org.junit.Test; - -/** - * - * JUnits for {@link LocalDateToDateConverter} class. - * - * @author abialas - * - */ -public class LocalDateToDateConverterTest { - - @Test - public void shouldReturn10thNovember2010WhenConvertViaInstant() { - // given - LocalDate dateToConvert = LocalDate.of(2010, 11, 10); - - // when - Date date = LocalDateToDateConverter.convertToDateViaInstant(dateToConvert); - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - - // then - assertEquals(2010, calendar.get(Calendar.YEAR)); - assertEquals(10, calendar.get(Calendar.MONTH)); - assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); - } - - @Test - public void shouldReturn10thNovember2010WhenConvertViaSqlDate() { - // given - LocalDate dateToConvert = LocalDate.of(2010, 11, 10); - - // when - Date date = LocalDateToDateConverter.convertToDateViaSqlDate(dateToConvert); - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - - // then - assertEquals(2010, calendar.get(Calendar.YEAR)); - assertEquals(10, calendar.get(Calendar.MONTH)); - assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); - } - -} diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java new file mode 100644 index 0000000000..1b9315678a --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.java9.language.stream; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +public class CollectionFilterUnitTest { + + private static final Collection BASE_INTEGER_COLLECTION = Arrays.asList(9, 12, 55, 56, 101, 115, 8002, 223, 2668, 19, 8); + private static final Map> EXPECTED_EVEN_FILTERED_AFTER_GROUPING_MAP = createExpectedFilterAfterGroupingMap(); + private static Map> createExpectedFilterAfterGroupingMap() { + Map> map = new HashMap<>(); + map.put(1, Arrays.asList(8)); + map.put(2, Arrays.asList(12, 56)); + map.put(3, Collections.emptyList()); + map.put(4, Arrays.asList(8002, 2668)); + return map; + + } + + private static final Map> EXPECTED_EVEN_FILTERED_BEFORE_GROUPING_MAP = createExpectedFilterBeforeGroupingMap(); + private static Map> createExpectedFilterBeforeGroupingMap() { + Map> map = new HashMap<>(); + map.put(1, Arrays.asList(8)); + map.put(2, Arrays.asList(12, 56)); + map.put(4, Arrays.asList(8002, 2668)); + return map; + + } + + @Test + public void givenAStringCollection_whenFilteringFourLetterWords_thenObtainTheFilteredCollection() { + Map> filteredAfterGroupingMap = StreamsGroupingCollectionFilter.findEvenNumbersAfterGroupingByQuantityOfDigits(BASE_INTEGER_COLLECTION); + Map> filteredBeforeGroupingMap = StreamsGroupingCollectionFilter.findEvenNumbersBeforeGroupingByQuantityOfDigits(BASE_INTEGER_COLLECTION); + + assertThat(filteredAfterGroupingMap).containsAllEntriesOf(EXPECTED_EVEN_FILTERED_AFTER_GROUPING_MAP); + assertThat(filteredBeforeGroupingMap).doesNotContainKey(3) + .containsAllEntriesOf(EXPECTED_EVEN_FILTERED_BEFORE_GROUPING_MAP); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java new file mode 100644 index 0000000000..aa2fb34753 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java @@ -0,0 +1,199 @@ +package com.baeldung.java9.modules; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.collection.IsEmptyCollection.empty; +import static org.junit.Assert.*; + +import java.lang.module.ModuleDescriptor; +import java.lang.module.ModuleDescriptor.*; +import java.sql.Date; +import java.sql.Driver; +import java.util.HashMap; +import java.util.Set; +import java.util.stream.Collectors; + +import org.junit.Before; +import org.junit.Test; + +public class ModuleAPIUnitTest { + + public static final String JAVA_BASE_MODULE_NAME = "java.base"; + + private Module javaBaseModule; + private Module javaSqlModule; + private Module module; + + @Before + public void setUp() { + Class hashMapClass = HashMap.class; + javaBaseModule = hashMapClass.getModule(); + + Class dateClass = Date.class; + javaSqlModule = dateClass.getModule(); + + Class personClass = Person.class; + module = personClass.getModule(); + } + + @Test + public void whenCheckingIfNamed_thenModuleIsNamed() { + assertThat(javaBaseModule.isNamed(), is(true)); + assertThat(javaBaseModule.getName(), is(JAVA_BASE_MODULE_NAME)); + } + + @Test + public void whenCheckingIfNamed_thenModuleIsUnnamed() { + assertThat(module.isNamed(), is(false)); + assertThat(module.getName(), is(nullValue())); + } + + @Test + public void whenExtractingPackagesContainedInAModule_thenModuleContainsOnlyFewOfThem() { + assertTrue(javaBaseModule.getPackages().contains("java.lang.annotation")); + assertFalse(javaBaseModule.getPackages().contains("java.sql")); + } + + @Test + public void whenRetrievingClassLoader_thenClassLoaderIsReturned() { + assertThat( + module.getClassLoader().getClass().getName(), + is("jdk.internal.loader.ClassLoaders$AppClassLoader") + ); + } + + @Test + public void whenGettingAnnotationsPresentOnAModule_thenNoAnnotationsArePresent() { + assertThat(javaBaseModule.getAnnotations().length, is(0)); + } + + @Test + public void whenGettingLayerOfAModule_thenModuleLayerInformationAreAvailable() { + ModuleLayer javaBaseModuleLayer = javaBaseModule.getLayer(); + + assertTrue(javaBaseModuleLayer.configuration().findModule(JAVA_BASE_MODULE_NAME).isPresent()); + assertThat(javaBaseModuleLayer.configuration().modules().size(), is(78)); + assertTrue(javaBaseModuleLayer.parents().get(0).configuration().parents().isEmpty()); + } + + @Test + public void whenRetrievingModuleDescriptor_thenTypeOfModuleIsInferred() { + ModuleDescriptor javaBaseModuleDescriptor = javaBaseModule.getDescriptor(); + ModuleDescriptor javaSqlModuleDescriptor = javaSqlModule.getDescriptor(); + + assertFalse(javaBaseModuleDescriptor.isAutomatic()); + assertFalse(javaBaseModuleDescriptor.isOpen()); + assertFalse(javaSqlModuleDescriptor.isAutomatic()); + assertFalse(javaSqlModuleDescriptor.isOpen()); + } + + @Test + public void givenModuleName_whenBuildingModuleDescriptor_thenBuilt() { + Builder moduleBuilder = ModuleDescriptor.newModule("baeldung.base"); + + ModuleDescriptor moduleDescriptor = moduleBuilder.build(); + + assertThat(moduleDescriptor.name(), is("baeldung.base")); + } + + @Test + public void givenModules_whenAccessingModuleDescriptorRequires_thenRequiresAreReturned() { + Set javaBaseRequires = javaBaseModule.getDescriptor().requires(); + Set javaSqlRequires = javaSqlModule.getDescriptor().requires(); + + Set javaSqlRequiresNames = javaSqlRequires.stream() + .map(Requires::name) + .collect(Collectors.toSet()); + + assertThat(javaBaseRequires, empty()); + assertThat(javaSqlRequires.size(), is(3)); + assertThat(javaSqlRequiresNames, containsInAnyOrder("java.base", "java.xml", "java.logging")); + } + + @Test + public void givenModules_whenAccessingModuleDescriptorProvides_thenProvidesAreReturned() { + Set javaBaseProvides = javaBaseModule.getDescriptor().provides(); + Set javaSqlProvides = javaSqlModule.getDescriptor().provides(); + + Set javaBaseProvidesService = javaBaseProvides.stream() + .map(Provides::service) + .collect(Collectors.toSet()); + + assertThat(javaBaseProvidesService, contains("java.nio.file.spi.FileSystemProvider")); + assertThat(javaSqlProvides, empty()); + } + + @Test + public void givenModules_whenAccessingModuleDescriptorExports_thenExportsAreReturned() { + Set javaBaseExports = javaBaseModule.getDescriptor().exports(); + Set javaSqlExports = javaSqlModule.getDescriptor().exports(); + + Set javaSqlExportsSource = javaSqlExports.stream() + .map(Exports::source) + .collect(Collectors.toSet()); + + assertThat(javaBaseExports.size(), is(108)); + assertThat(javaSqlExports.size(), is(3)); + assertThat(javaSqlExportsSource, containsInAnyOrder("java.sql", "javax.transaction.xa", "javax.sql")); + } + + @Test + public void givenModules_whenAccessingModuleDescriptorUses_thenUsesAreReturned() { + Set javaBaseUses = javaBaseModule.getDescriptor().uses(); + Set javaSqlUses = javaSqlModule.getDescriptor().uses(); + + assertThat(javaBaseUses.size(), is(34)); + assertThat(javaSqlUses, contains("java.sql.Driver")); + } + + @Test + public void givenModules_whenAccessingModuleDescriptorOpen_thenOpenAreReturned() { + Set javaBaseUses = javaBaseModule.getDescriptor().opens(); + Set javaSqlUses = javaSqlModule.getDescriptor().opens(); + + assertThat(javaBaseUses, empty()); + assertThat(javaSqlUses, empty()); + } + + @Test + public void whenAddingReadsToAModule_thenModuleCanReadNewModule() { + Module updatedModule = module.addReads(javaSqlModule); + + assertTrue(updatedModule.canRead(javaSqlModule)); + } + + @Test + public void whenExportingPackage_thenPackageIsExported() { + Module updatedModule = module.addExports("com.baeldung.java9.modules", javaSqlModule); + + assertTrue(updatedModule.isExported("com.baeldung.java9.modules")); + } + + @Test + public void whenOpeningAModulePackage_thenPackagedIsOpened() { + Module updatedModule = module.addOpens("com.baeldung.java9.modules", javaSqlModule); + + assertTrue(updatedModule.isOpen("com.baeldung.java9.modules", javaSqlModule)); + } + + @Test + public void whenAddingUsesToModule_thenUsesIsAdded() { + Module updatedModule = module.addUses(Driver.class); + + assertTrue(updatedModule.canUse(Driver.class)); + } + + private class Person { + private String name; + + public Person(String name) { + this.name = name; + } + + public String getName() { + return name; + } + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java new file mode 100644 index 0000000000..2c5525b9ed --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java @@ -0,0 +1,121 @@ +package com.baeldung.java9.process; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.String; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.lang.Integer; + +import org.junit.jupiter.api.Test; + +class ProcessUnderstandingTest { + + @Test + public void givenSourceProgram_whenExecutedFromAnotherProgram_thenSourceProgramOutput3() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java"); + process = Runtime.getRuntime() + .exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample"); + BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream())); + int value = Integer.parseInt(output.readLine()); + assertEquals(3, value); + } + + @Test + public void givenSourceProgram_whenReadingInputStream_thenFirstLineEquals3() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java"); + process = Runtime.getRuntime() + .exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample"); + BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream())); + int value = Integer.parseInt(output.readLine()); + assertEquals(3, value); + } + + @Test + public void givenSubProcess_whenEncounteringError_thenErrorStreamNotNull() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java"); + BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream())); + String errorString = error.readLine(); + assertNotNull(errorString); + } + + //@Test - windows specific + public void givenSubProcess_whenStarted_thenStartSuccessIsAlive() throws IOException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + assertTrue(builder.start().isAlive()); + } + + //@Test - windows specific + public void givenSubProcess_whenDestroying_thenProcessNotAlive() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + assertFalse(process.isAlive()); + } + + //@Test - windows specific + public void givenSubProcess_whenAlive_thenDestroyForcibly() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + if (process.isAlive()) { + process.destroyForcibly(); + } + assertFalse(process.isAlive()); + } + + //@Test - windows specific + public void givenSubProcess_whenDestroyed_thenCheckIfAlive() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + assertFalse(process.isAlive()); + } + + @Test + public void givenProcessNotCreated_fromWithinJavaApplicationDestroying_thenProcessNotAlive() { + Optional optionalProcessHandle = ProcessHandle.of(5232); + ProcessHandle processHandle = optionalProcessHandle.get(); + processHandle.destroy(); + assertFalse(processHandle.isAlive()); + } + + //@Test - windows specific + public void givenSubProcess_whenCurrentThreadWaitsIndefinitelyuntilSubProcessEnds_thenProcessWaitForReturnsGrt0() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + assertThat(process.waitFor() >= 0); + } + + //@Test - windows specific + public void givenSubProcess_whenCurrentThreadWaitsAndSubProcessNotTerminated_thenProcessWaitForReturnsFalse() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + assertFalse(process.waitFor(1, TimeUnit.SECONDS)); + } + + //@Test - windows specific + public void givenSubProcess_whenCurrentThreadWillNotWaitIndefinitelyforSubProcessToEnd_thenProcessExitValueReturnsGrt0() throws IOException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + assertThat(process.exitValue() >= 0); + } + + @Test + public void givenRunningProcesses_whenFilterOnProcessIdRange_thenGetSelectedProcessPid() { + assertThat(((int) ProcessHandle.allProcesses() + .filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000)) + .count()) > 0); + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/rangedates/DatesCollectionIterationUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/rangedates/DatesCollectionIterationUnitTest.java new file mode 100644 index 0000000000..522b00065e --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/rangedates/DatesCollectionIterationUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.java9.rangedates; + +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.Test; + +public class DatesCollectionIterationUnitTest { + + private Collection localDates = LocalDate.now() + .datesUntil(LocalDate.now() + .plus(10L, ChronoUnit.DAYS)) + .collect(Collectors.toList()); + + private Collection dates = localDates.stream() + .map(localDate -> Date.from(localDate.atStartOfDay(ZoneId.systemDefault()) + .toInstant())) + .collect(Collectors.toList()); + + @Test + public void givenIteratingListOfDatesJava7_WhenStartTodayAndEnding10DaysAhead() { + DatesCollectionIteration iterateInColleciton = new DatesCollectionIteration(); + Calendar today = Calendar.getInstance(); + Calendar next10Ahead = (Calendar) today.clone(); + next10Ahead.add(Calendar.DATE, 10); + + iterateInColleciton.iteratingRangeOfDatesJava7(createRangeDates(today.getTime(), next10Ahead.getTime())); + } + + @Test + public void givenIteratingListOfDatesJava8_WhenStartTodayAndEnd10DaysAhead() { + DatesCollectionIteration iterateInColleciton = new DatesCollectionIteration(); + + iterateInColleciton.iteratingRangeOfDatesJava8(dates); + } + + private List createRangeDates(Date start, Date end) { + + List dates = new ArrayList<>(); + Date current = start; + + while (current.before(end)) { + dates.add(current); + + Calendar calendar = Calendar.getInstance(); + calendar.setTime(current); + calendar.add(Calendar.DATE, 1); + + current = calendar.getTime(); + } + + return dates; + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/rangedates/RangeDatesIterationUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/rangedates/RangeDatesIterationUnitTest.java new file mode 100644 index 0000000000..4f5cd17d98 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/rangedates/RangeDatesIterationUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.java9.rangedates; + +import java.time.LocalDate; +import java.time.temporal.ChronoUnit; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +public class RangeDatesIterationUnitTest { + + @Test + public void givenIterateBetweenDatesJava9_WhenStartDateAsTodayAndEndDateAs10DaysAhead() { + LocalDate start = LocalDate.now(); + LocalDate end = start.plus(10L, ChronoUnit.DAYS); + + RangeDatesIteration iteration = new RangeDatesIteration(); + + iteration.iterateBetweenDatesJava9(start, end); + } + + @Test + public void givenIterateBetweenDatesJava8_WhenStartDateAsTodayAndEndDateAs10DaysAhead() { + LocalDate start = LocalDate.now(); + LocalDate end = start.plus(10L, ChronoUnit.DAYS); + + RangeDatesIteration iteration = new RangeDatesIteration(); + + iteration.iterateBetweenDatesJava8(start, end); + } + + @Test + public void givenIterateBetweenDatesJava7_WhenStartDateAsTodayAndEndDateAs10DaysAhead() { + Calendar today = Calendar.getInstance(); + Calendar calendar = Calendar.getInstance(); + calendar.clear(); + calendar.set(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE)); + Date start = calendar.getTime(); + + calendar.add(Calendar.DATE, 10); + Date end = calendar.getTime(); + + RangeDatesIteration iteration = new RangeDatesIteration(); + + iteration.iterateBetweenDatesJava7(start, end); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/time/TimeApiTest.java b/core-java-9/src/test/java/com/baeldung/java9/time/TimeApiTest.java deleted file mode 100644 index a024db19a8..0000000000 --- a/core-java-9/src/test/java/com/baeldung/java9/time/TimeApiTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.java9.time; - -import java.time.LocalDate; -import java.util.Calendar; -import java.util.Date; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import org.junit.Test; - -public class TimeApiTest { - - @Test - public void givenGetDatesBetweenWithUsingJava7_WhenStartEndDate_thenDatesList() { - Date startDate = Calendar.getInstance().getTime(); - Calendar endCalendar = Calendar.getInstance(); - endCalendar.add(Calendar.DATE, 2); - Date endDate = endCalendar.getTime(); - - List dates = TimeApi.getDatesBetweenUsingJava7(startDate, endDate); - assertEquals(dates.size(), 2); - - Calendar calendar = Calendar.getInstance(); - Date date1 = calendar.getTime(); - assertEquals(dates.get(0).getDay(), date1.getDay()); - assertEquals(dates.get(0).getMonth(), date1.getMonth()); - assertEquals(dates.get(0).getYear(), date1.getYear()); - - calendar.add(Calendar.DATE, 1); - Date date2 = calendar.getTime(); - assertEquals(dates.get(1).getDay(), date2.getDay()); - assertEquals(dates.get(1).getMonth(), date2.getMonth()); - assertEquals(dates.get(1).getYear(), date2.getYear()); - } - - @Test - public void givenGetDatesBetweenWithUsingJava8_WhenStartEndDate_thenDatesList() { - LocalDate startDate = LocalDate.now(); - LocalDate endDate = LocalDate.now().plusDays(2); - - List dates = TimeApi.getDatesBetweenUsingJava8(startDate, endDate); - assertEquals(dates.size(), 2); - assertEquals(dates.get(0), LocalDate.now()); - assertEquals(dates.get(1), LocalDate.now().plusDays(1)); - } - - @Test - public void givenGetDatesBetweenWithUsingJava9_WhenStartEndDate_thenDatesList() { - LocalDate startDate = LocalDate.now(); - LocalDate endDate = LocalDate.now().plusDays(2); - - List dates = TimeApi.getDatesBetweenUsingJava9(startDate, endDate); - assertEquals(dates.size(), 2); - assertEquals(dates.get(0), LocalDate.now()); - assertEquals(dates.get(1), LocalDate.now().plusDays(1)); - } - -} diff --git a/core-java-9/src/test/java/com/baeldung/optionals/OptionalsTest.java b/core-java-9/src/test/java/com/baeldung/optionals/OptionalsTest.java new file mode 100644 index 0000000000..4e5f94c0db --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/optionals/OptionalsTest.java @@ -0,0 +1,51 @@ +package com.baeldung.optionals; + +import static org.junit.Assert.assertEquals; + +import java.util.Optional; + +import org.junit.Test; + +public class OptionalsTest { + + @Test + public void givenOptional_whenEmptyValue_thenCustomMessage() { + assertEquals(Optional.of("Name not provided"), Optionals.getName(Optional.ofNullable(null))); + } + + @Test + public void givenOptional_whenValue_thenOptional() { + String name = "Filan Fisteku"; + Optional optionalString = Optional.ofNullable(name); + assertEquals(optionalString, Optionals.getName(optionalString)); + } + + @Test + public void givenOptional_whenValue_thenOptionalGeneralMethod() { + String name = "Filan Fisteku"; + String missingOptional = "Name not provided"; + Optional optionalString = Optional.ofNullable(name); + Optional fallbackOptionalString = Optional.ofNullable(missingOptional); + assertEquals(optionalString, Optionals.or(optionalString, fallbackOptionalString)); + } + + @Test + public void givenEmptyOptional_whenValue_thenOptionalGeneralMethod() { + String missingOptional = "Name not provided"; + Optional optionalString = Optional.empty(); + Optional fallbackOptionalString = Optional.ofNullable(missingOptional); + assertEquals(fallbackOptionalString, Optionals.or(optionalString, fallbackOptionalString)); + } + + @Test + public void givenGuavaOptional_whenInvoke_thenOptional() { + String name = "Filan Fisteku"; + com.google.common.base.Optional stringOptional = com.google.common.base.Optional.of(name); + assertEquals(stringOptional, Optionals.getOptionalGuavaName(stringOptional)); + } + + @Test + public void givenGuavaOptional_whenNull_thenDefaultText() { + assertEquals(com.google.common.base.Optional.of("Name not provided"), Optionals.getOptionalGuavaName(com.google.common.base.Optional.fromNullable(null))); + } +} \ No newline at end of file diff --git a/core-java-collections/README.md b/core-java-collections/README.md index e0cea14b20..f187141712 100644 --- a/core-java-collections/README.md +++ b/core-java-collections/README.md @@ -28,3 +28,24 @@ - [A Guide to TreeSet in Java](http://www.baeldung.com/java-tree-set) - [Java TreeMap vs HashMap](http://www.baeldung.com/java-treemap-vs-hashmap) - [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list) +- [How to Store Duplicate Keys in a Map in Java?](http://www.baeldung.com/java-map-duplicate-keys) +- [Getting the Size of an Iterable in Java](http://www.baeldung.com/java-iterable-size) +- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards) +- [How to Filter a Collection in Java](http://www.baeldung.com/java-collection-filtering) +- [Add Multiple Items to an Java ArrayList](http://www.baeldung.com/java-add-items-array-list) +- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list) +- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map) +- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset) +- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element) +- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator) +- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection) +- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java) +- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table) +- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another) +- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max) +- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections) +- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list) +- [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe) +- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list) +- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) +- [](https://www.baeldung.com/java-hashset-arraylist-contains-performance) diff --git a/core-java-collections/pom.xml b/core-java-collections/pom.xml index c5d3396642..92e4278593 100644 --- a/core-java-collections/pom.xml +++ b/core-java-collections/pom.xml @@ -1,60 +1,79 @@ - 4.0.0 - com.baeldung - core-java-collections - 0.1.0-SNAPSHOT - jar - core-java-collections + 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 + core-java-collections + 0.1.0-SNAPSHOT + jar + core-java-collections - + com.baeldung parent-java - 0.0.1-SNAPSHOT - ../parent-java + 0.0.1-SNAPSHOT + ../parent-java - - - junit - junit - ${junit.version} - test - - - net.sourceforge.collections - collections-generic - ${collections-generic.version} - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - - - com.jayway.awaitility - awaitility - ${avaitility.version} - test - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - org.assertj - assertj-core - ${assertj.version} - test - - + + + net.sourceforge.collections + collections-generic + ${collections-generic.version} + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + com.jayway.awaitility + awaitility + ${avaitility.version} + test + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.eclipse.collections + eclipse-collections + ${eclipse.collections.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + org.openjdk.jmh + jmh-core + ${openjdk.jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${openjdk.jmh.version} + + - - 3.5 - 4.1 - 4.01 - 1.7.0 - 3.6.1 - + + + 1.19 + 1.2.0 + 3.5 + 4.1 + 4.01 + 1.7.0 + 3.6.1 + 7.1.0 + diff --git a/core-java-collections/src/main/java/com/baeldung/convertlisttomap/Animal.java b/core-java-collections/src/main/java/com/baeldung/convertlisttomap/Animal.java new file mode 100644 index 0000000000..b8eddf71a5 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/convertlisttomap/Animal.java @@ -0,0 +1,27 @@ +package com.baeldung.convertlisttomap; + +public class Animal { + private int id; + private String name; + + public Animal(int id, String name) { + this.id = id; + this.setName(name); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java b/core-java-collections/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java new file mode 100644 index 0000000000..6527d35742 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java @@ -0,0 +1,42 @@ +package com.baeldung.convertlisttomap; + +import com.google.common.collect.Maps; +import org.apache.commons.collections4.MapUtils; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class ConvertListToMapService { + + public Map convertListBeforeJava8(List list) { + + Map map = new HashMap<>(); + + for (Animal animal : list) { + map.put(animal.getId(), animal); + } + return map; + } + + public Map convertListAfterJava8(List list) { + Map map = list.stream().collect(Collectors.toMap(Animal::getId, animal -> animal)); + return map; + } + + public Map convertListWithGuava(List list) { + + Map map = Maps.uniqueIndex(list, Animal::getId); + return map; + } + + public Map convertListWithApacheCommons(List list) { + + Map map = new HashMap<>(); + + MapUtils.populateMap(map, list, Animal::getId); + + return map; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/findanelement/Customer.java b/core-java-collections/src/main/java/com/baeldung/findanelement/Customer.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/findanelement/Customer.java rename to core-java-collections/src/main/java/com/baeldung/findanelement/Customer.java diff --git a/core-java-8/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java b/core-java-collections/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java rename to core-java-collections/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java diff --git a/core-java-8/src/main/java/com/baeldung/hashtable/Word.java b/core-java-collections/src/main/java/com/baeldung/hashtable/Word.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/hashtable/Word.java rename to core-java-collections/src/main/java/com/baeldung/hashtable/Word.java diff --git a/core-java-8/src/main/java/com/baeldung/iterators/Iterators.java b/core-java-collections/src/main/java/com/baeldung/iterators/Iterators.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/iterators/Iterators.java rename to core-java-collections/src/main/java/com/baeldung/iterators/Iterators.java diff --git a/core-java-collections/src/main/java/com/baeldung/java/filtering/CollectionUtilsCollectionFilter.java b/core-java-collections/src/main/java/com/baeldung/java/filtering/CollectionUtilsCollectionFilter.java new file mode 100644 index 0000000000..58f9f6af54 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/filtering/CollectionUtilsCollectionFilter.java @@ -0,0 +1,16 @@ +package com.baeldung.java.filtering; + +import java.util.Collection; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.Predicate; + +public class CollectionUtilsCollectionFilter { + + static public Collection findEvenNumbers(Collection baseCollection) { + Predicate apacheEventNumberPredicate = item -> item % 2 == 0; + + CollectionUtils.filter(baseCollection, apacheEventNumberPredicate); + return baseCollection; + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/java/filtering/EclipseCollectionsCollectionFilter.java b/core-java-collections/src/main/java/com/baeldung/java/filtering/EclipseCollectionsCollectionFilter.java new file mode 100644 index 0000000000..981d6ca241 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/filtering/EclipseCollectionsCollectionFilter.java @@ -0,0 +1,32 @@ +package com.baeldung.java.filtering; + +import java.util.Collection; + +import org.eclipse.collections.api.block.predicate.Predicate; +import org.eclipse.collections.impl.factory.Lists; +import org.eclipse.collections.impl.utility.Iterate; + +public class EclipseCollectionsCollectionFilter { + + static public Collection findEvenNumbers(Collection baseCollection) { + Predicate eclipsePredicate = item -> item % 2 == 0; + Collection filteredList = Lists.mutable.ofAll(baseCollection) + .select(eclipsePredicate); + + return filteredList; + } + + static public Collection findEvenNumbersUsingIterate(Collection baseCollection) { + Predicate eclipsePredicate = new Predicate() { + private static final long serialVersionUID = 1L; + + @Override + public boolean accept(Integer arg0) { + return arg0 % 2 == 0; + } + }; + Collection filteredList = Iterate.select(baseCollection, eclipsePredicate); + + return filteredList; + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/java/filtering/GuavaCollectionFilter.java b/core-java-collections/src/main/java/com/baeldung/java/filtering/GuavaCollectionFilter.java new file mode 100644 index 0000000000..88338fd6d4 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/filtering/GuavaCollectionFilter.java @@ -0,0 +1,17 @@ +package com.baeldung.java.filtering; + +import java.util.Collection; + +import com.google.common.base.Predicate; +import com.google.common.collect.Collections2; + +public class GuavaCollectionFilter { + + static public Collection findEvenNumbers(Collection baseCollection) { + Predicate guavaPredicate = item -> item % 2 == 0; + + Collection filteredCollection = Collections2.filter(baseCollection, guavaPredicate); + return filteredCollection; + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/java/filtering/StreamsCollectionFilter.java b/core-java-collections/src/main/java/com/baeldung/java/filtering/StreamsCollectionFilter.java new file mode 100644 index 0000000000..f074f74199 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/filtering/StreamsCollectionFilter.java @@ -0,0 +1,26 @@ +package com.baeldung.java.filtering; + +import java.util.Collection; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +public class StreamsCollectionFilter { + + public static Collection filterCollectionHelperMethod(Collection baseCollection, Predicate predicate) { + return baseCollection.stream() + .filter(predicate) + .collect(Collectors.toList()); + } + + static public Collection findEvenNumbersUsingHelperMethod(Collection baseCollection) { + return filterCollectionHelperMethod(baseCollection, item -> item % 2 == 0); + } + + static public Collection findEvenNumbers(Collection baseCollection) { + Predicate streamsPredicate = item -> item % 2 == 0; + + return baseCollection.stream() + .filter(streamsPredicate) + .collect(Collectors.toList()); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/java/iterable/IterableSize.java b/core-java-collections/src/main/java/com/baeldung/java/iterable/IterableSize.java new file mode 100644 index 0000000000..03864f16f2 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/iterable/IterableSize.java @@ -0,0 +1,65 @@ +package com.baeldung.java.iterable; + +import java.util.Collection; +import java.util.stream.StreamSupport; + +import org.apache.commons.collections4.IterableUtils; + +import com.google.common.collect.Iterables; + +/** + * Provides methods for getting the size of an {@link Iterable} object. + */ +public class IterableSize { + + /** + * Get the size of {@code Iterable} using Java 7. + * + * @param data the iterable + * @return the size of the iterable + */ + public static int sizeUsingJava7(final Iterable data) { + + if (data instanceof Collection) { + return ((Collection) data).size(); + } + int counter = 0; + for (final Object i : data) { + counter++; + } + return counter; + } + + /** + * Get the size of {@code Iterable} using Java 8. + * + * @param data the iterable + * @return the size of the iterable + */ + public static long sizeUsingJava8(final Iterable data) { + + return StreamSupport.stream(data.spliterator(), false).count(); + } + + /** + * Get the size of {@code Iterable} using Apache Collections. + * + * @param data the iterable + * @return the size of the iterable + */ + public static int sizeUsingApacheCollections(final Iterable data) { + + return IterableUtils.size(data); + } + + /** + * Get the size of {@code Iterable} using Google Guava. + * + * @param data the iterable + * @return the size of the iterable + */ + public static int sizeUsingGoogleGuava(final Iterable data) { + + return Iterables.size(data); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/java/list/CopyListService.java b/core-java-collections/src/main/java/com/baeldung/java/list/CopyListService.java new file mode 100644 index 0000000000..5c92d856aa --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/list/CopyListService.java @@ -0,0 +1,73 @@ +package com.baeldung.java.list; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class CopyListService { + + public List copyListByConstructor(List source) { + return new ArrayList(source); + } + + public List copyListByConstructorAndEditOneFlowerInTheNewList(List source) { + List flowers = new ArrayList<>(source); + if(flowers.size() > 0) { + flowers.get(0).setPetals(flowers.get(0).getPetals() * 3); + } + + return flowers; + } + + public List copyListByAddAllMethod(List source) { + List flowers = new ArrayList<>(); + flowers.addAll(source); + return flowers; + } + + public List copyListByAddAllMethodAndEditOneFlowerInTheNewList(List source) { + List flowers = new ArrayList<>(); + flowers.addAll(source); + + if(flowers.size() > 0) { + flowers.get(0).setPetals(flowers.get(0).getPetals() * 3); + } + + return flowers; + } + + public List copyListByCopyMethod(List source, List dest) { + Collections.copy(dest, source); + return dest; + } + + public List copyListByStream(List source) { + return source.stream().collect(Collectors.toList()); + } + + public List copyListByStreamAndSkipFirstElement(List source) { + return source.stream().skip(1).collect(Collectors.toList()); + } + + public List copyListByStreamWithFilter(List source, Integer moreThanPetals) { + return source.stream().filter(f -> f.getPetals() > moreThanPetals).collect(Collectors.toList()); + } + + public List copyListByStreamWithOptional(List source) { + return Optional.ofNullable(source) + .map(List::stream) + .orElseGet(Stream::empty) + .collect(Collectors.toList()); + } + + public List copyListByStreamWithOptionalAndSkip(List source) { + return Optional.ofNullable(source) + .map(List::stream) + .orElseGet(Stream::empty) + .skip(1) + .collect(Collectors.toList()); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/java/list/Flower.java b/core-java-collections/src/main/java/com/baeldung/java/list/Flower.java new file mode 100644 index 0000000000..eb897ea72f --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/list/Flower.java @@ -0,0 +1,28 @@ +package com.baeldung.java.list; + +public class Flower { + + private String name; + private int petals; + + public Flower(String name, int petals) { + this.name = name; + this.petals = petals; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getPetals() { + return petals; + } + + public void setPetals(int petals) { + this.petals = petals; + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/java/list/ReverseIterator.java b/core-java-collections/src/main/java/com/baeldung/java/list/ReverseIterator.java new file mode 100644 index 0000000000..42dd543ed4 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/list/ReverseIterator.java @@ -0,0 +1,80 @@ +package com.baeldung.java.list; + +import java.util.Collections; +import java.util.List; +import java.util.ListIterator; + +import org.apache.commons.collections4.iterators.ReverseListIterator; + +import com.google.common.collect.Lists; + +/** + * Provides methods for iterating backward over a list. + */ +public class ReverseIterator { + + /** + * Iterate using the for loop. + * + * @param list the list + */ + public void iterateUsingForLoop(final List list) { + + for (int i = list.size(); i-- > 0; ) { + System.out.println(list.get(i)); + } + } + + /** + * Iterate using the Java {@link ListIterator}. + * + * @param list the list + */ + public void iterateUsingListIterator(final List list) { + + final ListIterator listIterator = list.listIterator(list.size()); + while (listIterator.hasPrevious()) { + System.out.println(listIterator.previous()); + } + } + + /** + * Iterate using Java {@link Collections} API. + * + * @param list the list + */ + public void iterateUsingCollections(final List list) { + + Collections.reverse(list); + for (final String item : list) { + System.out.println(item); + } + } + + /** + * Iterate using Apache Commons {@link ReverseListIterator}. + * + * @param list the list + */ + public void iterateUsingApacheReverseListIterator(final List list) { + + final ReverseListIterator listIterator = new ReverseListIterator(list); + while (listIterator.hasNext()) { + System.out.println(listIterator.next()); + } + } + + /** + * Iterate using Guava {@link Lists} API. + * + * @param list the list + */ + public void iterateUsingGuava(final List list) { + + final List reversedList = Lists.reverse(list); + for (final String item : reversedList) { + System.out.println(item); + } + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/java/map/MapUtil.java b/core-java-collections/src/main/java/com/baeldung/java/map/MapUtil.java new file mode 100644 index 0000000000..688c7592f3 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/map/MapUtil.java @@ -0,0 +1,44 @@ +/** + * + */ +package com.baeldung.java.map; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.Map.Entry; +import java.util.stream.Stream; + +/** + * @author swpraman + * + */ +public class MapUtil { + + public static Stream keys(Map map, V value) { + return map.entrySet() + .stream() + .filter(entry -> value.equals(entry.getValue())) + .map(Map.Entry::getKey); + } + + public static Set getKeys(Map map, V value) { + Set keys = new HashSet<>(); + for (Entry entry : map.entrySet()) { + if (entry.getValue().equals(value)) { + keys.add(entry.getKey()); + } + } + return keys; + } + + public static K getKey(Map map, V value) { + for (Entry entry : map.entrySet()) { + if (entry.getValue().equals(value)) { + return entry.getKey(); + } + } + return null; + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/java/map/initialize/MapInitializer.java b/core-java-collections/src/main/java/com/baeldung/java/map/initialize/MapInitializer.java new file mode 100644 index 0000000000..4dbaceac62 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/map/initialize/MapInitializer.java @@ -0,0 +1,80 @@ +package com.baeldung.java.map.initialize; + +import java.util.AbstractMap; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class MapInitializer { + + public static Map articleMapOne; + static { + articleMapOne = new HashMap<>(); + articleMapOne.put("ar01", "Intro to Map"); + articleMapOne.put("ar02", "Some article"); + } + + public static Map createSingletonMap() { + Map passwordMap = Collections.singletonMap("username1", "password1"); + return passwordMap; + + } + + public Map createEmptyMap() { + Map emptyMap = Collections.emptyMap(); + return emptyMap; + } + + public Map createUsingDoubleBrace() { + Map doubleBraceMap = new HashMap() { + + /** + * + */ + private static final long serialVersionUID = 1L; + + { + put("key1", "value1"); + put("key2", "value2"); + } + }; + return doubleBraceMap; + } + + public Map createMapUsingStreamStringArray() { + Map map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, }) + .collect(Collectors.toMap(data -> data[0], data -> data[1])); + + return map; + } + + public Map createMapUsingStreamObjectArray() { + Map map = Stream.of(new Object[][] { { "data1", 1 }, { "data2", 2 }, }) + .collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1])); + + return map; + } + + public Map createMapUsingStreamSimpleEntry() { + Map map = Stream.of(new AbstractMap.SimpleEntry<>("idea", 1), new AbstractMap.SimpleEntry<>("mobile", 2)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + + return map; + } + + public Map createMapUsingStreamSimpleImmutableEntry() { + Map map = Stream.of(new AbstractMap.SimpleImmutableEntry<>("idea", 1), new AbstractMap.SimpleImmutableEntry<>("mobile", 2)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + + return map; + } + + public Map createImmutableMapWithStreams() { + Map map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, }) + .collect(Collectors.collectingAndThen(Collectors.toMap(data -> data[0], data -> data[1]), Collections:: unmodifiableMap)); + return map; + + } +} diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Car.java b/core-java-collections/src/main/java/com/baeldung/java_8_features/Car.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/Car.java rename to core-java-collections/src/main/java/com/baeldung/java_8_features/Car.java diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Person.java b/core-java-collections/src/main/java/com/baeldung/java_8_features/Person.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/Person.java rename to core-java-collections/src/main/java/com/baeldung/java_8_features/Person.java diff --git a/core-java-collections/src/main/java/com/baeldung/list/list/listoflist/Pen.java b/core-java-collections/src/main/java/com/baeldung/list/listoflist/Pen.java similarity index 100% rename from core-java-collections/src/main/java/com/baeldung/list/list/listoflist/Pen.java rename to core-java-collections/src/main/java/com/baeldung/list/listoflist/Pen.java diff --git a/core-java-collections/src/main/java/com/baeldung/list/list/listoflist/Pencil.java b/core-java-collections/src/main/java/com/baeldung/list/listoflist/Pencil.java similarity index 100% rename from core-java-collections/src/main/java/com/baeldung/list/list/listoflist/Pencil.java rename to core-java-collections/src/main/java/com/baeldung/list/listoflist/Pencil.java diff --git a/core-java-collections/src/main/java/com/baeldung/list/list/listoflist/Rubber.java b/core-java-collections/src/main/java/com/baeldung/list/listoflist/Rubber.java similarity index 100% rename from core-java-collections/src/main/java/com/baeldung/list/list/listoflist/Rubber.java rename to core-java-collections/src/main/java/com/baeldung/list/listoflist/Rubber.java diff --git a/core-java-collections/src/main/java/com/baeldung/list/list/listoflist/Stationery.java b/core-java-collections/src/main/java/com/baeldung/list/listoflist/Stationery.java similarity index 100% rename from core-java-collections/src/main/java/com/baeldung/list/list/listoflist/Stationery.java rename to core-java-collections/src/main/java/com/baeldung/list/listoflist/Stationery.java diff --git a/core-java-collections/src/main/java/com/baeldung/list/removeall/RemoveAll.java b/core-java-collections/src/main/java/com/baeldung/list/removeall/RemoveAll.java new file mode 100644 index 0000000000..d5f9cf4b4e --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/list/removeall/RemoveAll.java @@ -0,0 +1,111 @@ +package com.baeldung.list.removeall; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +public class RemoveAll { + + static void removeWithWhileLoopPrimitiveElement(List list, int element) { + while (list.contains(element)) { + list.remove(element); + } + } + + static void removeWithWhileLoopNonPrimitiveElement(List list, Integer element) { + while (list.contains(element)) { + list.remove(element); + } + } + + static void removeWithWhileLoopStoringFirstOccurrenceIndex(List list, Integer element) { + int index; + while ((index = list.indexOf(element)) >= 0) { + list.remove(index); + } + } + + static void removeWithCallingRemoveUntilModifies(List list, Integer element) { + while (list.remove(element)) + ; + } + + static void removeWithStandardForLoopUsingIndex(List list, int element) { + for (int i = 0; i < list.size(); i++) { + if (Objects.equals(element, list.get(i))) { + list.remove(i); + } + } + } + + static void removeWithForLoopDecrementOnRemove(List list, int element) { + for (int i = 0; i < list.size(); i++) { + if (Objects.equals(element, list.get(i))) { + list.remove(i); + i--; + } + } + } + + static void removeWithForLoopIncrementIfRemains(List list, int element) { + for (int i = 0; i < list.size();) { + if (Objects.equals(element, list.get(i))) { + list.remove(i); + } else { + i++; + } + } + } + + static void removeWithForEachLoop(List list, int element) { + for (Integer number : list) { + if (Objects.equals(number, element)) { + list.remove(number); + } + } + } + + static void removeWithIterator(List list, int element) { + for (Iterator i = list.iterator(); i.hasNext();) { + Integer number = i.next(); + if (Objects.equals(number, element)) { + i.remove(); + } + } + } + + static List removeWithCollectingAndReturningRemainingElements(List list, int element) { + List remainingElements = new ArrayList<>(); + for (Integer number : list) { + if (!Objects.equals(number, element)) { + remainingElements.add(number); + } + } + return remainingElements; + } + + static void removeWithCollectingRemainingElementsAndAddingToOriginalList(List list, int element) { + List remainingElements = new ArrayList<>(); + for (Integer number : list) { + if (!Objects.equals(number, element)) { + remainingElements.add(number); + } + } + + list.clear(); + list.addAll(remainingElements); + } + + static List removeWithStreamFilter(List list, Integer element) { + return list.stream() + .filter(e -> !Objects.equals(e, element)) + .collect(Collectors.toList()); + } + + static void removeWithRemoveIf(List list, Integer element) { + list.removeIf(n -> Objects.equals(n, element)); + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java b/core-java-collections/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java new file mode 100644 index 0000000000..2405c26aac --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java @@ -0,0 +1,19 @@ +package com.baeldung.nullsafecollectionstreams; + +import java.util.Collection; +import java.util.stream.Stream; +import static org.apache.commons.collections4.CollectionUtils.emptyIfNull; + +public class NullSafeCollectionStreamsUsingCommonsEmptyIfNull { + + /** + * This method shows how to make a null safe stream from a collection through the use of + * emptyIfNull() method from Apache Commons CollectionUtils library + * + * @param collection The collection that is to be converted into a stream + * @return The stream that has been created from the collection or an empty stream if the collection is null + */ + public Stream collectionAsStream(Collection collection) { + return emptyIfNull(collection).stream(); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java b/core-java-collections/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java new file mode 100644 index 0000000000..da767d4563 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java @@ -0,0 +1,21 @@ +package com.baeldung.nullsafecollectionstreams; + +import java.util.Collection; +import java.util.Optional; +import java.util.stream.Stream; + +public class NullSafeCollectionStreamsUsingJava8OptionalContainer { + + /** + * This method shows how to make a null safe stream from a collection through the use of + * Java SE 8’s Optional Container + * + * @param collection The collection that is to be converted into a stream + * @return The stream that has been created from the collection or an empty stream if the collection is null + */ + public Stream collectionAsStream(Collection collection) { + return Optional.ofNullable(collection) + .map(Collection::stream) + .orElseGet(Stream::empty); + } +} \ No newline at end of file diff --git a/core-java-collections/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java b/core-java-collections/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java new file mode 100644 index 0000000000..0c10f1cebc --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java @@ -0,0 +1,19 @@ +package com.baeldung.nullsafecollectionstreams; + +import java.util.Collection; +import java.util.stream.Stream; + +public class NullSafeCollectionStreamsUsingNullDereferenceCheck { + + /** + * This method shows how to make a null safe stream from a collection through the use of a check + * to prevent null dereferences + * + * @param collection The collection that is to be converted into a stream + * @return The stream that has been created from the collection or an empty stream if the collection is null + */ + public Stream collectionAsStream(Collection collection) { + return collection == null ? Stream.empty() : collection.stream(); + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/performance/ArrayListBenchmark.java b/core-java-collections/src/main/java/com/baeldung/performance/ArrayListBenchmark.java new file mode 100644 index 0000000000..dddd85007d --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/performance/ArrayListBenchmark.java @@ -0,0 +1,77 @@ +package com.baeldung.performance; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.*; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@Warmup(iterations = 10) +public class ArrayListBenchmark { + + @State(Scope.Thread) + public static class MyState { + + List employeeList = new ArrayList<>(); + //LinkedList employeeList = new LinkedList<>(); + + long iterations = 100000; + + Employee employee = new Employee(100L, "Harry"); + + int employeeIndex = -1; + + @Setup(Level.Trial) + public void setUp() { + for (long i = 0; i < iterations; i++) { + employeeList.add(new Employee(i, "John")); + } + + employeeList.add(employee); + employeeIndex = employeeList.indexOf(employee); + } + } + + @Benchmark + public void testAddAt(ArrayListBenchmark.MyState state) { + state.employeeList.add((int) (state.iterations), new Employee(state.iterations, "John")); + } + + @Benchmark + public boolean testContains(ArrayListBenchmark.MyState state) { + return state.employeeList.contains(state.employee); + } + + @Benchmark + public int testIndexOf(ArrayListBenchmark.MyState state) { + return state.employeeList.indexOf(state.employee); + } + + @Benchmark + public Employee testGet(ArrayListBenchmark.MyState state) { + return state.employeeList.get(state.employeeIndex); + } + + @Benchmark + public boolean testRemove(ArrayListBenchmark.MyState state) { + return state.employeeList.remove(state.employee); + } + +// @Benchmark +// public void testAdd(ArrayListBenchmark.MyState state) { +// state.employeeList.add(new Employee(state.iterations + 1, "John")); +// } + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(ArrayListBenchmark.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java b/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java new file mode 100644 index 0000000000..921e1608ea --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java @@ -0,0 +1,59 @@ +package com.baeldung.performance; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Warmup(iterations = 5) +public class CollectionsBenchmark { + + @State(Scope.Thread) + public static class MyState { + private Set employeeSet = new HashSet<>(); + private List employeeList = new ArrayList<>(); + + private long iterations = 10000; + + private Employee employee = new Employee(100L, "Harry"); + + @Setup(Level.Trial) + public void setUp() { + + for (long i = 0; i < iterations; i++) { + employeeSet.add(new Employee(i, "John")); + employeeList.add(new Employee(i, "John")); + } + + employeeList.add(employee); + employeeSet.add(employee); + } + } + + @Benchmark + public boolean testArrayList(MyState state) { + return state.employeeList.contains(state.employee); + } + + @Benchmark + public boolean testHashSet(MyState state) { + return state.employeeSet.contains(state.employee); + } + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(CollectionsBenchmark.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/performance/CopyOnWriteBenchmark.java b/core-java-collections/src/main/java/com/baeldung/performance/CopyOnWriteBenchmark.java new file mode 100644 index 0000000000..30c50291dd --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/performance/CopyOnWriteBenchmark.java @@ -0,0 +1,78 @@ +package com.baeldung.performance; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@Warmup(iterations = 10) +public class CopyOnWriteBenchmark { + + @State(Scope.Thread) + public static class MyState { + + CopyOnWriteArrayList employeeList = new CopyOnWriteArrayList<>(); + + long iterations = 100000; + + Employee employee = new Employee(100L, "Harry"); + + int employeeIndex = -1; + + @Setup(Level.Trial) + public void setUp() { + for (long i = 0; i < iterations; i++) { + employeeList.add(new Employee(i, "John")); + } + + employeeList.add(employee); + + employeeIndex = employeeList.indexOf(employee); + } + } + + @Benchmark + public void testAdd(CopyOnWriteBenchmark.MyState state) { + state.employeeList.add(new Employee(state.iterations + 1, "John")); + } + + @Benchmark + public void testAddAt(CopyOnWriteBenchmark.MyState state) { + state.employeeList.add((int) (state.iterations), new Employee(state.iterations, "John")); + } + + @Benchmark + public boolean testContains(CopyOnWriteBenchmark.MyState state) { + return state.employeeList.contains(state.employee); + } + + @Benchmark + public int testIndexOf(CopyOnWriteBenchmark.MyState state) { + return state.employeeList.indexOf(state.employee); + } + + @Benchmark + public Employee testGet(CopyOnWriteBenchmark.MyState state) { + return state.employeeList.get(state.employeeIndex); + } + + @Benchmark + public boolean testRemove(CopyOnWriteBenchmark.MyState state) { + return state.employeeList.remove(state.employee); + } + + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(CopyOnWriteBenchmark.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/performance/Employee.java b/core-java-collections/src/main/java/com/baeldung/performance/Employee.java new file mode 100644 index 0000000000..d811cfbb7d --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/performance/Employee.java @@ -0,0 +1,47 @@ +package com.baeldung.performance; + +public class Employee { + + private Long id; + private String name; + + public Employee(Long id, String name) { + this.name = name; + this.id = id; + } + + 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; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Employee employee = (Employee) o; + + if (!id.equals(employee.id)) return false; + return name.equals(employee.name); + + } + + @Override + public int hashCode() { + int result = id.hashCode(); + result = 31 * result + name.hashCode(); + return result; + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/performance/HashMapBenchmark.java b/core-java-collections/src/main/java/com/baeldung/performance/HashMapBenchmark.java new file mode 100644 index 0000000000..085daaceb7 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/performance/HashMapBenchmark.java @@ -0,0 +1,73 @@ +package com.baeldung.performance; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.*; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@Warmup(iterations = 10) +public class HashMapBenchmark { + + @State(Scope.Thread) + public static class MyState { + + Map employeeMap = new HashMap<>(); + //LinkedHashMap employeeMap = new LinkedHashMap<>(); + //IdentityHashMap employeeMap = new IdentityHashMap<>(); + //WeakHashMap employeeMap = new WeakHashMap<>(); + //ConcurrentHashMap employeeMap = new ConcurrentHashMap<>(); + //ConcurrentSkipListMap employeeMap = new ConcurrentSkipListMap <>(); + + // TreeMap + + long iterations = 100000; + + Employee employee = new Employee(100L, "Harry"); + + int employeeIndex = -1; + + @Setup(Level.Trial) + public void setUp() { + for (long i = 0; i < iterations; i++) { + employeeMap.put(i, new Employee(i, "John")); + } + + //employeeMap.put(iterations, employee); + } + } + + @Benchmark + public Employee testGet(HashMapBenchmark.MyState state) { + return state.employeeMap.get(state.iterations); + } + + @Benchmark + public Employee testRemove(HashMapBenchmark.MyState state) { + return state.employeeMap.remove(state.iterations); + } + + @Benchmark + public Employee testPut(HashMapBenchmark.MyState state) { + return state.employeeMap.put(state.employee.getId(), state.employee); + } + + @Benchmark + public Boolean testContainsKey(HashMapBenchmark.MyState state) { + return state.employeeMap.containsKey(state.employee.getId()); + } + + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(HashMapBenchmark.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/performance/SetBenchMark.java b/core-java-collections/src/main/java/com/baeldung/performance/SetBenchMark.java new file mode 100644 index 0000000000..f70bab4fcf --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/performance/SetBenchMark.java @@ -0,0 +1,66 @@ +package com.baeldung.performance; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentSkipListSet; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@Warmup(iterations = 10) +public class SetBenchMark { + + @State(Scope.Thread) + public static class MyState { + + //Set employeeSet = new HashSet<>(); + LinkedHashSet employeeSet = new LinkedHashSet<>(); + //ConcurrentSkipListSet employeeSet = new ConcurrentSkipListSet <>(); + + // TreeSet  + + long iterations = 1000; + Employee employee = new Employee(100L, "Harry"); + + @Setup(Level.Trial) + public void setUp() { + for (long i = 0; i < iterations; i++) { + employeeSet.add(new Employee(i, "John")); + } + + //employeeSet.add(employee); + } + } + + @Benchmark + public boolean testAdd(SetBenchMark.MyState state) { + return state.employeeSet.add(state.employee); + } + + @Benchmark + public Boolean testContains(SetBenchMark.MyState state) { + return state.employeeSet.contains(state.employee); + } + + @Benchmark + public boolean testRemove(SetBenchMark.MyState state) { + return state.employeeSet.remove(state.employee); + } + + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(SetBenchMark.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/thread_safe_lifo/DequeBasedSynchronizedStack.java b/core-java-collections/src/main/java/com/baeldung/thread_safe_lifo/DequeBasedSynchronizedStack.java new file mode 100644 index 0000000000..ea1618b0f2 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/thread_safe_lifo/DequeBasedSynchronizedStack.java @@ -0,0 +1,36 @@ +package com.baeldung.thread_safe_lifo; + +import java.util.ArrayDeque; + +/** + * Deque Based Stack implementation. + */ +public class DequeBasedSynchronizedStack { + + // Internal Deque which gets decorated for synchronization. + private ArrayDeque dequeStore = new ArrayDeque<>(); + + public DequeBasedSynchronizedStack(int initialCapacity) { + this.dequeStore = new ArrayDeque<>(initialCapacity); + } + + public DequeBasedSynchronizedStack() { + + } + + public synchronized T pop() { + return this.dequeStore.pop(); + } + + public synchronized void push(T element) { + this.dequeStore.push(element); + } + + public synchronized T peek() { + return this.dequeStore.peek(); + } + + public synchronized int size() { + return this.dequeStore.size(); + } +} diff --git a/core-java-collections/src/main/resources/logback.xml b/core-java-collections/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/core-java-collections/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/core-java-collections/src/test/java/com/baeldung/array/converter/ArrayConvertToListTest.java b/core-java-collections/src/test/java/com/baeldung/array/converter/ArrayConvertToListTest.java deleted file mode 100644 index a5db46a9b6..0000000000 --- a/core-java-collections/src/test/java/com/baeldung/array/converter/ArrayConvertToListTest.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.baeldung.array.converter; - -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.*; - -public class ArrayConvertToListTest { - - @Test - public void givenAnStringArray_whenConvertArrayToList_thenListCreated() { - String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" }; - List flowerList = Arrays.asList(flowers); - - assertNotNull(flowerList); - assertEquals(flowerList.size(), 4); - assertEquals(flowerList.get(0), "Ageratum"); - assertEquals(flowerList.get(1), "Allium"); - assertEquals(flowerList.get(2), "Poppy"); - assertEquals(flowerList.get(3), "Catmint"); - } - - @Test - public void givenAnIntArray_whenConvertArrayToList_thenListWithOneElementCreated() { - int[] primitives = { 1, 2, 3, 4 }; - List numbers = Arrays.asList(primitives); - - assertNotNull(numbers); - assertEquals(numbers.size(), 1); - assertEquals(numbers.get(0), primitives); - } - - @Test(expected = UnsupportedOperationException.class) - public void givenAnStringArray_whenConvertArrayToListAndAddAnElement_thenThrowUnsupportedOperationException() { - String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" }; - List flowerList = Arrays.asList(flowers); - - assertNotNull(flowerList); - assertEquals(flowerList.size(), 4); - assertEquals(flowerList.get(0), "Ageratum"); - assertEquals(flowerList.get(1), "Allium"); - assertEquals(flowerList.get(2), "Poppy"); - assertEquals(flowerList.get(3), "Catmint"); - - flowerList.add("Celosia"); - } - - @Test(expected = UnsupportedOperationException.class) - public void givenAnStringArray_whenConvertArrayToListAndRemoveAnElement_thenThrowUnsupportedOperationException() { - String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" }; - List flowerList = Arrays.asList(flowers); - - assertNotNull(flowerList); - assertEquals(flowerList.size(), 4); - assertEquals(flowerList.get(0), "Ageratum"); - assertEquals(flowerList.get(1), "Allium"); - assertEquals(flowerList.get(2), "Poppy"); - assertEquals(flowerList.get(3), "Catmint"); - - flowerList.remove("Poppy"); - } - - @Test - public void givenAnStringArray_whenCreateListFromArrayAndAddAnElement_thenListOk() { - String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" }; - List flowerList = Arrays.asList(flowers); - - assertNotNull(flowerList); - assertEquals(flowerList.size(), 4); - - assertEquals(flowerList.get(0), "Ageratum"); - assertEquals(flowerList.get(1), "Allium"); - assertEquals(flowerList.get(2), "Poppy"); - assertEquals(flowerList.get(3), "Catmint"); - - List newflowerList = new ArrayList<>(flowerList); - - assertNotNull(newflowerList); - assertEquals(newflowerList.size(), 4); - assertEquals(newflowerList.get(0), "Ageratum"); - assertEquals(newflowerList.get(1), "Allium"); - assertEquals(newflowerList.get(2), "Poppy"); - assertEquals(newflowerList.get(3), "Catmint"); - - newflowerList.add("Celosia"); - - assertEquals(newflowerList.size(), 5); - assertEquals(newflowerList.get(4), "Celosia"); - } - - @Test - public void givenAnStringArray_whenIterateArrayAndAddTheElementsToNewListAndAddAnElement_thenListOk() { - String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" }; - - List flowerList = new ArrayList<>(); - for(String flower: flowers) { - flowerList.add(flower); - } - - assertNotNull(flowerList); - assertEquals(flowerList.size(), 4); - - assertEquals(flowerList.get(0), "Ageratum"); - assertEquals(flowerList.get(1), "Allium"); - assertEquals(flowerList.get(2), "Poppy"); - assertEquals(flowerList.get(3), "Catmint"); - - flowerList.add("Celosia"); - - assertEquals(flowerList.size(), 5); - assertEquals(flowerList.get(4), "Celosia"); - } -} diff --git a/core-java-collections/src/test/java/com/baeldung/array/converter/ArrayConvertToListUnitTest.java b/core-java-collections/src/test/java/com/baeldung/array/converter/ArrayConvertToListUnitTest.java new file mode 100644 index 0000000000..cf8710d8a4 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/array/converter/ArrayConvertToListUnitTest.java @@ -0,0 +1,116 @@ +package com.baeldung.array.converter; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.*; + +public class ArrayConvertToListUnitTest { + + @Test + public void givenAnStringArray_whenConvertArrayToList_thenListCreated() { + String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" }; + List flowerList = Arrays.asList(flowers); + + assertNotNull(flowerList); + assertEquals(flowerList.size(), 4); + assertEquals(flowerList.get(0), "Ageratum"); + assertEquals(flowerList.get(1), "Allium"); + assertEquals(flowerList.get(2), "Poppy"); + assertEquals(flowerList.get(3), "Catmint"); + } + + @Test + public void givenAnIntArray_whenConvertArrayToList_thenListWithOneElementCreated() { + int[] primitives = { 1, 2, 3, 4 }; + List numbers = Arrays.asList(primitives); + + assertNotNull(numbers); + assertEquals(numbers.size(), 1); + assertEquals(numbers.get(0), primitives); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenAnStringArray_whenConvertArrayToListAndAddAnElement_thenThrowUnsupportedOperationException() { + String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" }; + List flowerList = Arrays.asList(flowers); + + assertNotNull(flowerList); + assertEquals(flowerList.size(), 4); + assertEquals(flowerList.get(0), "Ageratum"); + assertEquals(flowerList.get(1), "Allium"); + assertEquals(flowerList.get(2), "Poppy"); + assertEquals(flowerList.get(3), "Catmint"); + + flowerList.add("Celosia"); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenAnStringArray_whenConvertArrayToListAndRemoveAnElement_thenThrowUnsupportedOperationException() { + String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" }; + List flowerList = Arrays.asList(flowers); + + assertNotNull(flowerList); + assertEquals(flowerList.size(), 4); + assertEquals(flowerList.get(0), "Ageratum"); + assertEquals(flowerList.get(1), "Allium"); + assertEquals(flowerList.get(2), "Poppy"); + assertEquals(flowerList.get(3), "Catmint"); + + flowerList.remove("Poppy"); + } + + @Test + public void givenAnStringArray_whenCreateListFromArrayAndAddAnElement_thenListOk() { + String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" }; + List flowerList = Arrays.asList(flowers); + + assertNotNull(flowerList); + assertEquals(flowerList.size(), 4); + + assertEquals(flowerList.get(0), "Ageratum"); + assertEquals(flowerList.get(1), "Allium"); + assertEquals(flowerList.get(2), "Poppy"); + assertEquals(flowerList.get(3), "Catmint"); + + List newflowerList = new ArrayList<>(flowerList); + + assertNotNull(newflowerList); + assertEquals(newflowerList.size(), 4); + assertEquals(newflowerList.get(0), "Ageratum"); + assertEquals(newflowerList.get(1), "Allium"); + assertEquals(newflowerList.get(2), "Poppy"); + assertEquals(newflowerList.get(3), "Catmint"); + + newflowerList.add("Celosia"); + + assertEquals(newflowerList.size(), 5); + assertEquals(newflowerList.get(4), "Celosia"); + } + + @Test + public void givenAnStringArray_whenIterateArrayAndAddTheElementsToNewListAndAddAnElement_thenListOk() { + String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" }; + + List flowerList = new ArrayList<>(); + for(String flower: flowers) { + flowerList.add(flower); + } + + assertNotNull(flowerList); + assertEquals(flowerList.size(), 4); + + assertEquals(flowerList.get(0), "Ageratum"); + assertEquals(flowerList.get(1), "Allium"); + assertEquals(flowerList.get(2), "Poppy"); + assertEquals(flowerList.get(3), "Catmint"); + + flowerList.add("Celosia"); + + assertEquals(flowerList.size(), 5); + assertEquals(flowerList.get(4), "Celosia"); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/arraydeque/ArrayDequeTest.java b/core-java-collections/src/test/java/com/baeldung/arraydeque/ArrayDequeTest.java deleted file mode 100644 index 50813a8601..0000000000 --- a/core-java-collections/src/test/java/com/baeldung/arraydeque/ArrayDequeTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.arraydeque; - -import java.util.ArrayDeque; -import java.util.Deque; - -import static org.junit.Assert.*; -import org.junit.Test; - -public class ArrayDequeTest { - - @Test - public void whenOffer_addsAtLast() { - final Deque deque = new ArrayDeque<>(); - - deque.offer("first"); - deque.offer("second"); - - assertEquals("second", deque.getLast()); - } - - @Test - public void whenPoll_removesFirst() { - final Deque deque = new ArrayDeque<>(); - - deque.offer("first"); - deque.offer("second"); - - assertEquals("first", deque.poll()); - } - - @Test - public void whenPush_addsAtFirst() { - final Deque deque = new ArrayDeque<>(); - - deque.push("first"); - deque.push("second"); - - assertEquals("second", deque.getFirst()); - } - - @Test - public void whenPop_removesLast() { - final Deque deque = new ArrayDeque<>(); - - deque.push("first"); - deque.push("second"); - - assertEquals("second", deque.pop()); - } -} diff --git a/core-java-collections/src/test/java/com/baeldung/arraydeque/ArrayDequeUnitTest.java b/core-java-collections/src/test/java/com/baeldung/arraydeque/ArrayDequeUnitTest.java new file mode 100644 index 0000000000..71930eda97 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/arraydeque/ArrayDequeUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.arraydeque; + +import java.util.ArrayDeque; +import java.util.Deque; + +import static org.junit.Assert.*; +import org.junit.Test; + +public class ArrayDequeUnitTest { + + @Test + public void whenOffer_addsAtLast() { + final Deque deque = new ArrayDeque<>(); + + deque.offer("first"); + deque.offer("second"); + + assertEquals("second", deque.getLast()); + } + + @Test + public void whenPoll_removesFirst() { + final Deque deque = new ArrayDeque<>(); + + deque.offer("first"); + deque.offer("second"); + + assertEquals("first", deque.poll()); + } + + @Test + public void whenPush_addsAtFirst() { + final Deque deque = new ArrayDeque<>(); + + deque.push("first"); + deque.push("second"); + + assertEquals("second", deque.getFirst()); + } + + @Test + public void whenPop_removesLast() { + final Deque deque = new ArrayDeque<>(); + + deque.push("first"); + deque.push("second"); + + assertEquals("second", deque.pop()); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/collection/CollectionsEmpty.java b/core-java-collections/src/test/java/com/baeldung/collection/CollectionsEmpty.java new file mode 100644 index 0000000000..86a262107d --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/collection/CollectionsEmpty.java @@ -0,0 +1,26 @@ +package com.baeldung.collection; + +import java.util.List; +import java.util.ArrayList; +import java.util.Collections; +import org.junit.Assert; +import org.junit.Test; + +public class CollectionsEmpty { + + @Test + public void givenArrayList_whenAddingElement_addsNewElement() { + ArrayList mutableList = new ArrayList<>(); + mutableList.add("test"); + + Assert.assertEquals(mutableList.size(), 1); + Assert.assertEquals(mutableList.get(0), "test"); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenCollectionsEmptyList_whenAddingElement_throwsUnsupportedOperationException() { + List immutableList = Collections.emptyList(); + immutableList.add("test"); + } + +} \ No newline at end of file diff --git a/core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java b/core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java new file mode 100644 index 0000000000..9f002c89a2 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java @@ -0,0 +1,80 @@ +package com.baeldung.collection; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class StreamOperateAndRemoveUnitTest { + + private List itemList; + + @Before + public void setup() { + + itemList = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + itemList.add(new Item(i)); + } + } + + @Test + public void givenAListOf10Items_whenFilteredForQualifiedItems_thenFilteredListContains5Items() { + + final List filteredList = itemList.stream().filter(item -> item.isQualified()) + .collect(Collectors.toList()); + + Assert.assertEquals(5, filteredList.size()); + } + + @Test + public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveIf_thenListContains5Items() { + + final Predicate isQualified = item -> item.isQualified(); + itemList.stream().filter(isQualified).forEach(item -> item.operate()); + itemList.removeIf(isQualified); + + Assert.assertEquals(5, itemList.size()); + } + + @Test + public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveAll_thenListContains5Items() { + + final List operatedList = new ArrayList<>(); + itemList.stream().filter(item -> item.isQualified()).forEach(item -> { + item.operate(); + operatedList.add(item); + }); + itemList.removeAll(operatedList); + + Assert.assertEquals(5, itemList.size()); + } + + class Item { + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + private final int value; + + public Item(final int value) { + + this.value = value; + } + + public boolean isQualified() { + + return value % 2 == 0; + } + + public void operate() { + + logger.info("Even Number: " + this.value); + } + } +} \ No newline at end of file diff --git a/core-java-collections/src/test/java/com/baeldung/convertlisttomap/ConvertListToMapServiceUnitTest.java b/core-java-collections/src/test/java/com/baeldung/convertlisttomap/ConvertListToMapServiceUnitTest.java new file mode 100644 index 0000000000..4d783f4525 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/convertlisttomap/ConvertListToMapServiceUnitTest.java @@ -0,0 +1,68 @@ +package com.baeldung.convertlisttomap; + +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; + +public class ConvertListToMapServiceUnitTest { + List list; + + private ConvertListToMapService convertListService; + + @Before + public void init() { + this.convertListService = new ConvertListToMapService(); + this.list = new ArrayList<>(); + + Animal cat = new Animal(1, "Cat"); + list.add(cat); + Animal dog = new Animal(2, "Dog"); + list.add(dog); + Animal pig = new Animal(3, "Pig"); + list.add(pig); + Animal cow = new Animal(4, "Cow"); + list.add(cow); + Animal goat = new Animal(5, "Goat"); + list.add(goat); + + } + + @Test + public void givenAList_whenConvertBeforeJava8_thenReturnMapWithTheSameElements() { + + Map map = convertListService.convertListBeforeJava8(list); + + assertThat(map.values(), containsInAnyOrder(list.toArray())); + } + + @Test + public void givenAList_whenConvertAfterJava8_thenReturnMapWithTheSameElements() { + + Map map = convertListService.convertListAfterJava8(list); + + assertThat(map.values(), containsInAnyOrder(list.toArray())); + } + + @Test + public void givenAList_whenConvertWithGuava_thenReturnMapWithTheSameElements() { + + Map map = convertListService.convertListWithGuava(list); + + assertThat(map.values(), containsInAnyOrder(list.toArray())); + } + + @Test + public void givenAList_whenConvertWithApacheCommons_thenReturnMapWithTheSameElements() { + + Map map = convertListService.convertListWithApacheCommons(list); + + assertThat(map.values(), containsInAnyOrder(list.toArray())); + } + +} diff --git a/core-java-collections/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDiplicatedIdToMapServiceUnitTest.java b/core-java-collections/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDiplicatedIdToMapServiceUnitTest.java new file mode 100644 index 0000000000..6e766433d1 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDiplicatedIdToMapServiceUnitTest.java @@ -0,0 +1,68 @@ +package com.baeldung.convertlisttomap; + +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasSize; + +public class ConvertListWithDiplicatedIdToMapServiceUnitTest { + List duplicatedIdList; + + private ConvertListToMapService convertListService = new ConvertListToMapService(); + + @Before + public void init() { + + this.duplicatedIdList = new ArrayList<>(); + + Animal cat = new Animal(1, "Cat"); + duplicatedIdList.add(cat); + Animal dog = new Animal(2, "Dog"); + duplicatedIdList.add(dog); + Animal pig = new Animal(3, "Pig"); + duplicatedIdList.add(pig); + Animal cow = new Animal(4, "Cow"); + duplicatedIdList.add(cow); + Animal goat = new Animal(4, "Goat"); + duplicatedIdList.add(goat); + + } + + @Test + public void givenADupIdList_whenConvertBeforeJava8_thenReturnMapWithRewrittenElement() { + + Map map = convertListService.convertListBeforeJava8(duplicatedIdList); + + assertThat(map.values(), hasSize(4)); + assertThat(map.values(), hasItem(duplicatedIdList.get(4))); + } + + @Test + public void givenADupIdList_whenConvertWithApacheCommons_thenReturnMapWithRewrittenElement() { + + Map map = convertListService.convertListWithApacheCommons(duplicatedIdList); + + assertThat(map.values(), hasSize(4)); + assertThat(map.values(), hasItem(duplicatedIdList.get(4))); + } + + @Test(expected = IllegalStateException.class) + public void givenADupIdList_whenConvertAfterJava8_thenException() { + + convertListService.convertListAfterJava8(duplicatedIdList); + } + + @Test(expected = IllegalArgumentException.class) + public void givenADupIdList_whenConvertWithGuava_thenException() { + + convertListService.convertListWithGuava(duplicatedIdList); + + } + +} diff --git a/core-java-collections/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java b/core-java-collections/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java new file mode 100644 index 0000000000..3c96cf1392 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java @@ -0,0 +1,158 @@ +package com.baeldung.findanelement; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +public class FindACustomerInGivenListUnitTest { + + private static List customers = new ArrayList<>(); + + static { + customers.add(new Customer(1, "Jack")); + customers.add(new Customer(2, "James")); + customers.add(new Customer(3, "Sam")); + } + + private static FindACustomerInGivenList findACustomerInGivenList = new FindACustomerInGivenList(); + + @Test + public void givenAnIndex_whenFoundUsingGivenIndex_thenReturnCustomer() { + Customer customer = findACustomerInGivenList.findUsingGivenIndex(0, customers); + + assertEquals(1, customer.getId()); + } + + @Test + public void givenAnIndex_whenNotFoundUsingGivenIndex_thenReturnNull() { + Customer customer = findACustomerInGivenList.findUsingGivenIndex(5, customers); + + assertNull(customer); + } + + @Test + public void givenACustomer_whenFoundUsingContains_thenReturnTrue() { + Customer james = new Customer(2, "James"); + boolean isJamesPresent = findACustomerInGivenList.findUsingContains(james, customers); + + assertEquals(true, isJamesPresent); + } + + @Test + public void givenACustomer_whenNotFoundUsingContains_thenReturnFalse() { + Customer john = new Customer(5, "John"); + boolean isJohnPresent = findACustomerInGivenList.findUsingContains(john, customers); + + assertEquals(false, isJohnPresent); + } + + @Test + public void givenACustomer_whenFoundUsingIndexOf_thenReturnItsIndex() { + Customer james = new Customer(2, "James"); + int indexOfJames = findACustomerInGivenList.findUsingIndexOf(james, customers); + + assertEquals(1, indexOfJames); + } + + @Test + public void givenACustomer_whenNotFoundUsingIndexOf_thenReturnMinus1() { + Customer john = new Customer(5, "John"); + int indexOfJohn = findACustomerInGivenList.findUsingIndexOf(john, customers); + + assertEquals(-1, indexOfJohn); + } + + @Test + public void givenName_whenCustomerWithNameFoundUsingIterator_thenReturnCustomer() { + Customer james = findACustomerInGivenList.findUsingIterator("James", customers); + + assertEquals("James", james.getName()); + assertEquals(2, james.getId()); + } + + @Test + public void givenName_whenCustomerWithNameNotFoundUsingIterator_thenReturnNull() { + Customer john = findACustomerInGivenList.findUsingIterator("John", customers); + + assertNull(john); + } + + @Test + public void givenName_whenCustomerWithNameFoundUsingEnhancedFor_thenReturnCustomer() { + Customer james = findACustomerInGivenList.findUsingEnhancedForLoop("James", customers); + + assertEquals("James", james.getName()); + assertEquals(2, james.getId()); + } + + @Test + public void givenName_whenCustomerWithNameNotFoundUsingEnhancedFor_thenReturnNull() { + Customer john = findACustomerInGivenList.findUsingEnhancedForLoop("John", customers); + + assertNull(john); + } + + @Test + public void givenName_whenCustomerWithNameFoundUsingStream_thenReturnCustomer() { + Customer james = findACustomerInGivenList.findUsingStream("James", customers); + + assertEquals("James", james.getName()); + assertEquals(2, james.getId()); + } + + @Test + public void givenName_whenCustomerWithNameNotFoundUsingStream_thenReturnNull() { + Customer john = findACustomerInGivenList.findUsingStream("John", customers); + + assertNull(john); + } + + @Test + public void givenName_whenCustomerWithNameFoundUsingParallelStream_thenReturnCustomer() { + Customer james = findACustomerInGivenList.findUsingParallelStream("James", customers); + + assertEquals("James", james.getName()); + assertEquals(2, james.getId()); + } + + @Test + public void givenName_whenCustomerWithNameNotFoundUsingParallelStream_thenReturnNull() { + Customer john = findACustomerInGivenList.findUsingParallelStream("John", customers); + + assertNull(john); + } + + @Test + public void givenName_whenCustomerWithNameFoundUsingApacheCommon_thenReturnCustomer() { + Customer james = findACustomerInGivenList.findUsingApacheCommon("James", customers); + + assertEquals("James", james.getName()); + assertEquals(2, james.getId()); + } + + @Test + public void givenName_whenCustomerWithNameNotFoundUsingApacheCommon_thenReturnNull() { + Customer john = findACustomerInGivenList.findUsingApacheCommon("John", customers); + + assertNull(john); + } + + @Test + public void givenName_whenCustomerWithNameFoundUsingGuava_thenReturnCustomer() { + Customer james = findACustomerInGivenList.findUsingGuava("James", customers); + + assertEquals("James", james.getName()); + assertEquals(2, james.getId()); + } + + @Test + public void givenName_whenCustomerWithNameNotFoundUsingGuava_thenReturnNull() { + Customer john = findACustomerInGivenList.findUsingGuava("John", customers); + + assertNull(john); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java b/core-java-collections/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java similarity index 99% rename from core-java-8/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java index e8c42c94e1..8d30596ab4 100644 --- a/core-java-8/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java +++ b/core-java-collections/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java @@ -233,7 +233,7 @@ public class HashtableUnitTest { Hashtable table = new Hashtable(); String[] animals = { "cat", "dog", "dog", "cat", "bird", "mouse", "mouse" }; for (String animal : animals) { - table.compute(animal, (key, value) -> (value == null ? Integer.valueOf(1) : Integer.valueOf(value) + 1)); + table.compute(animal, (key, value) -> (value == null ? 1 : value + 1)); } assertThat(table.values(), hasItems(2, 2, 2, 1)); @@ -271,4 +271,4 @@ public class HashtableUnitTest { assertThat(table.values(), hasItems("cat - a small domesticated carnivorous mammal", "dog - another animal")); } -} +} \ No newline at end of file diff --git a/core-java-collections/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java b/core-java-collections/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java new file mode 100644 index 0000000000..36e1f4a83c --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.iterators; + +import static com.baeldung.iterators.Iterators.failFast1; +import static com.baeldung.iterators.Iterators.failFast2; +import static com.baeldung.iterators.Iterators.failSafe1; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ConcurrentModificationException; + +import org.junit.Test; + +/** + * Source code https://github.com/eugenp/tutorials + * + * @author Santosh Thakur + */ + +public class IteratorsUnitTest { + + @Test + public void whenFailFast_ThenThrowsException() { + assertThatThrownBy(() -> { + failFast1(); + }).isInstanceOf(ConcurrentModificationException.class); + } + + @Test + public void whenFailFast_ThenThrowsExceptionInSecondIteration() { + assertThatThrownBy(() -> { + failFast2(); + }).isInstanceOf(ConcurrentModificationException.class); + } + + @Test + public void whenFailSafe_ThenDoesNotThrowException() { + assertThat(failSafe1()).isGreaterThanOrEqualTo(0); + } + +} diff --git a/core-java-collections/src/test/java/com/baeldung/java/filtering/CollectionFiltersUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/filtering/CollectionFiltersUnitTest.java new file mode 100644 index 0000000000..b30805d471 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/java/filtering/CollectionFiltersUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.java.filtering; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +public class CollectionFiltersUnitTest { + + private static final Collection BASE_INTEGER_COLLECTION = Arrays.asList(9, 14, 2, 7, 1, 5, 8); + private static final Collection EXPECTED_EVEN_FILTERED_COLLECTION = Arrays.asList(14, 2, 8); + + @Test + public void givenAStringCollection_whenFilteringFourLetterWords_thenObtainTheFilteredCollection() { + final Collection baseStrings = Arrays.asList("java", "baeldung", "type", "example", "other"); + + Collection filtered = StreamsCollectionFilter.filterCollectionHelperMethod(baseStrings, item -> item.length() == 4); + + assertThat(filtered).containsExactlyInAnyOrder("java", "type"); + } + + @Test + public void givenAnIntegerCollection_whenFilteringEvenValues_thenObtainTheFilteredCollectionForAllCases() { + Collection filteredWithStreams1 = StreamsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION); + Collection filteredWithCollectionUtils = CollectionUtilsCollectionFilter.findEvenNumbers(new ArrayList<>(BASE_INTEGER_COLLECTION)); + Collection filteredWithEclipseCollections = EclipseCollectionsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION); + Collection filteredWithEclipseCollectionsUsingIterate = EclipseCollectionsCollectionFilter.findEvenNumbersUsingIterate(BASE_INTEGER_COLLECTION); + Collection filteredWithGuava = GuavaCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION); + + assertThat(filteredWithStreams1).hasSameElementsAs(filteredWithCollectionUtils) + .hasSameElementsAs(filteredWithEclipseCollections) + .hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate) + .hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate) + .hasSameElementsAs(filteredWithGuava) + .hasSameElementsAs(EXPECTED_EVEN_FILTERED_COLLECTION); + } + +} diff --git a/core-java-collections/src/test/java/com/baeldung/java/iterable/IterableSizeUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/iterable/IterableSizeUnitTest.java new file mode 100644 index 0000000000..4bc413dee0 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/java/iterable/IterableSizeUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.java.iterable; + +import static org.junit.Assert.assertEquals; + +import java.sql.SQLException; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.google.common.collect.Lists; + +class IterableSizeUnitTest { + + private final List list = Lists.newArrayList("Apple", "Orange", "Banana"); + + private Iterable data; + + @Test + void whenUsingJava7_iterableOfCollectionType_thenCorrectSize() { + + final int size = IterableSize.sizeUsingJava7(list); + + assertEquals(3, size); + } + + @Test + void whenUsingJava7_iterableNotOfCollectionType_thenCorrect() { + + final SQLException exception = new SQLException(); + exception.setNextException(new SQLException()); + final int size = IterableSize.sizeUsingJava7(exception); + + assertEquals(2, size); + } + + @Test + void whenUsingJava8_thenCorrect() { + + final long size = IterableSize.sizeUsingJava8(list); + + assertEquals(3, size); + } + + @Test + void whenUsingApacheCollections_thenCorrect() { + + final int size = IterableSize.sizeUsingApacheCollections(list); + + assertEquals(3, size); + } + + @Test + void whenUsingGoogleGuava_thenCorrect() { + + final int size = IterableSize.sizeUsingGoogleGuava(list); + + assertEquals(3, size); + } +} \ No newline at end of file diff --git a/core-java-collections/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java new file mode 100644 index 0000000000..bc1611038c --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java @@ -0,0 +1,133 @@ +package com.baeldung.java.list; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class CopyListServiceUnitTest { + + List flowers; + + private CopyListService copyListService; + + @Before + public void init() { + this.copyListService = new CopyListService(); + this.flowers = new ArrayList<>(); + + Flower poppy = new Flower("Poppy", 12); + flowers.add(poppy); + Flower anemone = new Flower("Anemone", 8); + flowers.add(anemone); + Flower catmint = new Flower("Catmint", 12); + flowers.add(catmint); + Flower diascia = new Flower("Diascia", 5); + flowers.add(diascia); + Flower iris = new Flower("Iris", 3); + flowers.add(iris); + Flower pansy = new Flower("Pansy", 5); + flowers.add(pansy); + } + + @Test + public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithTheSameElementsByConstructor() { + List copy = copyListService.copyListByConstructor(flowers); + assertEquals(copy.size(), flowers.size()); + assertTrue(copy.containsAll(flowers)); + } + + @Test + public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneModifiedElementByConstructor() { + List copy = copyListService.copyListByConstructorAndEditOneFlowerInTheNewList(flowers); + assertEquals(copy.size(), flowers.size()); + assertTrue(copy.containsAll(flowers)); + } + + @Test + public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithTheSameElementsByAddAllmethod() { + List copy = copyListService.copyListByAddAllMethod(flowers); + assertEquals(copy.size(), flowers.size()); + assertTrue(copy.containsAll(flowers)); + } + + @Test + public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneModifiedElementByAddAllmethod() { + List copy = copyListService.copyListByAddAllMethodAndEditOneFlowerInTheNewList(flowers); + assertEquals(copy.size(), flowers.size()); + assertTrue(copy.containsAll(flowers)); + } + + @Test + public void givenAList_whenListsHaveSameSize_thenReturnAnotherListWithTheSameElementsByCopyMethod() { + List source = Arrays.asList(1,2,3); + List dest = Arrays.asList(4,5,6); + + dest = copyListService.copyListByCopyMethod(source, dest); + assertEquals(dest.size(), source.size()); + assertTrue(dest.containsAll(source)); + } + + @Test + public void givenAList_whenListsHaveDifferentSize_thenReturnAnotherListWithTheSameElementsByCopyMethod() { + List source = Arrays.asList(1,2,3); + List dest = Arrays.asList(5,6,7,8,9,10); + + dest = copyListService.copyListByCopyMethod(source, dest); + assertNotEquals(dest.size(), source.size()); + assertTrue(dest.containsAll(source)); + } + + @Test + public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithTheSameElementsByStreamProcess() { + List copy = copyListService.copyListByStream(flowers); + assertEquals(copy.size(), flowers.size()); + assertTrue(copy.containsAll(flowers)); + } + + @Test + public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneElementLessByStreamProcess() { + List copy = copyListService.copyListByStreamAndSkipFirstElement(flowers); + assertNotEquals(copy.size(), flowers.size()); + assertEquals(copy.size() + 1, flowers.size()); + assertFalse(copy.containsAll(flowers)); + } + + @Test + public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithFilterElementsByStreamProcess() { + List copy = copyListService.copyListByStreamWithFilter(flowers, 5); + assertNotEquals(copy.size(), flowers.size()); + assertEquals(copy.size() + 3, flowers.size()); + assertFalse(copy.containsAll(flowers)); + } + + @Test + public void givenAList_whenListIsNull_thenReturnEmptyListByStreamProcess() { + List copy = copyListService.copyListByStreamWithOptional(null); + assertNotNull(copy); + assertEquals(copy.size(), 0); + } + + @Test + public void givenAList_whenListIsNotNull_thenReturnAnotherListWithTheElementsByStreamProcess() { + List copy = copyListService.copyListByStreamWithOptional(flowers); + assertEquals(copy.size(), flowers.size()); + assertTrue(copy.containsAll(flowers)); + } + + @Test + public void givenAList_whenListIsNotNull_thenReturnAnotherListWithOneElementLessByStreamProcess() { + List copy = copyListService.copyListByStreamWithOptionalAndSkip(flowers); + assertNotEquals(copy.size(), flowers.size()); + assertEquals(copy.size() + 1, flowers.size()); + assertFalse(copy.containsAll(flowers)); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/java/list/ReverseIteratorUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/list/ReverseIteratorUnitTest.java new file mode 100644 index 0000000000..172a2fe417 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/java/list/ReverseIteratorUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.java.list; + +import static org.junit.Assert.assertEquals; + +import java.util.Collections; +import java.util.List; +import java.util.ListIterator; + +import org.apache.commons.collections4.iterators.ReverseListIterator; +import org.apache.commons.lang3.StringUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.google.common.collect.Lists; + +public class ReverseIteratorUnitTest { + + private final ReverseIterator reverseIterator = new ReverseIterator(); + + private List list; + + private final String originalString = "ABCDE"; + + @BeforeEach + void setUp() { + + list = Lists.newArrayList("A", "B", "C", "D", "E"); + } + + @Test + void whenIteratingUsingForLoop_thenCorrect() { + + String reverseString = ""; + for (int i = list.size(); i-- > 0; ) { + reverseString += list.get(i); + } + assertEquals(reverseString, StringUtils.reverse(originalString)); + } + + @Test + void whenIteratingUsingListIterator_thenCorrect() { + + String reverseString = ""; + final ListIterator listIterator = list.listIterator(list.size()); + while (listIterator.hasPrevious()) { + reverseString += listIterator.previous(); + } + assertEquals(reverseString, StringUtils.reverse(originalString)); + } + + @Test + void whenIteratingUsingCollections_thenCorrect() { + + String reverseString = ""; + Collections.reverse(list); + for (final String item : list) { + reverseString += item; + } + assertEquals(reverseString, StringUtils.reverse(originalString)); + + assertEquals("E", list.get(0)); + } + + @Test + void whenIteratingUsingApacheReverseListIterator_thenCorrect() { + + String reverseString = ""; + final ReverseListIterator listIterator = new ReverseListIterator(list); + while (listIterator.hasNext()) { + reverseString += listIterator.next(); + } + assertEquals(reverseString, StringUtils.reverse(originalString)); + } + + @Test + void whenIteratingUsingGuava_thenCorrect() { + + String reverseString = ""; + final List reversedList = Lists.reverse(list); + for (final String item : reversedList) { + reverseString += item; + } + assertEquals(reverseString, StringUtils.reverse(originalString)); + + assertEquals("A", list.get(0)); + } +} \ No newline at end of file diff --git a/core-java-collections/src/test/java/com/baeldung/java/map/MapMultipleValuesTest.java b/core-java-collections/src/test/java/com/baeldung/java/map/MapMultipleValuesTest.java deleted file mode 100644 index 88f97f6c19..0000000000 --- a/core-java-collections/src/test/java/com/baeldung/java/map/MapMultipleValuesTest.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.baeldung.java.map; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.collections4.MultiMap; -import org.apache.commons.collections4.MultiMapUtils; -import org.apache.commons.collections4.MultiValuedMap; -import org.apache.commons.collections4.map.MultiValueMap; -import org.apache.commons.collections4.multimap.ArrayListValuedHashMap; -import org.apache.commons.collections4.multimap.HashSetValuedHashMap; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.LinkedHashMultimap; -import com.google.common.collect.Multimap; -import com.google.common.collect.TreeMultimap; - -public class MapMultipleValuesTest { - private static final Logger LOG = LoggerFactory.getLogger(MapMultipleValuesTest.class); - - @Test - public void givenHashMap_whenPuttingTwice_thenReturningFirstValue() { - Map map = new HashMap<>(); - assertThat(map.put("key1", "value1")).isEqualTo(null); - assertThat(map.put("key1", "value2")).isEqualTo("value1"); - assertThat(map.get("key1")).isEqualTo("value2"); - } - - @Test - public void givenCollectionAsValue_whenPuttingTwice_thenReturningCollection() { - Map> map = new HashMap<>(); - List list = new ArrayList<>(); - map.put("key1", list); - map.get("key1").add("value1"); - map.get("key1").add("value2"); - assertThat(map.get("key1").get(0)).isEqualTo("value1"); - assertThat(map.get("key1").get(1)).isEqualTo("value2"); - } - - @Test - public void givenCollectionAsValueAndJava8_whenPuttingTwice_thenReturningCollection() { - Map> map = new HashMap<>(); - map.computeIfAbsent("key1", k -> new ArrayList<>()).add("value1"); - map.computeIfAbsent("key1", k -> new ArrayList<>()).add("value2"); - assertThat(map.get("key1").get(0)).isEqualTo("value1"); - assertThat(map.get("key1").get(1)).isEqualTo("value2"); - } - - @Test - public void givenMultiValueMap_whenPuttingTwice_thenReturningValues() { - MultiMap map = new MultiValueMap<>(); - map.put("key1", "value1"); - map.put("key1", "value2"); - assertThat((Collection) map.get("key1")) - .contains("value1", "value2"); - } - - @Test - public void givenArrayListValuedHashMap_whenPuttingDoubleValues_thenReturningAllValues() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key1", "value1"); - map.put("key1", "value2"); - map.put("key1", "value2"); - assertThat((Collection) map.get("key1")) - .containsExactly("value1", "value2", "value2"); - } - - @Test - public void givenHashSetValuedHashMap_whenPuttingTwiceTheSame_thenReturningOneValue() { - MultiValuedMap map = new HashSetValuedHashMap<>(); - map.put("key1", "value1"); - map.put("key1", "value1"); - assertThat((Collection) map.get("key1")) - .containsExactly("value1"); - } - - @Test(expected = UnsupportedOperationException.class) - public void givenUnmodifiableMultiValuedMap_whenInserting_thenThrowingException() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key1", "value1"); - map.put("key1", "value2"); - MultiValuedMap immutableMap = - MultiMapUtils.unmodifiableMultiValuedMap(map); - immutableMap.put("key1", "value3"); - } - - @Test - public void givenArrayListMultiMap_whenInserting_thenCorrectOutput() { - Multimap map = ArrayListMultimap.create(); - map.put("key1", "value2"); - map.put("key1", "value1"); - assertThat((Collection) map.get("key1")) - .containsExactly("value2", "value1"); - } - - @Test - public void givenLinkedHashMultiMap_whenInserting_thenReturningValuesInInsertionOrder() { - Multimap map = LinkedHashMultimap.create(); - map.put("key1", "value3"); - map.put("key1", "value1"); - map.put("key1", "value2"); - assertThat((Collection) map.get("key1")) - .containsExactly("value3", "value1", "value2"); - } - - @Test - public void givenTreeMultimap_whenInserting_thenReturningValuesInNaturalOrder() { - Multimap map = TreeMultimap.create(); - map.put("key1", "value3"); - map.put("key1", "value1"); - map.put("key1", "value2"); - assertThat((Collection) map.get("key1")) - .containsExactly("value1", "value2", "value3"); - } - -} \ No newline at end of file diff --git a/core-java-collections/src/test/java/com/baeldung/java/map/MapMultipleValuesUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/map/MapMultipleValuesUnitTest.java new file mode 100644 index 0000000000..3a0affa6f3 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/java/map/MapMultipleValuesUnitTest.java @@ -0,0 +1,124 @@ +package com.baeldung.java.map; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections4.MultiMap; +import org.apache.commons.collections4.MultiMapUtils; +import org.apache.commons.collections4.MultiValuedMap; +import org.apache.commons.collections4.map.MultiValueMap; +import org.apache.commons.collections4.multimap.ArrayListValuedHashMap; +import org.apache.commons.collections4.multimap.HashSetValuedHashMap; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.LinkedHashMultimap; +import com.google.common.collect.Multimap; +import com.google.common.collect.TreeMultimap; + +public class MapMultipleValuesUnitTest { + private static final Logger LOG = LoggerFactory.getLogger(MapMultipleValuesUnitTest.class); + + @Test + public void givenHashMap_whenPuttingTwice_thenReturningFirstValue() { + Map map = new HashMap<>(); + assertThat(map.put("key1", "value1")).isEqualTo(null); + assertThat(map.put("key1", "value2")).isEqualTo("value1"); + assertThat(map.get("key1")).isEqualTo("value2"); + } + + @Test + public void givenCollectionAsValue_whenPuttingTwice_thenReturningCollection() { + Map> map = new HashMap<>(); + List list = new ArrayList<>(); + map.put("key1", list); + map.get("key1").add("value1"); + map.get("key1").add("value2"); + assertThat(map.get("key1").get(0)).isEqualTo("value1"); + assertThat(map.get("key1").get(1)).isEqualTo("value2"); + } + + @Test + public void givenCollectionAsValueAndJava8_whenPuttingTwice_thenReturningCollection() { + Map> map = new HashMap<>(); + map.computeIfAbsent("key1", k -> new ArrayList<>()).add("value1"); + map.computeIfAbsent("key1", k -> new ArrayList<>()).add("value2"); + assertThat(map.get("key1").get(0)).isEqualTo("value1"); + assertThat(map.get("key1").get(1)).isEqualTo("value2"); + } + + @Test + public void givenMultiValueMap_whenPuttingTwice_thenReturningValues() { + MultiMap map = new MultiValueMap<>(); + map.put("key1", "value1"); + map.put("key1", "value2"); + assertThat((Collection) map.get("key1")) + .contains("value1", "value2"); + } + + @Test + public void givenArrayListValuedHashMap_whenPuttingDoubleValues_thenReturningAllValues() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("key1", "value1"); + map.put("key1", "value2"); + map.put("key1", "value2"); + assertThat((Collection) map.get("key1")) + .containsExactly("value1", "value2", "value2"); + } + + @Test + public void givenHashSetValuedHashMap_whenPuttingTwiceTheSame_thenReturningOneValue() { + MultiValuedMap map = new HashSetValuedHashMap<>(); + map.put("key1", "value1"); + map.put("key1", "value1"); + assertThat((Collection) map.get("key1")) + .containsExactly("value1"); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenUnmodifiableMultiValuedMap_whenInserting_thenThrowingException() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("key1", "value1"); + map.put("key1", "value2"); + MultiValuedMap immutableMap = + MultiMapUtils.unmodifiableMultiValuedMap(map); + immutableMap.put("key1", "value3"); + } + + @Test + public void givenArrayListMultiMap_whenInserting_thenCorrectOutput() { + Multimap map = ArrayListMultimap.create(); + map.put("key1", "value2"); + map.put("key1", "value1"); + assertThat((Collection) map.get("key1")) + .containsExactly("value2", "value1"); + } + + @Test + public void givenLinkedHashMultiMap_whenInserting_thenReturningValuesInInsertionOrder() { + Multimap map = LinkedHashMultimap.create(); + map.put("key1", "value3"); + map.put("key1", "value1"); + map.put("key1", "value2"); + assertThat((Collection) map.get("key1")) + .containsExactly("value3", "value1", "value2"); + } + + @Test + public void givenTreeMultimap_whenInserting_thenReturningValuesInNaturalOrder() { + Multimap map = TreeMultimap.create(); + map.put("key1", "value3"); + map.put("key1", "value1"); + map.put("key1", "value2"); + assertThat((Collection) map.get("key1")) + .containsExactly("value1", "value2", "value3"); + } + +} \ No newline at end of file diff --git a/core-java-collections/src/test/java/com/baeldung/java/map/MapUtilUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/map/MapUtilUnitTest.java new file mode 100644 index 0000000000..e31385e972 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/java/map/MapUtilUnitTest.java @@ -0,0 +1,104 @@ +/** + * + */ +package com.baeldung.java.map; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.commons.collections4.BidiMap; +import org.apache.commons.collections4.bidimap.DualHashBidiMap; +import org.junit.Test; + +import com.google.common.collect.HashBiMap; + +/** + * @author swpraman + * + */ +public class MapUtilUnitTest { + + + @Test + public void whenUsingImperativeWayForSingleKey_shouldReturnSingleKey() { + Map capitalCountryMap = new HashMap<>(); + capitalCountryMap.put("Tokyo", "Japan"); + capitalCountryMap.put("New Delhi", "India"); + assertEquals("New Delhi", MapUtil.getKey(capitalCountryMap, "India")); + } + + @Test + public void whenUsingImperativeWayForAllKeys_shouldReturnAllKeys() { + Map capitalCountryMap = new HashMap<>(); + capitalCountryMap.put("Tokyo", "Japan"); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + capitalCountryMap.put("Pretoria", "South Africa"); + capitalCountryMap.put("Bloemfontein", "South Africa"); + + assertEquals(new HashSet(Arrays.asList( + new String[] {"Cape Town", "Pretoria", "Bloemfontein"})), + MapUtil.getKeys(capitalCountryMap, "South Africa")); + } + + @Test + public void whenUsingFunctionalWayForSingleKey_shouldReturnSingleKey() { + Map capitalCountryMap = new HashMap<>(); + capitalCountryMap.put("Tokyo", "Japan"); + capitalCountryMap.put("Berlin", "Germany"); + assertEquals("Berlin", MapUtil.keys(capitalCountryMap, "Germany").findFirst().get()); + } + + @Test + public void whenUsingFunctionalWayForAllKeys_shouldReturnAllKeys() { + Map capitalCountryMap = new HashMap<>(); + capitalCountryMap.put("Tokyo", "Japan"); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + capitalCountryMap.put("Pretoria", "South Africa"); + capitalCountryMap.put("Bloemfontein", "South Africa"); + assertEquals(new HashSet(Arrays.asList( + new String[] {"Cape Town", "Pretoria", "Bloemfontein"})), + MapUtil.keys(capitalCountryMap, "South Africa").collect(Collectors.toSet())); + } + + @Test + public void whenUsingBidiMap_shouldReturnKey() { + BidiMap capitalCountryMap = new DualHashBidiMap(); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + assertEquals("Berlin", capitalCountryMap.getKey("Germany")); + } + + @Test + public void whenUsingBidiMapAddDuplicateValue_shouldRemoveOldEntry() { + BidiMap capitalCountryMap = new DualHashBidiMap(); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + capitalCountryMap.put("Pretoria", "South Africa"); + assertEquals("Pretoria", capitalCountryMap.getKey("South Africa")); + } + + @Test + public void whenUsingBiMap_shouldReturnKey() { + HashBiMap capitalCountryMap = HashBiMap.create(); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + assertEquals("Berlin", capitalCountryMap.inverse().get("Germany")); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingBiMapAddDuplicateValue_shouldThrowException() { + HashBiMap capitalCountryMap = HashBiMap.create(); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + capitalCountryMap.put("Pretoria", "South Africa"); + assertEquals("Berlin", capitalCountryMap.inverse().get("Germany")); + } + +} diff --git a/core-java-collections/src/test/java/com/baeldung/java/map/initialize/MapInitializerUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/map/initialize/MapInitializerUnitTest.java new file mode 100644 index 0000000000..80a8983d6f --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/java/map/initialize/MapInitializerUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.java.map.initialize; + +import static org.junit.Assert.assertEquals; + +import java.util.Map; + +import org.junit.Test; + +public class MapInitializerUnitTest { + + @Test + public void givenStaticMap_whenUpdated_thenCorrect() { + + MapInitializer.articleMapOne.put("NewArticle1", "Convert array to List"); + + assertEquals(MapInitializer.articleMapOne.get("NewArticle1"), "Convert array to List"); + + } + + @Test(expected=UnsupportedOperationException.class) + public void givenSingleTonMap_whenEntriesAdded_throwsException() { + + Map map = MapInitializer.createSingletonMap(); + map.put("username2", "password2"); + } + +} diff --git a/core-java-collections/src/test/java/com/baeldung/java/set/HashSetInitalizingUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/set/HashSetInitalizingUnitTest.java new file mode 100644 index 0000000000..2e736501cf --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/java/set/HashSetInitalizingUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung.java.set; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; + +public class HashSetInitalizingUnitTest { + @Test + public void whenUsingJava_usingArraysStaticMethod_thenCorrectSize() { + Set set = new HashSet<>(Arrays.asList("a", "b", "c")); + assertEquals(3, set.size()); + } + + @Test + public void whenUsingJava_usingAnonymousClass_thenCorrectSize() { + Set set = new HashSet(){{ + add("a"); + add("b"); + add("c"); + }}; + assertEquals(3, set.size()); + } + + @Test + public void whenUsingJava_creatingSingletonSet_thenCorrectSize() { + Set set = Collections.singleton("a"); + assertEquals(1, set.size()); + } + + public static final Set newHashSet(T... objs) { + Set set = new HashSet(); + Collections.addAll(set, objs); + return set; + } + + @Test + public void whenUsingJava_usingCustomStaticUtilMethod_thenCorrectSize() { + Set set = newHashSet("a","b","c"); + assertEquals(3, set.size()); + } + + @Test + public void whenUsingJava8_usingCollectOnStream_thenCorrectSize() { + Set set = Stream.of("a", "b", "c").collect(Collectors.toCollection(HashSet::new)); + assertEquals(3, set.size()); + } + + @Test + public void whenUsingGoogleGuava_createMutableSet_thenCorrectSize() { + Set set = Sets.newHashSet("a", "b", "c"); + assertEquals(3, set.size()); + } + + @Test + public void whenUsingGoogleGuava_createImmutableSet_thenCorrectSize() { + Set set = ImmutableSet.of("a", "b", "c"); + assertEquals(3, set.size()); + } + +} + diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/list/listoflist/AddElementsToListUnitTest.java b/core-java-collections/src/test/java/com/baeldung/list/listoflist/AddElementsToListUnitTest.java new file mode 100644 index 0000000000..299a87026f --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/list/listoflist/AddElementsToListUnitTest.java @@ -0,0 +1,69 @@ +package com.baeldung.list.listoflist; + +import com.baeldung.java.list.Flower; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import java.util.*; +import static org.junit.Assert.*; + +public class AddElementsToListUnitTest { + + List flowers; + + @Before + public void init() { + this.flowers = new ArrayList<>(Arrays.asList( + new Flower("Poppy", 12), + new Flower("Anemone", 8), + new Flower("Catmint", 12))); + } + @Test + public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithNewItems() { + List anotherList = new ArrayList<>(); + anotherList.addAll(flowers); + assertEquals(anotherList.size(), flowers.size()); + Assert.assertTrue(anotherList.containsAll(flowers)); + } + @Test + public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithOneModifiedElementByConstructor() { + List anotherList = new ArrayList<>(); + anotherList.addAll(flowers); + Flower flower = anotherList.get(0); + flower.setPetals(flowers.get(0).getPetals() * 3); + assertEquals(anotherList.size(), flowers.size()); + Assert.assertTrue(anotherList.containsAll(flowers)); + } + @Test + public void givenAListAndElements_whenUseCollectionsAddAll_thenAddElementsToTargetList() { + List target = new ArrayList<>(); + Collections.addAll(target, flowers.get(0), flowers.get(1), flowers.get(2), flowers.get(0)); + assertEquals(target.size(), 4); + } + @Test + public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListSkipFirstElementByStreamProcess() { + List flowerVase = new ArrayList<>(); + flowers.stream() + .skip(1) + .forEachOrdered(flowerVase::add); + assertEquals(flowerVase.size() + 1, flowers.size()); + assertFalse(flowerVase.containsAll(flowers)); + } + @Test + public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListFilteringElementsByStreamProcess() { + List flowerVase = new ArrayList<>(); + flowers.stream() + .filter(f -> f.getPetals() > 10) + .forEachOrdered(flowerVase::add); + assertEquals(flowerVase.size() + 1, flowers.size()); + assertFalse(flowerVase.containsAll(flowers)); + } + @Test + public void givenAList_whenListIsNotNull_thenAddElementsToListByStreamProcessWihtOptional() { + List target = new ArrayList<>(); + Optional.ofNullable(flowers) + .ifPresent(target::addAll); + assertNotNull(target); + assertEquals(target.size(), 3); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/list/removeall/RemoveAllUnitTest.java b/core-java-collections/src/test/java/com/baeldung/list/removeall/RemoveAllUnitTest.java new file mode 100644 index 0000000000..c23121053b --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/list/removeall/RemoveAllUnitTest.java @@ -0,0 +1,210 @@ +package com.baeldung.list.removeall; + +import static com.baeldung.list.removeall.RemoveAll.removeWithCallingRemoveUntilModifies; +import static com.baeldung.list.removeall.RemoveAll.removeWithCollectingAndReturningRemainingElements; +import static com.baeldung.list.removeall.RemoveAll.removeWithCollectingRemainingElementsAndAddingToOriginalList; +import static com.baeldung.list.removeall.RemoveAll.removeWithForEachLoop; +import static com.baeldung.list.removeall.RemoveAll.removeWithForLoopDecrementOnRemove; +import static com.baeldung.list.removeall.RemoveAll.removeWithForLoopIncrementIfRemains; +import static com.baeldung.list.removeall.RemoveAll.removeWithIterator; +import static com.baeldung.list.removeall.RemoveAll.removeWithRemoveIf; +import static com.baeldung.list.removeall.RemoveAll.removeWithStandardForLoopUsingIndex; +import static com.baeldung.list.removeall.RemoveAll.removeWithStreamFilter; +import static com.baeldung.list.removeall.RemoveAll.removeWithWhileLoopNonPrimitiveElement; +import static com.baeldung.list.removeall.RemoveAll.removeWithWhileLoopPrimitiveElement; +import static com.baeldung.list.removeall.RemoveAll.removeWithWhileLoopStoringFirstOccurrenceIndex; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.ConcurrentModificationException; +import java.util.List; + +import org.junit.Test; + +public class RemoveAllUnitTest { + + private List list(Integer... elements) { + return new ArrayList<>(Arrays.asList(elements)); + } + + @Test + public void givenAList_whenRemovingElementsWithWhileLoopUsingPrimitiveElement_thenTheResultCorrect() { + // given + List list = list(1, 2, 3); + int valueToRemove = 1; + + // when + assertThatThrownBy(() -> removeWithWhileLoopPrimitiveElement(list, valueToRemove)) + .isInstanceOf(IndexOutOfBoundsException.class); + } + + @Test + public void givenAList_whenRemovingElementsWithWhileLoopUsingNonPrimitiveElement_thenTheResultCorrect() { + // given + List list = list(1, 2, 3); + int valueToRemove = 1; + + // when + removeWithWhileLoopNonPrimitiveElement(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(2, 3)); + } + + @Test + public void givenAList_whenRemovingElementsWithWhileLoopStoringFirstOccurrenceIndex_thenTheResultCorrect() { + // given + List list = list(1, 2, 3); + int valueToRemove = 1; + + // when + removeWithWhileLoopStoringFirstOccurrenceIndex(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(2, 3)); + } + + @Test + public void givenAList_whenRemovingElementsWithCallingRemoveUntilModifies_thenTheResultIsCorrect() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + removeWithCallingRemoveUntilModifies(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(2, 3)); + } + + @Test + public void givenAListWithoutDuplication_whenRemovingElementsWithStandardForLoopUsingIndex_thenTheResultIsCorrect() { + // given + List list = list(1, 2, 3); + int valueToRemove = 1; + + // when + removeWithStandardForLoopUsingIndex(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(2, 3)); + } + + @Test + public void givenAListWithAdjacentElements_whenRemovingElementsWithStandardForLoop_thenTheResultIsInCorrect() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + removeWithStandardForLoopUsingIndex(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(1, 2, 3)); + } + + @Test + public void givenAListWithAdjacentElements_whenRemovingElementsWithForLoopAndDecrementOnRemove_thenTheResultIsCorrect() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + removeWithForLoopDecrementOnRemove(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(2, 3)); + } + + @Test + public void givenAListWithAdjacentElements_whenRemovingElementsWithForLoopAndIncrementIfRemains_thenTheResultIsCorrect() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + removeWithForLoopIncrementIfRemains(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(2, 3)); + } + + @Test + public void givenAList_whenRemovingElementsWithForEachLoop_thenExceptionIsThrown() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + assertThatThrownBy(() -> removeWithForEachLoop(list, valueToRemove)) + .isInstanceOf(ConcurrentModificationException.class); + } + + @Test + public void givenAList_whenRemovingElementsWithIterator_thenTheResultIsCorrect() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + removeWithIterator(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(2, 3)); + } + + @Test + public void givenAList_whenRemovingElementsWithCollectingAndReturningRemainingElements_thenTheResultIsCorrect() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + List result = removeWithCollectingAndReturningRemainingElements(list, valueToRemove); + + // then + assertThat(result).isEqualTo(list(2, 3)); + } + + @Test + public void givenAList_whenRemovingElementsWithCollectingRemainingAndAddingToOriginalList_thenTheResultIsCorrect() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + removeWithCollectingRemainingElementsAndAddingToOriginalList(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(2, 3)); + } + + @Test + public void givenAList_whenRemovingElementsWithStreamFilter_thenTheResultIsCorrect() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + List result = removeWithStreamFilter(list, valueToRemove); + + // then + assertThat(result).isEqualTo(list(2, 3)); + } + + @Test + public void givenAList_whenRemovingElementsWithCallingRemoveIf_thenTheResultIsCorrect() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + removeWithRemoveIf(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(2, 3)); + } + +} diff --git a/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java b/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java new file mode 100644 index 0000000000..f2b1bd9d88 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.list.removefirst; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class RemoveFirstElementUnitTest { + + private List list = new ArrayList<>(); + private LinkedList linkedList = new LinkedList<>(); + + @Before + public void init() { + + list.add("cat"); + list.add("dog"); + list.add("pig"); + list.add("cow"); + list.add("goat"); + + linkedList.add("cat"); + linkedList.add("dog"); + linkedList.add("pig"); + linkedList.add("cow"); + linkedList.add("goat"); + } + + @Test + public void givenList_whenRemoveFirst_thenRemoved() { + list.remove(0); + + assertThat(list, hasSize(4)); + assertThat(list, not(contains("cat"))); + } + + @Test + public void givenLinkedList_whenRemoveFirst_thenRemoved() { + + linkedList.removeFirst(); + + assertThat(linkedList, hasSize(4)); + assertThat(linkedList, not(contains("cat"))); + } + + @Test + public void givenStringArray_whenRemovingFirstElement_thenArrayIsSmallerAndElementRemoved() { + String[] stringArray = {"foo", "bar", "baz"}; + + String[] modifiedArray = Arrays.copyOfRange(stringArray, 1, stringArray.length); + + assertThat(modifiedArray.length, is(2)); + assertThat(modifiedArray[0], is("bar")); + } + +} diff --git a/core-java-collections/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java b/core-java-collections/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java new file mode 100644 index 0000000000..875045946d --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.nullsafecollectionstreams; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.stream.Stream; +import org.junit.Test; +import static org.junit.Assert.*; + +public class NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest { + + private final NullSafeCollectionStreamsUsingCommonsEmptyIfNull instance = + new NullSafeCollectionStreamsUsingCommonsEmptyIfNull(); + @Test + public void whenCollectionIsNull_thenExpectAnEmptyStream() { + Collection collection = null; + Stream expResult = Stream.empty(); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + } + + @Test + public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() { + Collection collection = Arrays.asList("a", "b", "c"); + Stream expResult = Arrays.stream(new String[] { "a", "b", "c" }); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + } + + private static void assertStreamEquals(Stream s1, Stream s2) { + Iterator iter1 = s1.iterator(), iter2 = s2.iterator(); + while (iter1.hasNext() && iter2.hasNext()) + assertEquals(iter1.next(), iter2.next()); + assert !iter1.hasNext() && !iter2.hasNext(); + } + +} diff --git a/core-java-collections/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java b/core-java-collections/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java new file mode 100644 index 0000000000..402f1a6a19 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.nullsafecollectionstreams; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.stream.Stream; +import org.junit.Test; +import static org.junit.Assert.*; + +public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest { + + private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = + new NullSafeCollectionStreamsUsingJava8OptionalContainer(); + @Test + public void whenCollectionIsNull_thenExpectAnEmptyStream() { + Collection collection = null; + Stream expResult = Stream.empty(); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + } + + @Test + public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() { + Collection collection = Arrays.asList("a", "b", "c"); + Stream expResult = Arrays.stream(new String[] { "a", "b", "c" }); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + } + + private static void assertStreamEquals(Stream s1, Stream s2) { + Iterator iter1 = s1.iterator(), iter2 = s2.iterator(); + while (iter1.hasNext() && iter2.hasNext()) + assertEquals(iter1.next(), iter2.next()); + assert !iter1.hasNext() && !iter2.hasNext(); + } + +} diff --git a/core-java-collections/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java b/core-java-collections/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java new file mode 100644 index 0000000000..bb6152371d --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.nullsafecollectionstreams; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.stream.Stream; +import org.junit.Test; +import static org.junit.Assert.*; + +public class NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest { + + private final NullSafeCollectionStreamsUsingNullDereferenceCheck instance = + new NullSafeCollectionStreamsUsingNullDereferenceCheck(); + + @Test + public void whenCollectionIsNull_thenExpectAnEmptyStream() { + Collection collection = null; + Stream expResult = Stream.empty(); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + } + + @Test + public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() { + Collection collection = Arrays.asList("a", "b", "c"); + Stream expResult = Arrays.stream(new String[] { "a", "b", "c" }); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + } + + private static void assertStreamEquals(Stream s1, Stream s2) { + Iterator iter1 = s1.iterator(), iter2 = s2.iterator(); + while (iter1.hasNext() && iter2.hasNext()) + assertEquals(iter1.next(), iter2.next()); + assert !iter1.hasNext() && !iter2.hasNext(); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java b/core-java-collections/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/stack_tests/MultithreadingCorrectnessStackUnitTest.java b/core-java-collections/src/test/java/com/baeldung/stack_tests/MultithreadingCorrectnessStackUnitTest.java new file mode 100644 index 0000000000..4550994aa3 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/stack_tests/MultithreadingCorrectnessStackUnitTest.java @@ -0,0 +1,101 @@ +package com.baeldung.stack_tests; + +import com.baeldung.thread_safe_lifo.DequeBasedSynchronizedStack; +import org.junit.Assert; +import org.junit.Test; + +import java.util.ArrayDeque; +import java.util.concurrent.ConcurrentLinkedDeque; + +import static java.util.stream.IntStream.range; + +/** + * Correctness tests for Stack in multi threaded environment. + */ +public class MultithreadingCorrectnessStackUnitTest { + + @Test + public void givenSynchronizedDeque_whenExecutedParallel_thenWorkRight() { + + DequeBasedSynchronizedStack deque = new DequeBasedSynchronizedStack<>(); + + // Serial execution of push on ConcurrentLinkedQueue will always result in correct execution. + range(1, 10000).forEach(value -> deque.push(value)); + + int sum = 0; + while(deque.peek() != null) { + sum += deque.pop(); + } + + Assert.assertEquals(49995000, sum); + + // Parallel execution of push on ConcurrentLinkedQueue will always result in correct execution. + range(1, 10000).parallel().forEach(value -> deque.push(value)); + + sum = 0; + while(deque.peek() != null) { + sum += deque.pop(); + } + + Assert.assertEquals(49995000, sum); + } + + @Test + public void givenConcurrentLinkedQueue_whenExecutedParallel_thenWorkRight() { + + ConcurrentLinkedDeque deque = new ConcurrentLinkedDeque<>(); + + // Serial execution of push on ConcurrentLinkedQueue will always result in correct execution. + range(1, 10000).forEach(value -> deque.push(value)); + + int sum = 0; + while(deque.peek() != null) { + sum += deque.pop(); + } + + Assert.assertEquals(49995000, sum); + + // Parallel execution of push on ConcurrentLinkedQueue will always result in correct execution. + range(1, 10000).parallel().forEach(value -> deque.push(value)); + + sum = 0; + while(deque.peek() != null) { + sum += deque.pop(); + } + + Assert.assertEquals(49995000, sum); + } + + @Test + public void givenArrayDeque_whenExecutedParallel_thenShouldFail() { + + ArrayDeque deque = new ArrayDeque<>(); + + // Serial execution of push on ArrayDeque will always result in correct execution. + range(1, 10000).forEach(value -> deque.push(value)); + + int sum = 0; + while(deque.peek() != null) { + sum += deque.pop(); + } + + Assert.assertEquals(49995000, sum); + + // Parallel execution of push on ArrayDeque will not result in correct execution. + range(1, 10000).parallel().forEach(value -> deque.push(value)); + + sum = 0; + while(deque.peek() != null) { + sum += deque.pop(); + } + + // This shouldn't happen. + if(sum == 49995000) { + System.out.println("Something wrong in the environment, Please try some big value and check"); + // To safe-guard build without test failures. + return; + } + + Assert.assertNotEquals(49995000, sum); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/stack_tests/StackUnitTest.java b/core-java-collections/src/test/java/com/baeldung/stack_tests/StackUnitTest.java new file mode 100644 index 0000000000..07c4760186 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/stack_tests/StackUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.stack_tests; + +import com.baeldung.thread_safe_lifo.DequeBasedSynchronizedStack; +import com.google.common.collect.Streams; +import org.junit.Assert; +import org.junit.Test; + +import java.util.ArrayDeque; +import java.util.Collection; +import java.util.Collections; +import java.util.Stack; +import java.util.concurrent.ConcurrentLinkedDeque; +import java.util.stream.Stream; + +import static java.util.stream.IntStream.range; + +/** + * These tests are to understand the Stack implementation in Java Collections. + */ +public class StackUnitTest { + + @Test + public void givenStack_whenPushPopPeek_thenWorkRight() { + Stack namesStack = new Stack<>(); + + namesStack.push("Bill Gates"); + namesStack.push("Elon Musk"); + + Assert.assertEquals("Elon Musk", namesStack.peek()); + Assert.assertEquals("Elon Musk", namesStack.pop()); + Assert.assertEquals("Bill Gates", namesStack.pop()); + + Assert.assertEquals(0, namesStack.size()); + } + + @Test + public void givenSynchronizedDeque_whenPushPopPeek_thenWorkRight() { + DequeBasedSynchronizedStack namesStack = new DequeBasedSynchronizedStack<>(); + + namesStack.push("Bill Gates"); + namesStack.push("Elon Musk"); + + Assert.assertEquals("Elon Musk", namesStack.peek()); + Assert.assertEquals("Elon Musk", namesStack.pop()); + Assert.assertEquals("Bill Gates", namesStack.pop()); + + Assert.assertEquals(0, namesStack.size()); + } + + @Test + public void givenConcurrentLinkedDeque_whenPushPopPeek_thenWorkRight() { + ConcurrentLinkedDeque namesStack = new ConcurrentLinkedDeque<>(); + + namesStack.push("Bill Gates"); + namesStack.push("Elon Musk"); + + Assert.assertEquals("Elon Musk", namesStack.peek()); + Assert.assertEquals("Elon Musk", namesStack.pop()); + Assert.assertEquals("Bill Gates", namesStack.pop()); + + Assert.assertEquals(0, namesStack.size()); + } +} diff --git a/core-java-collections/src/test/java/org/baeldung/java/collections/CollectionsEmpty.java b/core-java-collections/src/test/java/org/baeldung/java/collections/CollectionsEmpty.java new file mode 100644 index 0000000000..09ecebe47b --- /dev/null +++ b/core-java-collections/src/test/java/org/baeldung/java/collections/CollectionsEmpty.java @@ -0,0 +1,26 @@ +package org.baeldung.java.collections; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; + +class CollectionsEmpty { + + @Test + public void givenArrayList_whenAddingElement_addsNewElement() { + ArrayList mutableList = new ArrayList<>(); + mutableList.add("test"); + + Assert.assertEquals(mutableList.size(), 1); + Assert.assertEquals(mutableList.get(0), "test"); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenCollectionsEmptyList_whenAddingElement_throwsUnsupportedOperationException() { + List immutableList = Collections.emptyList(); + immutableList.add("test"); + } + +} diff --git a/core-java-concurrency-collections/.gitignore b/core-java-concurrency-collections/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/core-java-concurrency-collections/.gitignore @@ -0,0 +1,26 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +*.txt +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/core-java-concurrency-collections/README.md b/core-java-concurrency-collections/README.md new file mode 100644 index 0000000000..b982a91861 --- /dev/null +++ b/core-java-concurrency-collections/README.md @@ -0,0 +1,15 @@ +========= + +## Core Java Concurrency Collections Examples + +### Relevant Articles: +- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue) +- [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map) +- [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue) +- [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception) +- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool) +- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue) +- [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue) +- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue) +- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map) +- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist) diff --git a/core-java-concurrency-collections/pom.xml b/core-java-concurrency-collections/pom.xml new file mode 100644 index 0000000000..9473de8c51 --- /dev/null +++ b/core-java-concurrency-collections/pom.xml @@ -0,0 +1,74 @@ + + 4.0.0 + com.baeldung + core-java-concurrency-collections + 0.1.0-SNAPSHOT + jar + core-java-concurrency-collections + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + commons-io + commons-io + ${commons-io.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + com.jayway.awaitility + awaitility + ${avaitility.version} + test + + + + + core-java-concurrency-collections + + + src/main/resources + true + + + + + + + 21.0 + 3.5 + 3.6.1 + 4.1 + 4.01 + + 3.6.1 + 1.7.0 + + + diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java similarity index 79% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java index 052136bfe4..842d4e630e 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java +++ b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java @@ -10,15 +10,18 @@ public class BlockingQueueUsage { int N_CONSUMERS = Runtime.getRuntime().availableProcessors(); int poisonPill = Integer.MAX_VALUE; int poisonPillPerProducer = N_CONSUMERS / N_PRODUCERS; - + int mod = N_CONSUMERS % N_PRODUCERS; BlockingQueue queue = new LinkedBlockingQueue<>(BOUND); - for (int i = 0; i < N_PRODUCERS; i++) { + for (int i = 1; i < N_PRODUCERS; i++) { new Thread(new NumbersProducer(queue, poisonPill, poisonPillPerProducer)).start(); } for (int j = 0; j < N_CONSUMERS; j++) { new Thread(new NumbersConsumer(queue, poisonPill)).start(); } + + new Thread(new NumbersProducer(queue, poisonPill, poisonPillPerProducer+mod)).start(); + } } \ No newline at end of file diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/Event.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/skiplist/Event.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/Event.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/skiplist/Event.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Consumer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/transferqueue/Consumer.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/transferqueue/Consumer.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/transferqueue/Consumer.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Producer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/transferqueue/Producer.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/transferqueue/Producer.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/transferqueue/Producer.java diff --git a/handling-spring-static-resources/src/main/resources/logback.xml b/core-java-concurrency-collections/src/main/resources/logback.xml similarity index 100% rename from handling-spring-static-resources/src/main/resources/logback.xml rename to core-java-concurrency-collections/src/main/resources/logback.xml diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java diff --git a/core-java-concurrency/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java b/core-java-concurrency-collections/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java similarity index 100% rename from core-java-concurrency/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java rename to core-java-concurrency-collections/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java diff --git a/out/production/main122/.gitignore b/core-java-concurrency-collections/src/test/resources/.gitignore similarity index 100% rename from out/production/main122/.gitignore rename to core-java-concurrency-collections/src/test/resources/.gitignore diff --git a/core-java-concurrency/README.md b/core-java-concurrency/README.md index 8192a8e301..d775d24dff 100644 --- a/core-java-concurrency/README.md +++ b/core-java-concurrency/README.md @@ -7,22 +7,12 @@ - [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial) - [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava) - [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future) -- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue) - [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch) -- [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map) -- [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue) -- [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception) -- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool) - [Guide to java.util.concurrent.Locks](http://www.baeldung.com/java-concurrent-locks) - [An Introduction to ThreadLocal in Java](http://www.baeldung.com/java-threadlocal) -- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue) -- [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue) -- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue) -- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map) - [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep) - [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator) - [The Dining Philosophers Problem in Java](http://www.baeldung.com/java-dining-philoshophers) -- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist) - [Guide to the Java Phaser](http://www.baeldung.com/java-phaser) - [Guide to Synchronized Keyword in Java](http://www.baeldung.com/java-synchronized) - [An Introduction to Atomic Variables in Java](http://www.baeldung.com/java-atomic-variables) @@ -38,3 +28,4 @@ - [Priority-based Job Scheduling in Java](http://www.baeldung.com/java-priority-job-schedule) - [A Custom Spring SecurityConfigurer](http://www.baeldung.com/spring-security-custom-configurer) - [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle) +- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable) diff --git a/core-java-concurrency/pom.xml b/core-java-concurrency/pom.xml index 7e162abc64..bd22253c2c 100644 --- a/core-java-concurrency/pom.xml +++ b/core-java-concurrency/pom.xml @@ -1,5 +1,5 @@ + 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 core-java-concurrency @@ -10,8 +10,8 @@ com.baeldung parent-java - 0.0.1-SNAPSHOT - ../parent-java + 0.0.1-SNAPSHOT + ../parent-java @@ -57,112 +57,6 @@ true - - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - prepare-package - - copy-dependencies - - - ${project.build.directory}/libs - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - true - libs/ - org.baeldung.executable.ExecutableMavenJar - - - - - - org.apache.maven.plugins - maven-assembly-plugin - - - package - - single - - - ${project.basedir} - - - org.baeldung.executable.ExecutableMavenJar - - - - jar-with-dependencies - - - - - - - org.apache.maven.plugins - maven-shade-plugin - - - - shade - - - true - - - org.baeldung.executable.ExecutableMavenJar - - - - - - - - com.jolira - onejar-maven-plugin - - - - org.baeldung.executable.ExecutableMavenJar - true - ${project.build.finalName}-onejar.${project.packaging} - - - one-jar - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - spring-boot - org.baeldung.executable.ExecutableMavenJar - - - - - @@ -170,7 +64,6 @@ 21.0 3.5 3.6.1 - 2.5 4.1 4.01 diff --git a/core-java-concurrency/src/main/resources/logback.xml b/core-java-concurrency/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/core-java-concurrency/src/main/resources/logback.xml +++ b/core-java-concurrency/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java new file mode 100644 index 0000000000..4eead471f8 --- /dev/null +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java @@ -0,0 +1,38 @@ +package com.baeldung.concurrent.atomic; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + +import org.junit.Test; + +public class ThreadSafeCounterIntegrationTest { + + @Test + public void givenMultiThread_whenSafeCounterWithLockIncrement() throws InterruptedException { + ExecutorService service = Executors.newFixedThreadPool(3); + SafeCounterWithLock safeCounter = new SafeCounterWithLock(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(safeCounter::increment)); + service.awaitTermination(100, TimeUnit.MILLISECONDS); + + assertEquals(1000, safeCounter.getValue()); + } + + @Test + public void givenMultiThread_whenSafeCounterWithoutLockIncrement() throws InterruptedException { + ExecutorService service = Executors.newFixedThreadPool(3); + SafeCounterWithoutLock safeCounter = new SafeCounterWithoutLock(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(safeCounter::increment)); + service.awaitTermination(100, TimeUnit.MILLISECONDS); + + assertEquals(1000, safeCounter.getValue()); + } + +} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java deleted file mode 100644 index e9b2e164ae..0000000000 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.concurrent.atomic; - -import static org.junit.Assert.assertEquals; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.stream.IntStream; - -import org.junit.Test; - -public class ThreadSafeCounterTest { - - @Test - public void givenMultiThread_whenSafeCounterWithLockIncrement() throws InterruptedException { - ExecutorService service = Executors.newFixedThreadPool(3); - SafeCounterWithLock safeCounter = new SafeCounterWithLock(); - - IntStream.range(0, 1000) - .forEach(count -> service.submit(safeCounter::increment)); - service.awaitTermination(100, TimeUnit.MILLISECONDS); - - assertEquals(1000, safeCounter.getValue()); - } - - @Test - public void givenMultiThread_whenSafeCounterWithoutLockIncrement() throws InterruptedException { - ExecutorService service = Executors.newFixedThreadPool(3); - SafeCounterWithoutLock safeCounter = new SafeCounterWithoutLock(); - - IntStream.range(0, 1000) - .forEach(count -> service.submit(safeCounter::increment)); - service.awaitTermination(100, TimeUnit.MILLISECONDS); - - assertEquals(1000, safeCounter.getValue()); - } - -} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadTest.java deleted file mode 100644 index 3ca69d8847..0000000000 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.concurrent.daemon; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Ignore; -import org.junit.Test; - -public class DaemonThreadTest { - - @Test - @Ignore - public void whenCallIsDaemon_thenCorrect() { - NewThread daemonThread = new NewThread(); - NewThread userThread = new NewThread(); - daemonThread.setDaemon(true); - daemonThread.start(); - userThread.start(); - - assertTrue(daemonThread.isDaemon()); - assertFalse(userThread.isDaemon()); - } - - @Test(expected = IllegalThreadStateException.class) - @Ignore - public void givenUserThread_whenSetDaemonWhileRunning_thenIllegalThreadStateException() { - NewThread daemonThread = new NewThread(); - daemonThread.start(); - daemonThread.setDaemon(true); - } -} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadUnitTest.java new file mode 100644 index 0000000000..2d8b91d846 --- /dev/null +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.concurrent.daemon; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Ignore; +import org.junit.Test; + +public class DaemonThreadUnitTest { + + @Test + @Ignore + public void whenCallIsDaemon_thenCorrect() { + NewThread daemonThread = new NewThread(); + NewThread userThread = new NewThread(); + daemonThread.setDaemon(true); + daemonThread.start(); + userThread.start(); + + assertTrue(daemonThread.isDaemon()); + assertFalse(userThread.isDaemon()); + } + + @Test(expected = IllegalThreadStateException.class) + @Ignore + public void givenUserThread_whenSetDaemonWhileRunning_thenIllegalThreadStateException() { + NewThread daemonThread = new NewThread(); + daemonThread.start(); + daemonThread.setDaemon(true); + } +} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java deleted file mode 100644 index 9c56fa64be..0000000000 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.concurrent.synchronize; - -import org.junit.Test; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.stream.IntStream; - -import static org.junit.Assert.assertEquals; - -public class BaeldungSychronizedBlockTest { - - @Test - public void givenMultiThread_whenBlockSync() throws InterruptedException { - ExecutorService service = Executors.newFixedThreadPool(3); - BaeldungSynchronizedBlocks synchronizedBlocks = new BaeldungSynchronizedBlocks(); - - IntStream.range(0, 1000) - .forEach(count -> service.submit(synchronizedBlocks::performSynchronisedTask)); - service.awaitTermination(500, TimeUnit.MILLISECONDS); - - assertEquals(1000, synchronizedBlocks.getCount()); - } - - @Test - public void givenMultiThread_whenStaticSyncBlock() throws InterruptedException { - ExecutorService service = Executors.newCachedThreadPool(); - - IntStream.range(0, 1000) - .forEach(count -> service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask)); - service.awaitTermination(500, TimeUnit.MILLISECONDS); - - assertEquals(1000, BaeldungSynchronizedBlocks.getStaticCount()); - } - -} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockUnitTest.java new file mode 100644 index 0000000000..553b8c9906 --- /dev/null +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.concurrent.synchronize; + +import org.junit.Test; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + +import static org.junit.Assert.assertEquals; + +public class BaeldungSychronizedBlockUnitTest { + + @Test + public void givenMultiThread_whenBlockSync() throws InterruptedException { + ExecutorService service = Executors.newFixedThreadPool(3); + BaeldungSynchronizedBlocks synchronizedBlocks = new BaeldungSynchronizedBlocks(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(synchronizedBlocks::performSynchronisedTask)); + service.awaitTermination(500, TimeUnit.MILLISECONDS); + + assertEquals(1000, synchronizedBlocks.getCount()); + } + + @Test + public void givenMultiThread_whenStaticSyncBlock() throws InterruptedException { + ExecutorService service = Executors.newCachedThreadPool(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask)); + service.awaitTermination(500, TimeUnit.MILLISECONDS); + + assertEquals(1000, BaeldungSynchronizedBlocks.getStaticCount()); + } + +} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsTest.java deleted file mode 100644 index ba7c1f0a7b..0000000000 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.concurrent.synchronize; - -import org.junit.Ignore; -import org.junit.Test; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.stream.IntStream; - -import static org.junit.Assert.assertEquals; - -public class BaeldungSynchronizeMethodsTest { - - @Test - @Ignore - public void givenMultiThread_whenNonSyncMethod() throws InterruptedException { - ExecutorService service = Executors.newFixedThreadPool(3); - BaeldungSynchronizedMethods method = new BaeldungSynchronizedMethods(); - - IntStream.range(0, 1000) - .forEach(count -> service.submit(method::calculate)); - service.awaitTermination(100, TimeUnit.MILLISECONDS); - - assertEquals(1000, method.getSum()); - } - - @Test - public void givenMultiThread_whenMethodSync() throws InterruptedException { - ExecutorService service = Executors.newFixedThreadPool(3); - BaeldungSynchronizedMethods method = new BaeldungSynchronizedMethods(); - - IntStream.range(0, 1000) - .forEach(count -> service.submit(method::synchronisedCalculate)); - service.awaitTermination(100, TimeUnit.MILLISECONDS); - - assertEquals(1000, method.getSyncSum()); - } - - @Test - public void givenMultiThread_whenStaticSyncMethod() throws InterruptedException { - ExecutorService service = Executors.newCachedThreadPool(); - - IntStream.range(0, 1000) - .forEach(count -> service.submit(BaeldungSynchronizedMethods::syncStaticCalculate)); - service.awaitTermination(100, TimeUnit.MILLISECONDS); - - assertEquals(1000, BaeldungSynchronizedMethods.staticSum); - } - -} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsUnitTest.java new file mode 100644 index 0000000000..32648729d5 --- /dev/null +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.concurrent.synchronize; + +import org.junit.Ignore; +import org.junit.Test; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + +import static org.junit.Assert.assertEquals; + +public class BaeldungSynchronizeMethodsUnitTest { + + @Test + @Ignore + public void givenMultiThread_whenNonSyncMethod() throws InterruptedException { + ExecutorService service = Executors.newFixedThreadPool(3); + BaeldungSynchronizedMethods method = new BaeldungSynchronizedMethods(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(method::calculate)); + service.awaitTermination(100, TimeUnit.MILLISECONDS); + + assertEquals(1000, method.getSum()); + } + + @Test + public void givenMultiThread_whenMethodSync() throws InterruptedException { + ExecutorService service = Executors.newFixedThreadPool(3); + BaeldungSynchronizedMethods method = new BaeldungSynchronizedMethods(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(method::synchronisedCalculate)); + service.awaitTermination(100, TimeUnit.MILLISECONDS); + + assertEquals(1000, method.getSyncSum()); + } + + @Test + public void givenMultiThread_whenStaticSyncMethod() throws InterruptedException { + ExecutorService service = Executors.newCachedThreadPool(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(BaeldungSynchronizedMethods::syncStaticCalculate)); + service.awaitTermination(100, TimeUnit.MILLISECONDS); + + assertEquals(1000, BaeldungSynchronizedMethods.staticSum); + } + +} diff --git a/core-java-io/README.md b/core-java-io/README.md index 1354854e1f..17c93d9739 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -27,3 +27,7 @@ - [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice) - [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels) - [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel) +- [Download a File From an URL in Java](http://www.baeldung.com/java-download-file) +- [Create a Symbolic Link with Java](http://www.baeldung.com/java-symlink) +- [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter) +- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) diff --git a/core-java-io/pom.xml b/core-java-io/pom.xml index 1437b85ac2..bc71fb8838 100644 --- a/core-java-io/pom.xml +++ b/core-java-io/pom.xml @@ -1,5 +1,5 @@ + 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 core-java-io @@ -10,8 +10,8 @@ com.baeldung parent-java - 0.0.1-SNAPSHOT - ../parent-java + 0.0.1-SNAPSHOT + ../parent-java @@ -74,23 +74,6 @@ log4j ${log4j.version} - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - org.slf4j log4j-over-slf4j @@ -103,42 +86,12 @@ provided - - org.hamcrest - hamcrest-all - ${hamcrest-all.version} - test - - - junit - junit - ${junit.version} - test - - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - org.assertj assertj-core ${assertj.version} test - - org.mockito - mockito-core - ${mockito.version} - test - com.jayway.awaitility awaitility @@ -196,6 +149,12 @@ ${hsqldb.version} runtime + + + org.asynchttpclient + async-http-client + ${async-http-client.version} + @@ -214,6 +173,7 @@ **/*LiveTest.java **/*IntegrationTest.java + **/*IntTest.java **/*LongRunningUnitTest.java **/*ManualTest.java @@ -223,6 +183,7 @@ org.springframework.boot spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} @@ -246,7 +207,7 @@ -Xmx300m -XX:+UseParallelGC -classpath - + com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed @@ -283,6 +244,7 @@ **/*IntegrationTest.java + **/*IntTest.java @@ -310,7 +272,7 @@ java -classpath - + org.openjdk.jmh.Main .* @@ -327,18 +289,12 @@ 2.8.5 - - 1.7.21 - 1.1.7 - - 22.0 3.5 1.55 1.10 3.6.1 1.0.3 - 2.5 4.1 4.01 0.4 @@ -350,21 +306,18 @@ 0.9.0 - 1.3 - 4.12 - 2.8.9 3.6.1 1.7.0 - 3.7.0 - 2.19.1 1.8 1.8 3.0.0-M1 2.4.0 2.1.0.1 1.19 + 2.4.5 + 2.0.4.RELEASE \ No newline at end of file diff --git a/core-java-io/src/main/java/com/baeldung/download/FileDownload.java b/core-java-io/src/main/java/com/baeldung/download/FileDownload.java new file mode 100644 index 0000000000..c7dd154023 --- /dev/null +++ b/core-java-io/src/main/java/com/baeldung/download/FileDownload.java @@ -0,0 +1,89 @@ +package com.baeldung.download; + +import org.apache.commons.io.FileUtils; +import org.asynchttpclient.*; + +import java.io.*; +import java.net.*; +import java.nio.channels.Channels; +import java.nio.channels.FileChannel; +import java.nio.channels.ReadableByteChannel; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.concurrent.ExecutionException; + +public class FileDownload { + + public static void downloadWithJavaIO(String url, String localFilename) { + + try (BufferedInputStream in = new BufferedInputStream(new URL(url).openStream()); FileOutputStream fileOutputStream = new FileOutputStream(localFilename)) { + + byte dataBuffer[] = new byte[1024]; + int bytesRead; + while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) { + fileOutputStream.write(dataBuffer, 0, bytesRead); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void downloadWithJava7IO(String url, String localFilename) { + + try (InputStream in = new URL(url).openStream()) { + Files.copy(in, Paths.get(localFilename), StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void downloadWithJavaNIO(String fileURL, String localFilename) throws IOException { + + URL url = new URL(fileURL); + try (ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream()); + FileOutputStream fileOutputStream = new FileOutputStream(localFilename); FileChannel fileChannel = fileOutputStream.getChannel()) { + + fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE); + } + } + + public static void downloadWithApacheCommons(String url, String localFilename) { + + int CONNECT_TIMEOUT = 10000; + int READ_TIMEOUT = 10000; + try { + FileUtils.copyURLToFile(new URL(url), new File(localFilename), CONNECT_TIMEOUT, READ_TIMEOUT); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public static void downloadWithAHC(String url, String localFilename) throws ExecutionException, InterruptedException, IOException { + + FileOutputStream stream = new FileOutputStream(localFilename); + AsyncHttpClient client = Dsl.asyncHttpClient(); + + client.prepareGet(url) + .execute(new AsyncCompletionHandler() { + + @Override + public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception { + stream.getChannel() + .write(bodyPart.getBodyByteBuffer()); + return State.CONTINUE; + } + + @Override + public FileOutputStream onCompleted(Response response) throws Exception { + return stream; + } + }) + .get(); + + stream.getChannel().close(); + client.close(); + } + +} diff --git a/core-java-io/src/main/java/com/baeldung/download/ResumableDownload.java b/core-java-io/src/main/java/com/baeldung/download/ResumableDownload.java new file mode 100644 index 0000000000..55ff485e40 --- /dev/null +++ b/core-java-io/src/main/java/com/baeldung/download/ResumableDownload.java @@ -0,0 +1,62 @@ +package com.baeldung.download; + +import java.io.*; +import java.net.*; + +public class ResumableDownload { + + public static long downloadFile(String downloadUrl, String saveAsFileName) throws IOException, URISyntaxException { + + File outputFile = new File(saveAsFileName); + URLConnection downloadFileConnection = new URI(downloadUrl).toURL() + .openConnection(); + return transferDataAndGetBytesDownloaded(downloadFileConnection, outputFile); + } + + private static long transferDataAndGetBytesDownloaded(URLConnection downloadFileConnection, File outputFile) throws IOException { + + long bytesDownloaded = 0; + try (InputStream is = downloadFileConnection.getInputStream(); OutputStream os = new FileOutputStream(outputFile, true)) { + + byte[] buffer = new byte[1024]; + + int bytesCount; + while ((bytesCount = is.read(buffer)) > 0) { + os.write(buffer, 0, bytesCount); + bytesDownloaded += bytesCount; + } + } + return bytesDownloaded; + } + + public static long downloadFileWithResume(String downloadUrl, String saveAsFileName) throws IOException, URISyntaxException { + File outputFile = new File(saveAsFileName); + + URLConnection downloadFileConnection = addFileResumeFunctionality(downloadUrl, outputFile); + return transferDataAndGetBytesDownloaded(downloadFileConnection, outputFile); + } + + private static URLConnection addFileResumeFunctionality(String downloadUrl, File outputFile) throws IOException, URISyntaxException, ProtocolException, ProtocolException { + long existingFileSize = 0L; + URLConnection downloadFileConnection = new URI(downloadUrl).toURL() + .openConnection(); + + if (outputFile.exists() && downloadFileConnection instanceof HttpURLConnection) { + HttpURLConnection httpFileConnection = (HttpURLConnection) downloadFileConnection; + + HttpURLConnection tmpFileConn = (HttpURLConnection) new URI(downloadUrl).toURL() + .openConnection(); + tmpFileConn.setRequestMethod("HEAD"); + long fileLength = tmpFileConn.getContentLengthLong(); + existingFileSize = outputFile.length(); + + if (existingFileSize < fileLength) { + httpFileConnection.setRequestProperty("Range", "bytes=" + existingFileSize + "-" + fileLength); + } else { + throw new IOException("File Download already completed."); + } + } + return downloadFileConnection; + } + +} diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java new file mode 100644 index 0000000000..45ff486a79 --- /dev/null +++ b/core-java-io/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java @@ -0,0 +1,24 @@ +package com.baeldung.fileparser; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; + +public class BufferedReaderExample { + + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { + + ArrayList result = new ArrayList<>(); + + try (BufferedReader br = new BufferedReader(new FileReader(filename))) { + + while (br.ready()) { + result.add(br.readLine()); + } + return result; + } + + } + +} diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/FileReaderExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/FileReaderExample.java new file mode 100644 index 0000000000..f9dd2a9ec5 --- /dev/null +++ b/core-java-io/src/main/java/com/baeldung/fileparser/FileReaderExample.java @@ -0,0 +1,31 @@ +package com.baeldung.fileparser; + +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; + +public class FileReaderExample { + + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { + + ArrayList result = new ArrayList<>(); + + try (FileReader f = new FileReader(filename)) { + StringBuffer sb = new StringBuffer(); + while (f.ready()) { + char c = (char) f.read(); + if (c == '\n') { + result.add(sb.toString()); + sb = new StringBuffer(); + } else { + sb.append(c); + } + } + if (sb.length() > 0) { + result.add(sb.toString()); + } + } + + return result; + } +} diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java new file mode 100644 index 0000000000..8e74f7d386 --- /dev/null +++ b/core-java-io/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java @@ -0,0 +1,18 @@ +package com.baeldung.fileparser; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +public class FilesReadLinesExample { + + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { + + List result = Files.readAllLines(Paths.get(filename)); + + return (ArrayList) result; + } + +} diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/ScannerIntExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/ScannerIntExample.java new file mode 100644 index 0000000000..25d17af4ea --- /dev/null +++ b/core-java-io/src/main/java/com/baeldung/fileparser/ScannerIntExample.java @@ -0,0 +1,24 @@ +package com.baeldung.fileparser; + +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Scanner; + +public class ScannerIntExample { + + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { + + ArrayList result = new ArrayList<>(); + + try (Scanner s = new Scanner(new FileReader(filename))) { + + while (s.hasNext()) { + result.add(s.nextInt()); + } + return result; + } + + } + +} diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/ScannerStringExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/ScannerStringExample.java new file mode 100644 index 0000000000..ec213c9490 --- /dev/null +++ b/core-java-io/src/main/java/com/baeldung/fileparser/ScannerStringExample.java @@ -0,0 +1,24 @@ +package com.baeldung.fileparser; + +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Scanner; + +public class ScannerStringExample { + + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { + + ArrayList result = new ArrayList<>(); + + try (Scanner s = new Scanner(new FileReader(filename))) { + + while (s.hasNext()) { + result.add(s.nextLine()); + } + return result; + } + + } + +} diff --git a/core-java-io/src/main/java/com/baeldung/symlink/SymLinkExample.java b/core-java-io/src/main/java/com/baeldung/symlink/SymLinkExample.java new file mode 100644 index 0000000000..63ee0f14b1 --- /dev/null +++ b/core-java-io/src/main/java/com/baeldung/symlink/SymLinkExample.java @@ -0,0 +1,54 @@ +package com.baeldung.symlink; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import static java.nio.file.StandardOpenOption.*; +import java.util.stream.IntStream; + +public class SymLinkExample { + + public void createSymbolicLink(Path link, Path target) throws IOException { + if (Files.exists(link)) { + Files.delete(link); + } + Files.createSymbolicLink(link, target); + } + + public void createHardLink(Path link, Path target) throws IOException { + if (Files.exists(link)) { + Files.delete(link); + } + Files.createLink(link, target); + } + + public Path createTextFile() throws IOException { + byte[] content = IntStream.range(0, 10000) + .mapToObj(i -> i + System.lineSeparator()) + .reduce("", String::concat) + .getBytes(StandardCharsets.UTF_8); + Path filePath = Paths.get(".", "target_link.txt"); + Files.write(filePath, content, CREATE, TRUNCATE_EXISTING); + return filePath; + } + + public void printLinkFiles(Path path) throws IOException { + try (DirectoryStream stream = Files.newDirectoryStream(path)) { + for (Path file : stream) { + if (Files.isDirectory(file)) { + printLinkFiles(file); + } else if (Files.isSymbolicLink(file)) { + System.out.format("File link '%s' with target '%s'%n", file, Files.readSymbolicLink(file)); + } + } + } + } + + public static void main(String[] args) throws IOException { + new SymLinkExample().printLinkFiles(Paths.get(".")); + } + +} diff --git a/core-java-io/src/main/resources/logback.xml b/core-java-io/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/core-java-io/src/main/resources/logback.xml +++ b/core-java-io/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierIntegrationTest.java b/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierIntegrationTest.java new file mode 100644 index 0000000000..4603644bf5 --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierIntegrationTest.java @@ -0,0 +1,69 @@ +package com.baeldung.copyfiles; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; + +import org.apache.commons.io.FileUtils; +import org.junit.Before; +import org.junit.Test; +import static org.assertj.core.api.Assertions.*; + +public class FileCopierIntegrationTest { + File original = new File("src/test/resources/original.txt"); + + @Before + public void init() throws IOException { + if (!original.exists()) + Files.createFile(original.toPath()); + } + + @Test + public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException { + File copied = new File("src/test/resources/copiedWithIo.txt"); + try (InputStream in = new BufferedInputStream(new FileInputStream(original)); OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) { + byte[] buffer = new byte[1024]; + int lengthRead; + while ((lengthRead = in.read(buffer)) > 0) { + out.write(buffer, 0, lengthRead); + out.flush(); + } + } + assertThat(copied).exists(); + assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); + } + + @Test + public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException { + File copied = new File("src/test/resources/copiedWithApacheCommons.txt"); + FileUtils.copyFile(original, copied); + assertThat(copied).exists(); + assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); + } + + @Test + public void givenNIO2_whenCopied_thenCopyExistsWithSameContents() throws IOException { + Path copied = Paths.get("src/test/resources/copiedWithNio.txt"); + Path originalPath = original.toPath(); + Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING); + assertThat(copied).exists(); + assertThat(Files.readAllLines(originalPath).equals(Files.readAllLines(copied))); + } + + @Test + public void givenGuava_whenCopied_thenCopyExistsWithSameContents() throws IOException { + File copied = new File("src/test/resources/copiedWithApacheCommons.txt"); + com.google.common.io.Files.copy(original, copied); + assertThat(copied).exists(); + assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); + } +} diff --git a/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierTest.java b/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierTest.java deleted file mode 100644 index 6d96d2fc0b..0000000000 --- a/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.copyfiles; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; - -import org.apache.commons.io.FileUtils; -import org.junit.Before; -import org.junit.Test; -import static org.assertj.core.api.Assertions.*; - -public class FileCopierTest { - File original = new File("src/test/resources/original.txt"); - - @Before - public void init() throws IOException { - if (!original.exists()) - Files.createFile(original.toPath()); - } - - @Test - public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException { - File copied = new File("src/test/resources/copiedWithIo.txt"); - try (InputStream in = new BufferedInputStream(new FileInputStream(original)); OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) { - byte[] buffer = new byte[1024]; - int lengthRead; - while ((lengthRead = in.read(buffer)) > 0) { - out.write(buffer, 0, lengthRead); - out.flush(); - } - } - assertThat(copied).exists(); - assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); - } - - @Test - public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException { - File copied = new File("src/test/resources/copiedWithApacheCommons.txt"); - FileUtils.copyFile(original, copied); - assertThat(copied).exists(); - assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); - } - - @Test - public void givenNIO2_whenCopied_thenCopyExistsWithSameContents() throws IOException { - Path copied = Paths.get("src/test/resources/copiedWithNio.txt"); - Path originalPath = original.toPath(); - Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING); - assertThat(copied).exists(); - assertThat(Files.readAllLines(originalPath).equals(Files.readAllLines(copied))); - } - - @Test - public void givenGuava_whenCopied_thenCopyExistsWithSameContents() throws IOException { - File copied = new File("src/test/resources/copiedWithApacheCommons.txt"); - com.google.common.io.Files.copy(original, copied); - assertThat(copied).exists(); - assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); - } -} diff --git a/core-java-io/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java b/core-java-io/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java new file mode 100644 index 0000000000..81ac391958 --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java @@ -0,0 +1,91 @@ +package com.baeldung.download; + +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.concurrent.ExecutionException; + +import javax.xml.bind.DatatypeConverter; + +import org.junit.After; +import org.junit.BeforeClass; +import org.junit.Test; + +public class FileDownloadIntegrationTest { + + static String FILE_URL = "http://ovh.net/files/1Mio.dat"; + static String FILE_NAME = "file.dat"; + static String FILE_MD5_HASH = "6cb91af4ed4c60c11613b75cd1fc6116"; + + @Test + public void givenJavaIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException { + + FileDownload.downloadWithJavaIO(FILE_URL, FILE_NAME); + assertTrue(checkMd5Hash(FILE_NAME)); + } + + @Test + public void givenJavaNIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException { + + FileDownload.downloadWithJavaNIO(FILE_URL, FILE_NAME); + assertTrue(checkMd5Hash(FILE_NAME)); + } + + @Test + public void givenJava7IO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException { + + FileDownload.downloadWithJava7IO(FILE_URL, FILE_NAME); + assertTrue(checkMd5Hash(FILE_NAME)); + } + + @Test + public void givenAHCLibrary_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException, ExecutionException, InterruptedException { + + FileDownload.downloadWithAHC(FILE_URL, FILE_NAME); + assertTrue(checkMd5Hash(FILE_NAME)); + } + + @Test + public void givenApacheCommonsIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException { + + FileDownload.downloadWithApacheCommons(FILE_URL, FILE_NAME); + assertTrue(checkMd5Hash(FILE_NAME)); + } + + @Test + public void givenJavaIO_whenDownloadingFileStops_thenDownloadShouldBeResumedCorrectly() throws NoSuchAlgorithmException, IOException, URISyntaxException { + + ResumableDownload.downloadFileWithResume(FILE_URL, FILE_NAME); + assertTrue(checkMd5Hash(FILE_NAME)); + } + + private boolean checkMd5Hash(String filename) throws IOException, NoSuchAlgorithmException { + + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(Files.readAllBytes(Paths.get(filename))); + byte[] digest = md.digest(); + String myChecksum = DatatypeConverter.printHexBinary(digest); + + return myChecksum.equalsIgnoreCase(FILE_MD5_HASH); + } + + @BeforeClass + public static void setup() throws IOException { + if (Files.exists(Paths.get(FILE_NAME))) { + Files.delete(Paths.get(FILE_NAME)); + } + } + + @After + public void cleanup() throws IOException { + if (Files.exists(Paths.get(FILE_NAME))) { + Files.delete(Paths.get(FILE_NAME)); + } + } +} diff --git a/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java b/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java new file mode 100644 index 0000000000..f9a2ce972d --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java @@ -0,0 +1,48 @@ +package com.baeldung.file; + +import java.io.File; +import java.io.FilenameFilter; +import java.util.Arrays; +import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +public class FilenameFilterManualTest { + + private static File directory; + + @BeforeClass + public static void setupClass() { + directory = new File(FilenameFilterManualTest.class.getClassLoader() + .getResource("fileNameFilterManualTestFolder") + .getFile()); + } + + @Test + public void whenFilteringFilesEndingWithJson_thenEqualExpectedFiles() { + FilenameFilter filter = (dir, name) -> name.endsWith(".json"); + + String[] expectedFiles = { "people.json", "students.json" }; + String[] actualFiles = directory.list(filter); + + Assert.assertArrayEquals(expectedFiles, actualFiles); + } + + @Test + public void whenFilteringFilesEndingWithXml_thenEqualExpectedFiles() { + Predicate predicate = (name) -> name.endsWith(".xml"); + + String[] expectedFiles = { "teachers.xml", "workers.xml" }; + List files = Arrays.stream(directory.list()) + .filter(predicate) + .collect(Collectors.toList()); + String[] actualFiles = files.toArray(new String[files.size()]); + + Assert.assertArrayEquals(expectedFiles, actualFiles); + } + +} diff --git a/core-java-io/src/test/java/com/baeldung/file/FilesManualTest.java b/core-java-io/src/test/java/com/baeldung/file/FilesManualTest.java new file mode 100644 index 0000000000..f5c5c3dd3a --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/file/FilesManualTest.java @@ -0,0 +1,82 @@ +package com.baeldung.file; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; + +import com.google.common.base.Charsets; +import com.google.common.io.CharSink; +import com.google.common.io.FileWriteMode; +import org.apache.commons.io.FileUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.util.StreamUtils; + +public class FilesManualTest { + + public static final String fileName = "src/main/resources/countries.properties"; + + @Before + @After + public void setup() throws Exception { + PrintWriter writer = new PrintWriter(fileName); + writer.print("UK\r\n" + "US\r\n" + "Germany\r\n"); + writer.close(); + } + + @Test + public void whenAppendToFileUsingGuava_thenCorrect() throws IOException { + File file = new File(fileName); + CharSink chs = com.google.common.io.Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND); + chs.write("Spain\r\n"); + + assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); + } + + @Test + public void whenAppendToFileUsingFiles_thenCorrect() throws IOException { + Files.write(Paths.get(fileName), "Spain\r\n".getBytes(), StandardOpenOption.APPEND); + + assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); + } + + @Test + public void whenAppendToFileUsingFileUtils_thenCorrect() throws IOException { + File file = new File(fileName); + FileUtils.writeStringToFile(file, "Spain\r\n", StandardCharsets.UTF_8, true); + + assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); + } + + @Test + public void whenAppendToFileUsingFileOutputStream_thenCorrect() throws Exception { + FileOutputStream fos = new FileOutputStream(fileName, true); + fos.write("Spain\r\n".getBytes()); + fos.close(); + + assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); + } + + @Test + public void whenAppendToFileUsingFileWriter_thenCorrect() throws IOException { + FileWriter fw = new FileWriter(fileName, true); + BufferedWriter bw = new BufferedWriter(fw); + bw.write("Spain"); + bw.newLine(); + bw.close(); + + assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); + } +} \ No newline at end of file diff --git a/core-java-io/src/test/java/com/baeldung/file/FilesTest.java b/core-java-io/src/test/java/com/baeldung/file/FilesTest.java deleted file mode 100644 index a35cda8b23..0000000000 --- a/core-java-io/src/test/java/com/baeldung/file/FilesTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.baeldung.file; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.nio.file.StandardOpenOption; - -import com.google.common.base.Charsets; -import com.google.common.io.CharSink; -import com.google.common.io.FileWriteMode; -import org.apache.commons.io.FileUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.util.StreamUtils; - -public class FilesTest { - - public static final String fileName = "src/main/resources/countries.properties"; - - @Before - @After - public void setup() throws Exception { - PrintWriter writer = new PrintWriter(fileName); - writer.print("UK\r\n" + "US\r\n" + "Germany\r\n"); - writer.close(); - } - - @Test - public void whenAppendToFileUsingGuava_thenCorrect() throws IOException { - File file = new File(fileName); - CharSink chs = com.google.common.io.Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND); - chs.write("Spain\r\n"); - - assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); - } - - @Test - public void whenAppendToFileUsingFiles_thenCorrect() throws IOException { - Files.write(Paths.get(fileName), "Spain\r\n".getBytes(), StandardOpenOption.APPEND); - - assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); - } - - @Test - public void whenAppendToFileUsingFileUtils_thenCorrect() throws IOException { - File file = new File(fileName); - FileUtils.writeStringToFile(file, "Spain\r\n", StandardCharsets.UTF_8, true); - - assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); - } - - @Test - public void whenAppendToFileUsingFileOutputStream_thenCorrect() throws Exception { - FileOutputStream fos = new FileOutputStream(fileName, true); - fos.write("Spain\r\n".getBytes()); - fos.close(); - - assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); - } - - @Test - public void whenAppendToFileUsingFileWriter_thenCorrect() throws IOException { - FileWriter fw = new FileWriter(fileName, true); - BufferedWriter bw = new BufferedWriter(fw); - bw.write("Spain"); - bw.newLine(); - bw.close(); - - assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n"); - } -} \ No newline at end of file diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java new file mode 100644 index 0000000000..78f900d796 --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class BufferedReaderUnitTest { + + protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetArrayList() throws IOException { + List lines = BufferedReaderExample.generateArrayListFromFile(TEXT_FILENAME); + assertTrue("File does not has 2 lines", lines.size() == 2); + } +} diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java new file mode 100644 index 0000000000..a38e58d348 --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class FileReaderUnitTest { + + protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetArrayList() throws IOException { + List lines = FileReaderExample.generateArrayListFromFile(TEXT_FILENAME); + assertTrue("File does not has 2 lines", lines.size() == 2); + } +} diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java new file mode 100644 index 0000000000..c0b742fd47 --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class FilesReadAllLinesUnitTest { + + protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetArrayList() throws IOException { + List lines = FilesReadLinesExample.generateArrayListFromFile(TEXT_FILENAME); + assertTrue("File does not has 2 lines", lines.size() == 2); + } +} diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java new file mode 100644 index 0000000000..0a398ba7c6 --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class ScannerIntUnitTest { + + protected static final String NUMBER_FILENAME = "src/test/resources/sampleNumberFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetIntArrayList() throws IOException { + List numbers = ScannerIntExample.generateArrayListFromFile(NUMBER_FILENAME); + assertTrue("File does not has 2 lines", numbers.size() == 2); + } +} diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java new file mode 100644 index 0000000000..8f9b0a56c0 --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class ScannerStringUnitTest { + + protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetArrayList() throws IOException { + List lines = ScannerStringExample.generateArrayListFromFile(TEXT_FILENAME); + assertTrue("File does not has 2 lines", lines.size() == 2); + } +} diff --git a/core-java-io/src/test/java/com/baeldung/symlink/SymLinkExampleUnitTest.java b/core-java-io/src/test/java/com/baeldung/symlink/SymLinkExampleUnitTest.java new file mode 100644 index 0000000000..803d8881b4 --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/symlink/SymLinkExampleUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.symlink; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import org.junit.Test; + +public class SymLinkExampleUnitTest { + + @Test + public void whenUsingFiles_thenCreateSymbolicLink() throws IOException { + SymLinkExample example = new SymLinkExample(); + Path filePath = example.createTextFile(); + Path linkPath = Paths.get(".", "symbolic_link.txt"); + example.createSymbolicLink(linkPath, filePath); + assertTrue(Files.isSymbolicLink(linkPath)); + } + + @Test + public void whenUsingFiles_thenCreateHardLink() throws IOException { + SymLinkExample example = new SymLinkExample(); + Path filePath = example.createTextFile(); + Path linkPath = Paths.get(".", "hard_link.txt"); + example.createHardLink(linkPath, filePath); + assertFalse(Files.isSymbolicLink(linkPath)); + assertEquals(filePath.toFile() + .length(), + linkPath.toFile() + .length()); + } + +} diff --git a/core-java-io/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java b/core-java-io/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java index f1bea1eefb..c49681efb8 100644 --- a/core-java-io/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java +++ b/core-java-io/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java @@ -14,8 +14,10 @@ import org.slf4j.LoggerFactory; import java.io.*; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.Scanner; +import java.util.UUID; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.hamcrest.Matchers.equalTo; @@ -111,6 +113,19 @@ public class JavaInputStreamToXUnitTest { assertThat(writer.toString(), equalTo(originalString)); } + + @Test + public final void givenUsingTempFile_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException { + final String originalString = randomAlphabetic(DEFAULT_SIZE); + final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes()); + + // When + Path tempFile = java.nio.file.Files.createTempDirectory("").resolve(UUID.randomUUID().toString() + ".tmp"); + java.nio.file.Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING); + String result = new String(java.nio.file.Files.readAllBytes(tempFile)); + + assertThat(result, equalTo(originalString)); + } // tests - InputStream to byte[] diff --git a/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java b/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java index b56841117e..a96232d66c 100644 --- a/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java +++ b/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java @@ -1,6 +1,7 @@ package org.baeldung.java.io; import org.junit.Test; +import org.junit.Ignore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -105,8 +106,9 @@ public class JavaReadFromFileUnitTest { } @Test + @Ignore // TODO public void whenReadUTFEncodedFile_thenCorrect() throws IOException { - final String expected_value = "�空"; + final String expected_value = "é’空"; final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8")); final String currentLine = reader.readLine(); reader.close(); diff --git a/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java b/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java index 08a4c673cd..6604d75ed1 100644 --- a/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java +++ b/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java @@ -1,10 +1,12 @@ package org.baeldung.java.io; import java.io.ByteArrayInputStream; +import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; +import java.io.SequenceInputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; @@ -74,6 +76,28 @@ public class JavaXToInputStreamUnitTest { IOUtils.closeQuietly(targetStream); } + @Test + public final void givenUsingPlainJava_whenConvertingFileToDataInputStream_thenCorrect() throws IOException { + final File initialFile = new File("src/test/resources/sample.txt"); + final InputStream targetStream = new DataInputStream(new FileInputStream(initialFile)); + + IOUtils.closeQuietly(targetStream); + } + + @Test + public final void givenUsingPlainJava_whenConvertingFileToSequenceInputStream_thenCorrect() throws IOException { + final File initialFile = new File("src/test/resources/sample.txt"); + final File anotherFile = new File("src/test/resources/anothersample.txt"); + final InputStream targetStream = new FileInputStream(initialFile); + final InputStream anotherTargetStream = new FileInputStream(anotherFile); + + InputStream sequenceTargetStream = new SequenceInputStream(targetStream, anotherTargetStream); + + IOUtils.closeQuietly(targetStream); + IOUtils.closeQuietly(anotherTargetStream); + IOUtils.closeQuietly(sequenceTargetStream); + } + @Test public final void givenUsingGuava_whenConvertingFileToInputStream_thenCorrect() throws IOException { final File initialFile = new File("src/test/resources/sample.txt"); diff --git a/core-java-io/src/test/resources/anothersample.txt b/core-java-io/src/test/resources/anothersample.txt new file mode 100644 index 0000000000..f06f18ce02 --- /dev/null +++ b/core-java-io/src/test/resources/anothersample.txt @@ -0,0 +1 @@ +...Continues \ No newline at end of file diff --git a/core-java-io/src/test/resources/fileNameFilterManualTestFolder/people.json b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/people.json new file mode 100644 index 0000000000..9e26dfeeb6 --- /dev/null +++ b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/people.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/core-java-io/src/test/resources/fileNameFilterManualTestFolder/students.json b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/students.json new file mode 100644 index 0000000000..9e26dfeeb6 --- /dev/null +++ b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/students.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/core-java-io/src/test/resources/fileNameFilterManualTestFolder/teachers.xml b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/teachers.xml new file mode 100644 index 0000000000..19b16cc72c --- /dev/null +++ b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/teachers.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/core-java-io/src/test/resources/fileNameFilterManualTestFolder/workers.xml b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/workers.xml new file mode 100644 index 0000000000..19b16cc72c --- /dev/null +++ b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/workers.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/core-java-io/src/test/resources/sampleNumberFile.txt b/core-java-io/src/test/resources/sampleNumberFile.txt new file mode 100644 index 0000000000..7787faa3c1 --- /dev/null +++ b/core-java-io/src/test/resources/sampleNumberFile.txt @@ -0,0 +1,2 @@ +111 +222 \ No newline at end of file diff --git a/core-java-io/src/test/resources/sampleTextFile.txt b/core-java-io/src/test/resources/sampleTextFile.txt new file mode 100644 index 0000000000..75cb50aafa --- /dev/null +++ b/core-java-io/src/test/resources/sampleTextFile.txt @@ -0,0 +1,2 @@ +Hello +World \ No newline at end of file diff --git a/core-java-persistence/README.md b/core-java-persistence/README.md new file mode 100644 index 0000000000..ca0ce81eef --- /dev/null +++ b/core-java-persistence/README.md @@ -0,0 +1,9 @@ +========= + +## Core Java Persistence Examples + +### Relevant Articles: +- [Introduction to JDBC](http://www.baeldung.com/java-jdbc) +- [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing) +- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset) +- [A Simple Guide to Connection Pooling in Java](https://www.baeldung.com/java-connection-pooling) diff --git a/core-java-persistence/pom.xml b/core-java-persistence/pom.xml new file mode 100644 index 0000000000..7279fd763b --- /dev/null +++ b/core-java-persistence/pom.xml @@ -0,0 +1,71 @@ + + 4.0.0 + com.baeldung.core-java-persistence + core-java-persistence + 0.1.0-SNAPSHOT + jar + core-java-persistence + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + com.h2database + h2 + ${h2database.version} + + + org.apache.commons + commons-dbcp2 + ${commons-dbcp2.version} + + + com.zaxxer + HikariCP + ${HikariCP.version} + + + com.mchange + c3p0 + ${c3p0.version} + + + org.springframework + spring-web + ${springframework.spring-web.version} + + + org.springframework.boot + spring-boot-starter + ${springframework.boot.spring-boot-starter.version} + + + + core-java-persistence + + + src/main/resources + true + + + + + 3.10.0 + 1.4.197 + 2.4.0 + 3.2.0 + 0.9.5.2 + 1.5.8.RELEASE + 4.3.4.RELEASE + + \ No newline at end of file diff --git a/core-java-persistence/src/main/java/com/baeldung/connectionpool/BasicConnectionPool.java b/core-java-persistence/src/main/java/com/baeldung/connectionpool/BasicConnectionPool.java new file mode 100644 index 0000000000..289db18c53 --- /dev/null +++ b/core-java-persistence/src/main/java/com/baeldung/connectionpool/BasicConnectionPool.java @@ -0,0 +1,92 @@ +package com.baeldung.connectionpool; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +public class BasicConnectionPool implements ConnectionPool { + + private final String url; + private final String user; + private final String password; + private final List connectionPool; + private final List usedConnections = new ArrayList<>(); + private static final int INITIAL_POOL_SIZE = 10; + private final int MAX_POOL_SIZE = 20; + + public static BasicConnectionPool create(String url, String user, String password) throws SQLException { + List pool = new ArrayList<>(INITIAL_POOL_SIZE); + for (int i = 0; i < INITIAL_POOL_SIZE; i++) { + pool.add(createConnection(url, user, password)); + } + return new BasicConnectionPool(url, user, password, pool); + } + + private BasicConnectionPool(String url, String user, String password, List connectionPool) { + this.url = url; + this.user = user; + this.password = password; + this.connectionPool = connectionPool; + } + + @Override + public Connection getConnection() throws SQLException { + if (connectionPool.isEmpty()) { + if (usedConnections.size() < MAX_POOL_SIZE) { + connectionPool.add(createConnection(url, user, password)); + } else { + throw new RuntimeException("Maximum pool size reached, no available connections!"); + } + } + + Connection connection = connectionPool.remove(connectionPool.size() - 1); + usedConnections.add(connection); + return connection; + } + + @Override + public boolean releaseConnection(Connection connection) { + connectionPool.add(connection); + return usedConnections.remove(connection); + } + + private static Connection createConnection(String url, String user, String password) throws SQLException { + return DriverManager.getConnection(url, user, password); + } + + @Override + public int getSize() { + return connectionPool.size() + usedConnections.size(); + } + + @Override + public List getConnectionPool() { + return connectionPool; + } + + @Override + public String getUrl() { + return url; + } + + @Override + public String getUser() { + return user; + } + + @Override + public String getPassword() { + return password; + } + + @Override + public void shutdown() throws SQLException { + usedConnections.forEach(this::releaseConnection); + for (Connection c : connectionPool) { + c.close(); + } + connectionPool.clear(); + } +} diff --git a/core-java-persistence/src/main/java/com/baeldung/connectionpool/C3poDataSource.java b/core-java-persistence/src/main/java/com/baeldung/connectionpool/C3poDataSource.java new file mode 100644 index 0000000000..78642459d5 --- /dev/null +++ b/core-java-persistence/src/main/java/com/baeldung/connectionpool/C3poDataSource.java @@ -0,0 +1,28 @@ +package com.baeldung.connectionpool; + +import com.mchange.v2.c3p0.ComboPooledDataSource; +import java.beans.PropertyVetoException; +import java.sql.Connection; +import java.sql.SQLException; + +public class C3poDataSource { + + private static final ComboPooledDataSource cpds = new ComboPooledDataSource(); + + static { + try { + cpds.setDriverClass("org.h2.Driver"); + cpds.setJdbcUrl("jdbc:h2:mem:test"); + cpds.setUser("user"); + cpds.setPassword("password"); + } catch (PropertyVetoException e) { + e.printStackTrace(); + } + } + + public static Connection getConnection() throws SQLException { + return cpds.getConnection(); + } + + private C3poDataSource(){} +} \ No newline at end of file diff --git a/core-java-persistence/src/main/java/com/baeldung/connectionpool/ConnectionPool.java b/core-java-persistence/src/main/java/com/baeldung/connectionpool/ConnectionPool.java new file mode 100644 index 0000000000..fa9355721b --- /dev/null +++ b/core-java-persistence/src/main/java/com/baeldung/connectionpool/ConnectionPool.java @@ -0,0 +1,24 @@ +package com.baeldung.connectionpool; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; + +public interface ConnectionPool { + + Connection getConnection() throws SQLException; + + boolean releaseConnection(Connection connection); + + List getConnectionPool(); + + int getSize(); + + String getUrl(); + + String getUser(); + + String getPassword(); + + void shutdown() throws SQLException;; +} \ No newline at end of file diff --git a/core-java-persistence/src/main/java/com/baeldung/connectionpool/DBCPDataSource.java b/core-java-persistence/src/main/java/com/baeldung/connectionpool/DBCPDataSource.java new file mode 100644 index 0000000000..1e33a08d46 --- /dev/null +++ b/core-java-persistence/src/main/java/com/baeldung/connectionpool/DBCPDataSource.java @@ -0,0 +1,25 @@ +package com.baeldung.connectionpool; + +import java.sql.Connection; +import java.sql.SQLException; +import org.apache.commons.dbcp2.BasicDataSource; + +public class DBCPDataSource { + + private static final BasicDataSource ds = new BasicDataSource(); + + static { + ds.setUrl("jdbc:h2:mem:test"); + ds.setUsername("user"); + ds.setPassword("password"); + ds.setMinIdle(5); + ds.setMaxIdle(10); + ds.setMaxOpenPreparedStatements(100); + } + + public static Connection getConnection() throws SQLException { + return ds.getConnection(); + } + + private DBCPDataSource(){} +} diff --git a/core-java-persistence/src/main/java/com/baeldung/connectionpool/HikariCPDataSource.java b/core-java-persistence/src/main/java/com/baeldung/connectionpool/HikariCPDataSource.java new file mode 100644 index 0000000000..cc0cc24520 --- /dev/null +++ b/core-java-persistence/src/main/java/com/baeldung/connectionpool/HikariCPDataSource.java @@ -0,0 +1,28 @@ +package com.baeldung.connectionpool; + +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; +import java.sql.Connection; +import java.sql.SQLException; + +public class HikariCPDataSource { + + private static final HikariConfig config = new HikariConfig(); + private static final HikariDataSource ds; + + static { + config.setJdbcUrl("jdbc:h2:mem:test"); + config.setUsername("user"); + config.setPassword("password"); + config.addDataSourceProperty("cachePrepStmts", "true"); + config.addDataSourceProperty("prepStmtCacheSize", "250"); + config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); + ds = new HikariDataSource(config); + } + + public static Connection getConnection() throws SQLException { + return ds.getConnection(); + } + + private HikariCPDataSource(){} +} diff --git a/core-java/src/main/java/com/baeldung/jdbc/BatchProcessing.java b/core-java-persistence/src/main/java/com/baeldung/jdbc/BatchProcessing.java similarity index 100% rename from core-java/src/main/java/com/baeldung/jdbc/BatchProcessing.java rename to core-java-persistence/src/main/java/com/baeldung/jdbc/BatchProcessing.java diff --git a/core-java/src/main/java/com/baeldung/jdbc/Employee.java b/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java similarity index 100% rename from core-java/src/main/java/com/baeldung/jdbc/Employee.java rename to core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java b/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java similarity index 100% rename from core-java/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java rename to core-java-persistence/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/ExampleListener.java b/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/ExampleListener.java similarity index 100% rename from core-java/src/main/java/com/baeldung/jdbcrowset/ExampleListener.java rename to core-java-persistence/src/main/java/com/baeldung/jdbcrowset/ExampleListener.java diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/FilterExample.java b/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/FilterExample.java similarity index 100% rename from core-java/src/main/java/com/baeldung/jdbcrowset/FilterExample.java rename to core-java-persistence/src/main/java/com/baeldung/jdbcrowset/FilterExample.java diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java b/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java similarity index 100% rename from core-java/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java rename to core-java-persistence/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java diff --git a/core-java-persistence/src/main/resources/logback.xml b/core-java-persistence/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/core-java-persistence/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/core-java-persistence/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java b/core-java-persistence/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java new file mode 100644 index 0000000000..479cd0db25 --- /dev/null +++ b/core-java-persistence/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java @@ -0,0 +1,67 @@ +package com.baeldung.connectionpool; + +import java.sql.Connection; +import java.sql.SQLException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.BeforeClass; +import org.junit.Test; + +public class BasicConnectionPoolUnitTest { + + private static ConnectionPool connectionPool; + + @BeforeClass + public static void setUpBasicConnectionPoolInstance() throws SQLException { + connectionPool = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password"); + } + + @Test + public void givenBasicConnectionPoolInstance_whenCalledgetConnection_thenCorrect() throws Exception { + assertTrue(connectionPool.getConnection().isValid(1)); + } + + @Test + public void givenBasicConnectionPoolInstance_whenCalledreleaseConnection_thenCorrect() throws Exception { + Connection connection = connectionPool.getConnection(); + assertThat(connectionPool.releaseConnection(connection)).isTrue(); + } + + @Test + public void givenBasicConnectionPoolInstance_whenCalledgetUrl_thenCorrect() { + assertThat(connectionPool.getUrl()).isEqualTo("jdbc:h2:mem:test"); + } + + @Test + public void givenBasicConnectionPoolInstance_whenCalledgetUser_thenCorrect() { + assertThat(connectionPool.getUser()).isEqualTo("user"); + } + + @Test + public void givenBasicConnectionPoolInstance_whenCalledgetPassword_thenCorrect() { + assertThat(connectionPool.getPassword()).isEqualTo("password"); + } + + @Test(expected = RuntimeException.class) + public void givenBasicConnectionPoolInstance_whenAskedForMoreThanMax_thenError() throws Exception { + // this test needs to be independent so it doesn't share the same connection pool as other tests + ConnectionPool cp = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password"); + final int MAX_POOL_SIZE = 20; + for (int i = 0; i < MAX_POOL_SIZE + 1; i++) { + cp.getConnection(); + } + fail(); + } + + @Test + public void givenBasicConnectionPoolInstance_whenSutdown_thenEmpty() throws Exception { + ConnectionPool cp = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password"); + assertThat(((BasicConnectionPool)cp).getSize()).isEqualTo(10); + + ((BasicConnectionPool) cp).shutdown(); + assertThat(((BasicConnectionPool)cp).getSize()).isEqualTo(0); + } +} diff --git a/core-java-persistence/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java b/core-java-persistence/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java new file mode 100644 index 0000000000..a07fa9e74b --- /dev/null +++ b/core-java-persistence/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java @@ -0,0 +1,13 @@ +package com.baeldung.connectionpool; + +import java.sql.SQLException; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class C3poDataSourceUnitTest { + + @Test + public void givenC3poDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException { + assertTrue(C3poDataSource.getConnection().isValid(1)); + } +} \ No newline at end of file diff --git a/core-java-persistence/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java b/core-java-persistence/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java new file mode 100644 index 0000000000..43aaf330b6 --- /dev/null +++ b/core-java-persistence/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java @@ -0,0 +1,13 @@ +package com.baeldung.connectionpool; + +import java.sql.SQLException; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class DBCPDataSourceUnitTest { + + @Test + public void givenDBCPDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException { + assertTrue(DBCPDataSource.getConnection().isValid(1)); + } +} \ No newline at end of file diff --git a/core-java-persistence/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java b/core-java-persistence/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java new file mode 100644 index 0000000000..b20ce70efd --- /dev/null +++ b/core-java-persistence/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java @@ -0,0 +1,13 @@ +package com.baeldung.connectionpool; + +import java.sql.SQLException; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class HikariCPDataSourceUnitTest { + + @Test + public void givenHikariDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException { + assertTrue(HikariCPDataSource.getConnection().isValid(1)); + } +} \ No newline at end of file diff --git a/core-java-persistence/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java b/core-java-persistence/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java new file mode 100644 index 0000000000..c905482f55 --- /dev/null +++ b/core-java-persistence/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java @@ -0,0 +1,71 @@ +package com.baeldung.jdbc; + + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.Statement; + +@RunWith(MockitoJUnitRunner.class) +public class BatchProcessingLiveTest { + + + @InjectMocks + private BatchProcessing target = new BatchProcessing(); + + @Mock + private Connection connection; + + @Mock + private Statement statement; + + @Mock + private PreparedStatement employeeStatement; + + @Mock + private PreparedStatement employeeAddressStatement; + + @Before + public void before(){ + MockitoAnnotations.initMocks(this); + } + + + @Test + public void when_useStatement_thenInsertData_success() throws Exception { + Mockito.when(connection.createStatement()).thenReturn(statement); + target.useStatement(); + } + + @Test + public void when_useStatement_ifThrowException_thenCatchException() throws Exception { + Mockito.when(connection.createStatement()).thenThrow(new RuntimeException()); + target.useStatement(); + } + + @Test + public void when_usePreparedStatement_thenInsertData_success() throws Exception { + String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES (?,?,?);"; + String insertEmployeeAddrSQL = "INSERT INTO EMP_ADDRESS(ID, EMP_ID, ADDRESS) VALUES (?,?,?);"; + Mockito.when(connection.prepareStatement(insertEmployeeSQL)).thenReturn(employeeStatement); + Mockito.when(connection.prepareStatement(insertEmployeeAddrSQL)).thenReturn(employeeAddressStatement); + target.usePreparedStatement(); + } + + @Test + public void when_usePreparedStatement_ifThrowException_thenCatchException() throws Exception { + String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES (?,?,?);"; + String insertEmployeeAddrSQL = "INSERT INTO EMP_ADDRESS(ID, EMP_ID, ADDRESS) VALUES (?,?,?);"; + Mockito.when(connection.prepareStatement(insertEmployeeSQL)).thenReturn(employeeStatement); + Mockito.when(connection.prepareStatement(insertEmployeeAddrSQL)).thenThrow(new RuntimeException()); + target.usePreparedStatement(); + } +} diff --git a/core-java/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java b/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java rename to core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java diff --git a/core-java-persistence/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java b/core-java-persistence/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java new file mode 100644 index 0000000000..ebfb4df102 --- /dev/null +++ b/core-java-persistence/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java @@ -0,0 +1,157 @@ +package com.baeldung.jdbcrowset; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; + +import javax.sql.rowset.CachedRowSet; +import javax.sql.rowset.FilteredRowSet; +import javax.sql.rowset.JdbcRowSet; +import javax.sql.rowset.JoinRowSet; +import javax.sql.rowset.RowSetFactory; +import javax.sql.rowset.RowSetProvider; +import javax.sql.rowset.WebRowSet; + +import org.junit.Before; +import org.junit.Test; + +import com.sun.rowset.CachedRowSetImpl; +import com.sun.rowset.JdbcRowSetImpl; +import com.sun.rowset.JoinRowSetImpl; +import com.sun.rowset.WebRowSetImpl; + +public class JdbcRowSetLiveTest { + Statement stmt = null; + String username = "sa"; + String password = ""; + String url = "jdbc:h2:mem:testdb"; + String sql = "SELECT * FROM customers"; + + @Before + public void setup() throws Exception { + Connection conn = DatabaseConfiguration.geth2Connection(); + + String drop = "DROP TABLE IF EXISTS customers, associates;"; + String schema = "CREATE TABLE customers (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id)); "; + String schemapartb = "CREATE TABLE associates (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id));"; + stmt = conn.createStatement(); + stmt.executeUpdate(drop); + stmt.executeUpdate(schema); + stmt.executeUpdate(schemapartb); + DatabaseConfiguration.initDatabase(stmt); + + } + + // JdbcRowSet Example + @Test + public void createJdbcRowSet_SelectCustomers_ThenCorrect() throws Exception { + + String sql = "SELECT * FROM customers"; + JdbcRowSet jdbcRS; + Connection conn = DatabaseConfiguration.geth2Connection(); + jdbcRS = new JdbcRowSetImpl(conn); + jdbcRS.setType(ResultSet.TYPE_SCROLL_INSENSITIVE); + jdbcRS.setCommand(sql); + jdbcRS.execute(); + jdbcRS.addRowSetListener(new ExampleListener()); + + while (jdbcRS.next()) { + // each call to next, generates a cursorMoved event + System.out.println("id=" + jdbcRS.getString(1)); + System.out.println("name=" + jdbcRS.getString(2)); + } + + } + + // CachedRowSet Example + @Test + public void createCachedRowSet_DeleteRecord_ThenCorrect() throws Exception { + + CachedRowSet crs = new CachedRowSetImpl(); + crs.setUsername(username); + crs.setPassword(password); + crs.setUrl(url); + crs.setCommand(sql); + crs.execute(); + crs.addRowSetListener(new ExampleListener()); + while (crs.next()) { + if (crs.getInt("id") == 1) { + System.out.println("CRS found customer1 and will remove the record."); + crs.deleteRow(); + break; + } + } + } + + // WebRowSet example + @Test + public void createWebRowSet_SelectCustomers_WritetoXML_ThenCorrect() throws SQLException, IOException { + + WebRowSet wrs = new WebRowSetImpl(); + wrs.setUsername(username); + wrs.setPassword(password); + wrs.setUrl(url); + wrs.setCommand(sql); + wrs.execute(); + FileOutputStream ostream = new FileOutputStream("customers.xml"); + wrs.writeXml(ostream); + } + + // JoinRowSet example + @Test + public void createCachedRowSets_DoJoinRowSet_ThenCorrect() throws Exception { + + CachedRowSetImpl customers = new CachedRowSetImpl(); + customers.setUsername(username); + customers.setPassword(password); + customers.setUrl(url); + customers.setCommand(sql); + customers.execute(); + + CachedRowSetImpl associates = new CachedRowSetImpl(); + associates.setUsername(username); + associates.setPassword(password); + associates.setUrl(url); + String associatesSQL = "SELECT * FROM associates"; + associates.setCommand(associatesSQL); + associates.execute(); + + JoinRowSet jrs = new JoinRowSetImpl(); + final String ID = "id"; + final String NAME = "name"; + jrs.addRowSet(customers, ID); + jrs.addRowSet(associates, ID); + jrs.last(); + System.out.println("Total rows: " + jrs.getRow()); + jrs.beforeFirst(); + while (jrs.next()) { + + String string1 = jrs.getString(ID); + String string2 = jrs.getString(NAME); + System.out.println("ID: " + string1 + ", NAME: " + string2); + } + } + + // FilteredRowSet example + @Test + public void createFilteredRowSet_filterByRegexExpression_thenCorrect() throws Exception { + RowSetFactory rsf = RowSetProvider.newFactory(); + FilteredRowSet frs = rsf.createFilteredRowSet(); + frs.setCommand("select * from customers"); + Connection conn = DatabaseConfiguration.geth2Connection(); + frs.execute(conn); + frs.setFilter(new FilterExample("^[A-C].*")); + + ResultSetMetaData rsmd = frs.getMetaData(); + int columncount = rsmd.getColumnCount(); + while (frs.next()) { + for (int i = 1; i <= columncount; i++) { + System.out.println(rsmd.getColumnLabel(i) + " = " + frs.getObject(i) + " "); + } + } + } +} diff --git a/core-java-sun/pom.xml b/core-java-sun/pom.xml index 3fd8e80296..57d5e9da5b 100644 --- a/core-java-sun/pom.xml +++ b/core-java-sun/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 com.baeldung core-java-sun @@ -9,8 +10,8 @@ com.baeldung parent-java - 0.0.1-SNAPSHOT - ../parent-java + 0.0.1-SNAPSHOT + ../parent-java @@ -73,23 +74,6 @@ log4j ${log4j.version} - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - org.slf4j log4j-over-slf4j @@ -102,42 +86,12 @@ provided - - org.hamcrest - hamcrest-all - ${hamcrest-all.version} - test - - - junit - junit - ${junit.version} - test - - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - org.assertj assertj-core ${assertj.version} test - - org.mockito - mockito-core - ${mockito.version} - test - com.jayway.awaitility awaitility @@ -212,25 +166,10 @@ - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - prepare-package - - copy-dependencies - - - ${project.build.directory}/libs - - - - org.apache.maven.plugins maven-jar-plugin + ${maven-jar-plugin.version} @@ -241,79 +180,6 @@ - - org.apache.maven.plugins - maven-assembly-plugin - - - package - - single - - - ${project.basedir} - - - org.baeldung.executable.ExecutableMavenJar - - - - jar-with-dependencies - - - - - - - org.apache.maven.plugins - maven-shade-plugin - - - - shade - - - true - - - org.baeldung.executable.ExecutableMavenJar - - - - - - - - com.jolira - onejar-maven-plugin - - - - org.baeldung.executable.ExecutableMavenJar - true - ${project.build.finalName}-onejar.${project.packaging} - - - one-jar - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - spring-boot - org.baeldung.executable.ExecutableMavenJar - - - - org.codehaus.mojo exec-maven-plugin @@ -325,7 +191,7 @@ -Xmx300m -XX:+UseParallelGC -classpath - + com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed @@ -353,6 +219,7 @@ **/*IntegrationTest.java + **/*IntTest.java @@ -380,7 +247,7 @@ java -classpath - + org.openjdk.jmh.Main .* @@ -397,10 +264,6 @@ 2.8.5 - - 1.7.21 - 1.1.7 - 23.0 3.5 @@ -408,7 +271,6 @@ 1.10 3.6.1 1.0.3 - 2.5 4.1 4.01 0.4 @@ -418,18 +280,16 @@ 1.13 0.6.5 0.9.0 + 4.3.4.RELEASE - 1.3 - 2.8.9 3.6.1 1.7.0 - 3.7.0 - 2.19.1 + 2.21.0 1.8.0 - 4.3.4.RELEASE + 3.0.2 \ No newline at end of file diff --git a/core-java-sun/src/main/resources/logback.xml b/core-java-sun/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/core-java-sun/src/main/resources/logback.xml +++ b/core-java-sun/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/core-java/README.md b/core-java/README.md index cc3097006c..ade7f46504 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -3,19 +3,14 @@ ## Core Java Cookbooks and Examples ### Relevant Articles: -- [Java – Random Long, Float, Integer and Double](http://www.baeldung.com/java-generate-random-long-float-integer-double) -- [Java – Generate Random String](http://www.baeldung.com/java-random-string) - [Java Timer](http://www.baeldung.com/java-timer-and-timertask) - [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java) - [MD5 Hashing in Java](http://www.baeldung.com/java-md5) - [Guide to Java Reflection](http://www.baeldung.com/java-reflection) - [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) -- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) -- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) - [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources) - [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join) - [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java) -- [How to Convert String to different data types in Java](http://www.baeldung.com/java-string-conversions) - [Introduction to Java Generics](http://www.baeldung.com/java-generics) - [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode) - [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java) @@ -38,9 +33,6 @@ - [A Quick JUnit vs TestNG Comparison](http://www.baeldung.com/junit-vs-testng) - [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions) - [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency) -- [Using Math.pow in Java](http://www.baeldung.com/java-math-pow) -- [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum) -- [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer) - [JVM Log Forging](http://www.baeldung.com/jvm-log-forging) - [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe) - [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request) @@ -49,52 +41,39 @@ - [How to Add a Single Element to a Stream](http://www.baeldung.com/java-stream-append-prepend) - [Iterating Over Enum Values in Java](http://www.baeldung.com/java-enum-iteration) - [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability) -- [How to Round a Number to N Decimal Places in Java](http://www.baeldung.com/java-round-decimal-number) - [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params) - [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null) - [Changing the Order in a Sum Operation Can Produce Different Results?](http://www.baeldung.com/java-floating-point-sum-order) - [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method) - [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies) - [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy) -- [Introduction to JDBC](http://www.baeldung.com/java-jdbc) -- [Period and Duration in Java](http://www.baeldung.com/java-period-duration) - [Converting a Stack Trace to a String in Java](http://www.baeldung.com/java-stacktrace-to-string) -- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars) - [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization) - [The StackOverflowError in Java](http://www.baeldung.com/java-stack-overflow-error) -- [Split a String in Java](http://www.baeldung.com/java-split-string) - [Introduction to Java Serialization](http://www.baeldung.com/java-serialization) -- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string) - [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) - [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) -- [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) - [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator) - [“Sneaky Throws†in Java](http://www.baeldung.com/java-sneaky-throws) - [OutOfMemoryError: GC Overhead Limit Exceeded](http://www.baeldung.com/java-gc-overhead-limit-exceeded) -- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer) -- [Number of Digits in an Integer in Java](http://www.baeldung.com/java-number-of-digits-in-int) - [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin) - [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static) - [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array) -- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool) - [Quick Example - Comparator vs Comparable in Java](http://www.baeldung.com/java-comparator-comparable) - [Quick Guide to Java Stack](http://www.baeldung.com/java-stack) - [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break) - [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter) -- [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing) - [Check if a Java Array Contains a Value](http://www.baeldung.com/java-array-contains-value) - [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array) - [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class) - [A Guide to Java Initialization](http://www.baeldung.com/java-initialization) - [Implementing a Binary Tree in Java](http://www.baeldung.com/java-binary-tree) - [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random) -- [RegEx for matching Date Pattern in Java](http://www.baeldung.com/java-date-regular-expressions) -- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset) - [Nested Classes in Java](http://www.baeldung.com/java-nested-classes) - [A Guide to Java Loops](http://www.baeldung.com/java-loops) - [Varargs in Java](http://www.baeldung.com/java-varargs) @@ -109,16 +88,12 @@ - [The Trie Data Structure in Java](http://www.baeldung.com/trie-java) - [Introduction to Javadoc](http://www.baeldung.com/javadoc) - [How to Make a Deep Copy of an Object in Java](http://www.baeldung.com/java-deep-copy) -- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome) -- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings) - [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance) - [Guide to Externalizable Interface in Java](http://www.baeldung.com/java-externalizable) - [Object Type Casting in Java](http://www.baeldung.com/java-type-casting) - [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat) - [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os) - [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java) -- [An Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced) -- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings) - [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition) - [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max) - [The "final" Keyword in Java](http://www.baeldung.com/java-final) @@ -132,12 +107,47 @@ - [Find Sum and Average in a Java Array](http://www.baeldung.com/java-array-sum-average) - [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception) - [Type Erasure in Java Explained](http://www.baeldung.com/java-type-erasure) -- [BigDecimal and BigInteger in Java](http://www.baeldung.com/java-bigdecimal-biginteger) -- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones) - [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split) - [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality) - [Sending Emails with Java](http://www.baeldung.com/java-email) - [Introduction to SSL in Java](http://www.baeldung.com/java-ssl) - [Java KeyStore API](http://www.baeldung.com/java-keystore) -- [Using Java Assertions](http://www.baeldung.com/java-assert) +- [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking) - [Guide to Java Clock Class](http://www.baeldung.com/java-clock) +- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java) +- [Using Java Assertions](http://www.baeldung.com/java-assert) +- [Pass-By-Value as a Parameter Passing Mechanism in Java](http://www.baeldung.com/java-pass-by-value-or-pass-by-reference) +- [Variable and Method Hiding in Java](http://www.baeldung.com/java-variable-method-hiding) +- [Access Modifiers in Java](http://www.baeldung.com/java-access-modifiers) +- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java) +- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns) +- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns) +- [Singletons in Java](http://www.baeldung.com/java-singleton) +- [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight) +- [The Observer Pattern in Java](http://www.baeldung.com/java-observer-pattern) +- [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern) +- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join) +- [Guide to the super Java Keyword](http://www.baeldung.com/java-super) +- [Guide to the this Java Keyword](http://www.baeldung.com/java-this) +- [Jagged Arrays In Java](http://www.baeldung.com/java-jagged-arrays) +- [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class) +- [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension) +- [Immutable Objects in Java](http://www.baeldung.com/java-immutable-object) +- [Console I/O in Java](http://www.baeldung.com/java-console-input-output) +- [Guide to the java.util.Arrays Class](http://www.baeldung.com/java-util-arrays) +- [Create a Custom Exception in Java](http://www.baeldung.com/java-new-custom-exception) +- [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler) +- [Encrypting and Decrypting Files in Java](http://www.baeldung.com/java-cipher-input-output-stream) +- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object) +- [Exception Handling in Java](http://www.baeldung.com/java-exceptions) +- [Guide to Java Instrumentation](http://www.baeldung.com/java-instrumentation) +- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type) +- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions) +- [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods) +- [Differences Between Final, Finally and Finalize in Java](https://www.baeldung.com/java-final-finally-finalize) +- [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding) +- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line) +- [Difference Between Throw and Throws in Java](https://www.baeldung.com/java-throw-throws) +- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist) +- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception) +- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string) diff --git a/core-java/pom.xml b/core-java/pom.xml index 88fae5edea..477a01375d 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -10,8 +10,8 @@ com.baeldung parent-java - 0.0.1-SNAPSHOT - ../parent-java + 0.0.1-SNAPSHOT + ../parent-java @@ -25,16 +25,6 @@ commons-lang3 ${commons-lang3.version} - - org.apache.commons - commons-math3 - ${commons-math3.version} - - - org.decimal4j - decimal4j - ${decimal4j.version} - org.bouncycastle bcprov-jdk15on @@ -68,23 +58,6 @@ log4j ${log4j.version} - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - org.slf4j log4j-over-slf4j @@ -97,42 +70,13 @@ provided - - org.hamcrest - hamcrest-all - ${hamcrest-all.version} - test - - - junit - junit - ${junit.version} - test - - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - org.assertj assertj-core - ${assertj.version} - test - - - org.mockito - mockito-core - ${mockito.version} + ${assertj-core.version} test + commons-codec commons-codec @@ -183,11 +127,6 @@ spring-web ${springframework.spring-web.version} - - org.springframework.boot - spring-boot-starter - ${springframework.boot.spring-boot-starter.version} - com.h2database h2 @@ -198,6 +137,30 @@ mail ${javax.mail.version} + + + org.apache.tika + tika-core + ${tika.version} + + + net.sf.jmimemagic + jmimemagic + ${jmime-magic.version} + + + + org.javassist + javassist + ${javaassist.version} + + + com.sun + tools + 1.8.0 + system + ${java.home}/../lib/tools.jar + @@ -217,6 +180,7 @@ **/*LiveTest.java **/*IntegrationTest.java + **/*IntTest.java **/*LongRunningUnitTest.java **/*ManualTest.java @@ -244,6 +208,7 @@ org.apache.maven.plugins maven-jar-plugin + ${maven-jar-plugin.version} @@ -282,6 +247,7 @@ org.apache.maven.plugins maven-shade-plugin + ${maven-shade-plugin.version} @@ -290,8 +256,7 @@ true - + org.baeldung.executable.ExecutableMavenJar @@ -303,6 +268,7 @@ com.jolira onejar-maven-plugin + ${onejar-maven-plugin.version} @@ -320,6 +286,7 @@ org.springframework.boot spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} @@ -344,12 +311,12 @@ -Xmx300m -XX:+UseParallelGC -classpath - + com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed - + org.apache.maven.plugins maven-javadoc-plugin @@ -382,6 +349,7 @@ **/*IntegrationTest.java + **/*IntTest.java @@ -395,7 +363,7 @@ org.codehaus.mojo exec-maven-plugin - + ${exec-maven-plugin.version} run-benchmarks @@ -409,7 +377,7 @@ java -classpath - + org.openjdk.jmh.Main .* @@ -420,25 +388,126 @@ + + + + buildAgentLoader + + + + org.apache.maven.plugins + maven-jar-plugin + + + package + + jar + + + agentLoader + target/classes + + + true + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + com/baeldung/instrumentation/application/AgentLoader.class + com/baeldung/instrumentation/application/Launcher.class + + + + + + + + + + buildApplication + + + + org.apache.maven.plugins + maven-jar-plugin + + + package + + jar + + + application + target/classes + + + true + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + com/baeldung/instrumentation/application/MyAtm.class + com/baeldung/instrumentation/application/MyAtmApplication.class + com/baeldung/instrumentation/application/Launcher.class + + + + + + + + + + buildAgent + + + + org.apache.maven.plugins + maven-jar-plugin + + + package + + jar + + + agent + target/classes + + + true + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + com/baeldung/instrumentation/agent/AtmTransformer.class + com/baeldung/instrumentation/agent/MyInstrumentationAgent.class + + + + + + + + + 2.8.5 2.8.2 - - 1.7.21 - 1.1.7 - 1.2.17 - 3.5 1.55 1.10 + 2.5 3.6.1 1.0.3 - 2.5 0.4 1.8.7 1.16.12 @@ -448,24 +517,31 @@ 0.9.0 - 1.3 - 2.8.9 - 3.6.1 + 3.10.0 - 3.7.0 - 2.19.1 + 2.21.0 4.3.4.RELEASE - 1.5.8.RELEASE + 1.1 - 1.3 1.4.197 2.1.0.1 1.19 + 1.19 3.0.0-M1 - 1.6.0 1.5.0-b01 + 3.0.2 + 1.4.4 + 3.1.1 + 2.0.3.RELEASE + 1.6.0 + 61.1 + + 1.18 + 0.1.5 + + 3.21.0-GA - \ No newline at end of file + diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/Public.java b/core-java/src/main/java/com/baeldung/accessmodifiers/Public.java new file mode 100644 index 0000000000..9a64c1d4c4 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/accessmodifiers/Public.java @@ -0,0 +1,9 @@ +package com.baeldung.accessmodifiers; + +public class Public { + public Public() { + SuperPublic.publicMethod(); // Available everywhere. + SuperPublic.protectedMethod(); // Available in the same package or subclass. + SuperPublic.defaultMethod(); // Available in the same package. + } +} diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/SubClass.java b/core-java/src/main/java/com/baeldung/accessmodifiers/SubClass.java new file mode 100644 index 0000000000..545f48c9ca --- /dev/null +++ b/core-java/src/main/java/com/baeldung/accessmodifiers/SubClass.java @@ -0,0 +1,9 @@ +package com.baeldung.accessmodifiers; + +public class SubClass extends SuperPublic { + public SubClass() { + SuperPublic.publicMethod(); // Available everywhere. + SuperPublic.protectedMethod(); // Available in the same package or subclass. + SuperPublic.defaultMethod(); // Available in the same package. + } +} diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java b/core-java/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java new file mode 100644 index 0000000000..7c9554f2c7 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java @@ -0,0 +1,39 @@ +package com.baeldung.accessmodifiers; + +//Only public or default access modifiers are permitted +public class SuperPublic { + // Always available from anywhere + static public void publicMethod() { + System.out.println(SuperPublic.class.getName() + " publicMethod()"); + } + + // Available within the same package + static void defaultMethod() { + System.out.println(SuperPublic.class.getName() + " defaultMethod()"); + } + + // Available within the same package and subclasses + static protected void protectedMethod() { + System.out.println(SuperPublic.class.getName() + " protectedMethod()"); + } + + // Available within the same class only + static private void privateMethod() { + System.out.println(SuperPublic.class.getName() + " privateMethod()"); + } + + // Method in the same class = has access to all members within the same class + private void anotherPrivateMethod() { + privateMethod(); + defaultMethod(); + protectedMethod(); + publicMethod(); // Available in the same class only. + } +} + +// Only public or default access modifiers are permitted +class SuperDefault { + public void publicMethod() { + System.out.println(this.getClass().getName() + " publicMethod()"); + } +} diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java new file mode 100644 index 0000000000..32eea36854 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java @@ -0,0 +1,9 @@ +package com.baeldung.accessmodifiers.another; + +import com.baeldung.accessmodifiers.SuperPublic; + +public class AnotherPublic { + public AnotherPublic() { + SuperPublic.publicMethod(); // Available everywhere. + } +} diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java new file mode 100644 index 0000000000..3d9dc3f119 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java @@ -0,0 +1,10 @@ +package com.baeldung.accessmodifiers.another; + +import com.baeldung.accessmodifiers.SuperPublic; + +public class AnotherSubClass extends SuperPublic { + public AnotherSubClass() { + SuperPublic.publicMethod(); // Available everywhere. + SuperPublic.protectedMethod(); // Available in subclass. Let's note different package. + } +} diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java new file mode 100644 index 0000000000..3932e6f990 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java @@ -0,0 +1,9 @@ +package com.baeldung.accessmodifiers.another; + +import com.baeldung.accessmodifiers.SuperPublic; + +public class AnotherSuperPublic { + public AnotherSuperPublic() { + SuperPublic.publicMethod(); // Available everywhere. Let's note different package. + } +} diff --git a/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java b/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java index 977587a06a..f35064b783 100644 --- a/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java +++ b/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java @@ -9,7 +9,7 @@ public class ArrayBenchmarkRunner { public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() - .include(SearchArrayTest.class.getSimpleName()).threads(1) + .include(SearchArrayUnitTest.class.getSimpleName()).threads(1) .forks(1).shouldFailOnError(true).shouldDoGC(true) .jvmArgs("-server").build(); diff --git a/core-java/src/main/java/com/baeldung/array/JaggedArray.java b/core-java/src/main/java/com/baeldung/array/JaggedArray.java new file mode 100644 index 0000000000..36cfc88b95 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/array/JaggedArray.java @@ -0,0 +1,49 @@ +package com.baeldung.array; + +import java.util.Arrays; +import java.util.Scanner; + +public class JaggedArray { + + int[][] shortHandFormInitialization() { + int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + return jaggedArr; + } + + int[][] declarationAndThenInitialization() { + int[][] jaggedArr = new int[3][]; + jaggedArr[0] = new int[] { 1, 2 }; + jaggedArr[1] = new int[] { 3, 4, 5 }; + jaggedArr[2] = new int[] { 6, 7, 8, 9 }; + return jaggedArr; + } + + int[][] declarationAndThenInitializationUsingUserInputs() { + int[][] jaggedArr = new int[3][]; + jaggedArr[0] = new int[2]; + jaggedArr[1] = new int[3]; + jaggedArr[2] = new int[4]; + initializeElements(jaggedArr); + return jaggedArr; + } + + void initializeElements(int[][] jaggedArr) { + Scanner sc = new Scanner(System.in); + for (int outer = 0; outer < jaggedArr.length; outer++) { + for (int inner = 0; inner < jaggedArr[outer].length; inner++) { + jaggedArr[outer][inner] = sc.nextInt(); + } + } + } + + void printElements(int[][] jaggedArr) { + for (int index = 0; index < jaggedArr.length; index++) { + System.out.println(Arrays.toString(jaggedArr[index])); + } + } + + int[] getElementAtGivenIndex(int[][] jaggedArr, int index) { + return jaggedArr[index]; + } + +} diff --git a/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java b/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java deleted file mode 100644 index 199ebdf036..0000000000 --- a/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.baeldung.array; - -import org.openjdk.jmh.annotations.*; - -import java.util.*; -import java.util.concurrent.TimeUnit; - -@BenchmarkMode(Mode.AverageTime) -@Warmup(iterations = 5) -@OutputTimeUnit(TimeUnit.MICROSECONDS) -public class SearchArrayTest { - - @State(Scope.Benchmark) - public static class SearchData { - static int count = 1000; - static String[] strings = seedArray(1000); - } - - - @Benchmark - public void searchArrayLoop() { - for (int i = 0; i < SearchData.count; i++) { - searchLoop(SearchData.strings, "T"); - } - } - - @Benchmark - public void searchArrayAllocNewList() { - for (int i = 0; i < SearchData.count; i++) { - searchList(SearchData.strings, "T"); - } - - } - - @Benchmark - public void searchArrayAllocNewSet() { - for (int i = 0; i < SearchData.count; i++) { - searchSet(SearchData.strings, "T"); - } - } - - - @Benchmark - public void searchArrayReuseList() { - List asList = Arrays.asList(SearchData.strings); - for (int i = 0; i < SearchData.count; i++) { - asList.contains("T"); - } - } - - - @Benchmark - public void searchArrayReuseSet() { - Set asSet = new HashSet<>(Arrays.asList(SearchData.strings)); - for (int i = 0; i < SearchData.count; i++) { - asSet.contains("T"); - } - } - - - @Benchmark - public void searchArrayBinarySearch() { - Arrays.sort(SearchData.strings); - for (int i = 0; i < SearchData.count; i++) { - Arrays.binarySearch(SearchData.strings, "T"); - } - } - - private boolean searchList(String[] strings, String searchString) { - return Arrays.asList(strings).contains(searchString); - } - - private boolean searchSet(String[] strings, String searchString) { - Set set = new HashSet<>(Arrays.asList(strings)); - return set.contains(searchString); - } - - private boolean searchLoop(String[] strings, String searchString) { - for (String s : strings) { - if (s.equals(searchString)) - return true; - } - return false; - } - - private static String[] seedArray(int length) { - String[] strings = new String[length]; - Random random = new Random(); - for (int i = 0; i < length; i++) - { - strings[i] = String.valueOf(random.nextInt()); - } - return strings; - } - -} diff --git a/core-java/src/main/java/com/baeldung/array/SearchArrayUnitTest.java b/core-java/src/main/java/com/baeldung/array/SearchArrayUnitTest.java new file mode 100644 index 0000000000..bed58356cb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/array/SearchArrayUnitTest.java @@ -0,0 +1,96 @@ +package com.baeldung.array; + +import org.openjdk.jmh.annotations.*; + +import java.util.*; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@Warmup(iterations = 5) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +public class SearchArrayUnitTest { + + @State(Scope.Benchmark) + public static class SearchData { + static int count = 1000; + static String[] strings = seedArray(1000); + } + + + @Benchmark + public void searchArrayLoop() { + for (int i = 0; i < SearchData.count; i++) { + searchLoop(SearchData.strings, "T"); + } + } + + @Benchmark + public void searchArrayAllocNewList() { + for (int i = 0; i < SearchData.count; i++) { + searchList(SearchData.strings, "T"); + } + + } + + @Benchmark + public void searchArrayAllocNewSet() { + for (int i = 0; i < SearchData.count; i++) { + searchSet(SearchData.strings, "T"); + } + } + + + @Benchmark + public void searchArrayReuseList() { + List asList = Arrays.asList(SearchData.strings); + for (int i = 0; i < SearchData.count; i++) { + asList.contains("T"); + } + } + + + @Benchmark + public void searchArrayReuseSet() { + Set asSet = new HashSet<>(Arrays.asList(SearchData.strings)); + for (int i = 0; i < SearchData.count; i++) { + asSet.contains("T"); + } + } + + + @Benchmark + public void searchArrayBinarySearch() { + Arrays.sort(SearchData.strings); + for (int i = 0; i < SearchData.count; i++) { + Arrays.binarySearch(SearchData.strings, "T"); + } + } + + private boolean searchList(String[] strings, String searchString) { + return Arrays.asList(strings).contains(searchString); + } + + private boolean searchSet(String[] strings, String searchString) { + Set set = new HashSet<>(Arrays.asList(strings)); + return set.contains(searchString); + } + + private boolean searchLoop(String[] strings, String searchString) { + for (String s : strings) { + if (s.equals(searchString)) + return true; + } + return false; + } + + private static String[] seedArray(int length) { + String[] strings = new String[length]; + Random random = new Random(); + for (int i = 0; i < length; i++) + { + strings[i] = String.valueOf(random.nextInt()); + } + return strings; + } + +} diff --git a/core-java/src/main/java/com/baeldung/binding/Animal.java b/core-java/src/main/java/com/baeldung/binding/Animal.java new file mode 100644 index 0000000000..12eaa2a7a3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/binding/Animal.java @@ -0,0 +1,23 @@ +package com.baeldung.binding; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Created by madhumita.g on 25-07-2018. + */ +public class Animal { + + final static Logger logger = LoggerFactory.getLogger(Animal.class); + + public void makeNoise() { + logger.info("generic animal noise"); + } + + public void makeNoise(Integer repetitions) { + while(repetitions != 0) { + logger.info("generic animal noise countdown " + repetitions); + repetitions -= 1; + } + } +} diff --git a/core-java/src/main/java/com/baeldung/binding/AnimalActivity.java b/core-java/src/main/java/com/baeldung/binding/AnimalActivity.java new file mode 100644 index 0000000000..1bd36123e3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/binding/AnimalActivity.java @@ -0,0 +1,43 @@ +package com.baeldung.binding; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Created by madhumita.g on 25-07-2018. + */ +public class AnimalActivity { + + final static Logger logger = LoggerFactory.getLogger(AnimalActivity.class); + + + public static void sleep(Animal animal) { + logger.info("Animal is sleeping"); + } + + public static void sleep(Cat cat) { + logger.info("Cat is sleeping"); + } + + public static void main(String[] args) { + + Animal animal = new Animal(); + + //calling methods of animal object + animal.makeNoise(); + + animal.makeNoise(3); + + + //assigning a dog object to reference of type Animal + Animal catAnimal = new Cat(); + + catAnimal.makeNoise(); + + // calling static function + AnimalActivity.sleep(catAnimal); + + return; + + } +} diff --git a/core-java/src/main/java/com/baeldung/binding/Cat.java b/core-java/src/main/java/com/baeldung/binding/Cat.java new file mode 100644 index 0000000000..bbe740e412 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/binding/Cat.java @@ -0,0 +1,18 @@ +package com.baeldung.binding; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Created by madhumita.g on 25-07-2018. + */ +public class Cat extends Animal { + + final static Logger logger = LoggerFactory.getLogger(Cat.class); + + public void makeNoise() { + + logger.info("meow"); + } + +} diff --git a/core-java/src/main/java/com/baeldung/classcastexception/ClassCastException.java b/core-java/src/main/java/com/baeldung/classcastexception/ClassCastException.java new file mode 100644 index 0000000000..26e5bf0c6b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/classcastexception/ClassCastException.java @@ -0,0 +1,21 @@ +package com.baeldung.classcastexception; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class ClassCastException { + + public static void main(String[] args) { + + String p1 = new String("John"); + String p2 = new String("Snow"); + String[] strArray = new String[] { p1, p2 }; + ArrayList strList = (ArrayList) Arrays.asList(strArray); + // To fix the ClassCastException at above line, modify the code as: + // List strList = Arrays.asList(strArray); + System.out.println("String list: " + strList); + + } + +} diff --git a/core-java/src/main/java/com/baeldung/console/ConsoleConsoleClass.java b/core-java/src/main/java/com/baeldung/console/ConsoleConsoleClass.java new file mode 100644 index 0000000000..a5c704345f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/console/ConsoleConsoleClass.java @@ -0,0 +1,26 @@ +package com.baeldung.console; + +import java.io.Console; + +public class ConsoleConsoleClass { + + public static void main(String[] args) { + Console console = System.console(); + + if (console == null) { + System.out.print("No console available"); + return; + } + + String progLanguauge = console.readLine("Enter your favourite programming language: "); + console.printf(progLanguauge + " is very interesting!"); + + char[] pass = console.readPassword("To finish, enter password: "); + + if ("BAELDUNG".equals(pass.toString().toUpperCase())) + console.printf("Good! Regards!"); + else + console.printf("Nice try. Regards."); + + } +} diff --git a/core-java/src/main/java/com/baeldung/console/ConsoleScannerClass.java b/core-java/src/main/java/com/baeldung/console/ConsoleScannerClass.java new file mode 100644 index 0000000000..7b7a7a4ade --- /dev/null +++ b/core-java/src/main/java/com/baeldung/console/ConsoleScannerClass.java @@ -0,0 +1,76 @@ +package com.baeldung.console; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Scanner; +import java.util.regex.Pattern; + +public class ConsoleScannerClass { + + public static void main(String[] args) { + System.out.println("Please enter your name and surname: "); + + Scanner scanner = new Scanner(System.in); + + String nameSurname = scanner.nextLine(); + + System.out.println("Please enter your gender: "); + + char gender = scanner.next().charAt(0); + + System.out.println("Please enter your age: "); + + int age = scanner.nextInt(); + + System.out.println("Please enter your height in meters: "); + + double height = scanner.nextDouble(); + + System.out.println(nameSurname + ", " + age + ", is a great " + (gender == 'm' ? "guy" : "girl") + " with " + height + " meters height" + " and " + (gender == 'm' ? "he" : "she") + " reads Baeldung."); + + System.out.print("Have a good"); + System.out.print(" one!"); + + System.out.println("\nPlease enter number of years of experience as a developer: "); + + BufferedReader buffReader = new BufferedReader(new InputStreamReader(System.in)); + + int i = 0; + + try { + i = Integer.parseInt(buffReader.readLine()); + } catch (NumberFormatException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + System.out.println("You are a " + (i > 5 ? "great" : "good") + " developer!"); + + int sum = 0, count = 0; + + System.out.println("Please enter your college degrees. To finish, enter baeldung website url"); + + while (scanner.hasNextInt()) { + int nmbr = scanner.nextInt(); + sum += nmbr; + count++; + } + int mean = sum / count; + + System.out.println("Your average degree is " + mean); + + if (scanner.hasNext(Pattern.compile("www.baeldung.com"))) + System.out.println("Correct!"); + else + System.out.println("Baeldung website url is www.baeldung.com"); + + if (scanner != null) + scanner.close(); + + } + +} diff --git a/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/application/Application.java b/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/application/Application.java new file mode 100644 index 0000000000..d19772072f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/application/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.constructorsstaticfactorymethods.application; + +import com.baeldung.constructorsstaticfactorymethods.entities.User; + +public class Application { + + public static void main(String[] args) { + User user1 = User.createWithDefaultCountry("John", "john@domain.com"); + User user2 = User.createWithLoggedInstantiationTime("John", "john@domain.com", "Argentina"); + User user3 = User.getSingletonInstance("John", "john@domain.com", "Argentina"); + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java b/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java new file mode 100644 index 0000000000..4036b622c6 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java @@ -0,0 +1,63 @@ +package com.baeldung.constructorsstaticfactorymethods.entities; + +import java.time.LocalTime; +import java.util.logging.ConsoleHandler; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.logging.SimpleFormatter; + +public class User { + + private static volatile User instance = null; + private static final Logger LOGGER = Logger.getLogger(User.class.getName()); + private final String name; + private final String email; + private final String country; + + public static User createWithDefaultCountry(String name, String email) { + return new User(name, email, "Argentina"); + } + + public static User createWithLoggedInstantiationTime(String name, String email, String country) { + setLoggerProperties(); + LOGGER.log(Level.INFO, "Creating User instance at : {0}", LocalTime.now()); + return new User(name, email, country); + } + + public static User getSingletonInstance(String name, String email, String country) { + if (instance == null) { + synchronized (User.class) { + if (instance == null) { + instance = new User(name, email, country); + } + } + } + return instance; + + } + + private User(String name, String email, String country) { + this.name = name; + this.email = email; + this.country = country; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + public String getCountry() { + return country; + } + + private static void setLoggerProperties() { + ConsoleHandler handler = new ConsoleHandler(); + handler.setLevel(Level.INFO); + handler.setFormatter(new SimpleFormatter()); + LOGGER.addHandler(handler); + } +} diff --git a/core-java/src/main/java/com/baeldung/customexception/FileManager.java b/core-java/src/main/java/com/baeldung/customexception/FileManager.java new file mode 100644 index 0000000000..b6f4d960aa --- /dev/null +++ b/core-java/src/main/java/com/baeldung/customexception/FileManager.java @@ -0,0 +1,43 @@ +package com.baeldung.customexception; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.Scanner; + +public class FileManager { + + public static String getFirstLine(String fileName) throws IncorrectFileNameException { + try (Scanner file = new Scanner(new File(fileName))) { + if (file.hasNextLine()) { + return file.nextLine(); + } else { + throw new IllegalArgumentException("Non readable file"); + } + } catch (FileNotFoundException err) { + if (!isCorrectFileName(fileName)) { + throw new IncorrectFileNameException("Incorrect filename : " + fileName, err); + } + // Logging etc + } catch (IllegalArgumentException err) { + if (!containsExtension(fileName)) { + throw new IncorrectFileExtensionException("Filename does not contain extension : " + fileName, err); + } + // Other error cases and logging + } + return "Default First Line"; + } + + private static boolean containsExtension(String fileName) { + if (fileName.contains(".txt") || fileName.contains(".doc")) + return true; + return false; + } + + private static boolean isCorrectFileName(String fileName) { + if (fileName.equals("wrongFileName.txt")) + return false; + else + return true; + } + +} diff --git a/core-java/src/main/java/com/baeldung/customexception/IncorrectFileExtensionException.java b/core-java/src/main/java/com/baeldung/customexception/IncorrectFileExtensionException.java new file mode 100644 index 0000000000..c6dc6d6964 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/customexception/IncorrectFileExtensionException.java @@ -0,0 +1,9 @@ +package com.baeldung.customexception; + +public class IncorrectFileExtensionException extends RuntimeException{ + private static final long serialVersionUID = 1L; + + public IncorrectFileExtensionException(String errorMessage, Throwable err) { + super(errorMessage, err); + } +} diff --git a/core-java/src/main/java/com/baeldung/customexception/IncorrectFileNameException.java b/core-java/src/main/java/com/baeldung/customexception/IncorrectFileNameException.java new file mode 100644 index 0000000000..a804cadb84 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/customexception/IncorrectFileNameException.java @@ -0,0 +1,9 @@ +package com.baeldung.customexception; + +public class IncorrectFileNameException extends Exception { + private static final long serialVersionUID = 1L; + + public IncorrectFileNameException(String errorMessage, Throwable err) { + super(errorMessage, err); + } +} diff --git a/core-java/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/core-java/src/main/java/com/baeldung/datetime/UseLocalDateTime.java deleted file mode 100644 index 7f39ac2f91..0000000000 --- a/core-java/src/main/java/com/baeldung/datetime/UseLocalDateTime.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.datetime; - -import java.time.LocalDateTime; - -public class UseLocalDateTime { - - public LocalDateTime getLocalDateTimeUsingParseMethod(String representation) { - return LocalDateTime.parse(representation); - } - -} diff --git a/core-java/src/main/java/com/baeldung/decimalformat/DoubletoString.java b/core-java/src/main/java/com/baeldung/decimalformat/DoubletoString.java new file mode 100644 index 0000000000..87d10a3548 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/decimalformat/DoubletoString.java @@ -0,0 +1,38 @@ +package com.baeldung.decimalformat; + + import java.math.RoundingMode; + import java.text.DecimalFormat; + import java.text.NumberFormat; + import java.util.Locale; + + public class DoubletoString { + + public static void main(String[] args) { + + double doubleValue = 345.56; + + System.out.println(String.valueOf((int) doubleValue)); + + System.out.println(String.format("%.0f", doubleValue)); + + doubleValue = Math.floor(doubleValue); + DecimalFormat df = new DecimalFormat("#"); + df.setRoundingMode(RoundingMode.FLOOR); + System.out.println(df.format(doubleValue)); + + Locale enlocale = new Locale("en", "US"); + String pattern = "###,##"; + df = (DecimalFormat) NumberFormat.getNumberInstance(enlocale); + df.applyPattern(pattern); + String format = df.format(doubleValue); + System.out.println(format); + + Locale dalocale = new Locale("da", "DK"); + df = (DecimalFormat) NumberFormat.getNumberInstance(dalocale); + df.applyPattern(pattern); + System.out.println(df.format(doubleValue)); + + + } + + } diff --git a/core-java/src/main/java/com/baeldung/encrypt/FileEncrypterDecrypter.java b/core-java/src/main/java/com/baeldung/encrypt/FileEncrypterDecrypter.java new file mode 100644 index 0000000000..b557ccf31a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/encrypt/FileEncrypterDecrypter.java @@ -0,0 +1,60 @@ +package com.baeldung.encrypt; + +import javax.crypto.*; +import javax.crypto.spec.IvParameterSpec; +import java.io.*; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; + +class FileEncrypterDecrypter { + + private SecretKey secretKey; + private Cipher cipher; + + FileEncrypterDecrypter(SecretKey secretKey, String cipher) throws NoSuchPaddingException, NoSuchAlgorithmException { + this.secretKey = secretKey; + this.cipher = Cipher.getInstance(cipher); + } + + void encrypt(String content, String fileName) throws InvalidKeyException, IOException { + cipher.init(Cipher.ENCRYPT_MODE, secretKey); + byte[] iv = cipher.getIV(); + + try ( + FileOutputStream fileOut = new FileOutputStream(fileName); + CipherOutputStream cipherOut = new CipherOutputStream(fileOut, cipher) + ) { + fileOut.write(iv); + cipherOut.write(content.getBytes()); + } + + } + + String decrypt(String fileName) throws InvalidAlgorithmParameterException, InvalidKeyException, IOException { + + String content; + + try (FileInputStream fileIn = new FileInputStream(fileName)) { + byte[] fileIv = new byte[16]; + fileIn.read(fileIv); + cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(fileIv)); + + try ( + CipherInputStream cipherIn = new CipherInputStream(fileIn, cipher); + InputStreamReader inputReader = new InputStreamReader(cipherIn); + BufferedReader reader = new BufferedReader(inputReader) + ) { + + StringBuilder sb = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + sb.append(line); + } + content = sb.toString(); + } + + } + return content; + } +} diff --git a/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java b/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java new file mode 100644 index 0000000000..9690648386 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java @@ -0,0 +1,212 @@ +package com.baeldung.exceptionhandling; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Scanner; +import java.util.logging.Logger; +import java.util.stream.Collectors; + +public class Exceptions { + + private final static Logger logger = Logger.getLogger("ExceptionLogging"); + + public static List getPlayers() throws IOException { + Path path = Paths.get("players.dat"); + List players = Files.readAllLines(path); + + return players.stream() + .map(Player::new) + .collect(Collectors.toList()); + } + + public List loadAllPlayers(String playersFile) throws IOException{ + try { + throw new IOException(); + } catch(IOException ex) { + throw new IllegalStateException(); + } + } + + public int getPlayerScoreThrows(String playerFile) throws FileNotFoundException { + Scanner contents = new Scanner(new File(playerFile)); + return Integer.parseInt(contents.nextLine()); + } + + public int getPlayerScoreTryCatch(String playerFile) { + try { + Scanner contents = new Scanner(new File(playerFile)); + return Integer.parseInt(contents.nextLine()); + } catch (FileNotFoundException noFile) { + throw new IllegalArgumentException("File not found"); + } + } + + public int getPlayerScoreTryCatchRecovery(String playerFile) { + try { + Scanner contents = new Scanner(new File(playerFile)); + return Integer.parseInt(contents.nextLine()); + } catch ( FileNotFoundException noFile ) { + logger.warning("File not found, resetting score."); + return 0; + } + } + + public int getPlayerScoreFinally(String playerFile) throws FileNotFoundException { + Scanner contents = null; + try { + contents = new Scanner(new File(playerFile)); + return Integer.parseInt(contents.nextLine()); + } finally { + if (contents != null) { + contents.close(); + } + } + } + + public int getPlayerScoreTryWithResources(String playerFile) { + try (Scanner contents = new Scanner(new File(playerFile))) { + return Integer.parseInt(contents.nextLine()); + } catch (FileNotFoundException e ) { + logger.warning("File not found, resetting score."); + return 0; + } + } + + public int getPlayerScoreMultipleCatchBlocks(String playerFile) { + try (Scanner contents = new Scanner(new File(playerFile))) { + return Integer.parseInt(contents.nextLine()); + } catch (IOException e) { + logger.warning("Player file wouldn't load!"); + return 0; + } catch (NumberFormatException e) { + logger.warning("Player file was corrupted!"); + return 0; + } + } + + public int getPlayerScoreMultipleCatchBlocksAlternative(String playerFile) { + try (Scanner contents = new Scanner(new File(playerFile)) ) { + return Integer.parseInt(contents.nextLine()); + } catch (FileNotFoundException e) { + logger.warning("Player file not found!"); + return 0; + } catch (IOException e) { + logger.warning("Player file wouldn't load!"); + return 0; + } catch (NumberFormatException e) { + logger.warning("Player file was corrupted!"); + return 0; + } + } + + public int getPlayerScoreUnionCatchBlocks(String playerFile) { + try (Scanner contents = new Scanner(new File(playerFile))) { + return Integer.parseInt(contents.nextLine()); + } catch (IOException | NumberFormatException e) { + logger.warning("Failed to load score!"); + return 0; + } + } + + public List loadAllPlayersThrowingChecked(String playersFile) throws TimeoutException { + boolean tooLong = true; + + while (!tooLong) { + // ... potentially long operation + } + throw new TimeoutException("This operation took too long"); + } + + public List loadAllPlayersThrowingUnchecked(String playersFile) throws TimeoutException { + if(!isFilenameValid(playersFile)) { + throw new IllegalArgumentException("Filename isn't valid!"); + } + return null; + + // ... + } + + public List loadAllPlayersWrapping(String playersFile) throws IOException { + try { + throw new IOException(); + } catch (IOException io) { + throw io; + } + } + + public List loadAllPlayersRethrowing(String playersFile) throws PlayerLoadException { + try { + throw new IOException(); + } catch (IOException io) { + throw new PlayerLoadException(io); + } + } + + public List loadAllPlayersThrowable(String playersFile) { + try { + throw new NullPointerException(); + } catch ( Throwable t ) { + throw t; + } + } + + class FewerExceptions extends Exceptions { + @Override + public List loadAllPlayers(String playersFile) { //can't add "throws MyCheckedException + return null; + // overridden + } + } + + public void throwAsGotoAntiPattern() throws MyException { + try { + // bunch of code + throw new MyException(); + // second bunch of code + } catch ( MyException e ) { + // third bunch of code + } + } + + public int getPlayerScoreSwallowingExceptionAntiPattern(String playerFile) { + try { + // ... + } catch (Exception e) {} // <== catch and swallow + return 0; + } + + public int getPlayerScoreSwallowingExceptionAntiPatternAlternative(String playerFile) { + try { + // ... + } catch (Exception e) { + e.printStackTrace(); + } + return 0; + } + + public int getPlayerScoreSwallowingExceptionAntiPatternAlternative2(String playerFile) throws PlayerScoreException { + try { + throw new IOException(); + } catch (IOException e) { + throw new PlayerScoreException(e); + } + } + + public int getPlayerScoreReturnInFinallyAntiPattern(String playerFile) { + int score = 0; + try { + throw new IOException(); + } finally { + return score; // <== the IOException is dropped + } + } + + private boolean isFilenameValid(String name) { + return false; + } +} diff --git a/core-java/src/main/java/com/baeldung/exceptionhandling/MyException.java b/core-java/src/main/java/com/baeldung/exceptionhandling/MyException.java new file mode 100644 index 0000000000..5a50acc4de --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptionhandling/MyException.java @@ -0,0 +1,5 @@ +package com.baeldung.exceptionhandling; + +public class MyException extends Throwable { + +} diff --git a/core-java/src/main/java/com/baeldung/exceptionhandling/Player.java b/core-java/src/main/java/com/baeldung/exceptionhandling/Player.java new file mode 100644 index 0000000000..4efd37134f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptionhandling/Player.java @@ -0,0 +1,12 @@ +package com.baeldung.exceptionhandling; + +public class Player { + + public int id; + public String name; + + public Player(String name) { + this.name = name; + } + +} diff --git a/core-java/src/main/java/com/baeldung/exceptionhandling/PlayerLoadException.java b/core-java/src/main/java/com/baeldung/exceptionhandling/PlayerLoadException.java new file mode 100644 index 0000000000..5302fd8e7d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptionhandling/PlayerLoadException.java @@ -0,0 +1,11 @@ +package com.baeldung.exceptionhandling; + +import java.io.IOException; + +public class PlayerLoadException extends Exception { + + public PlayerLoadException(IOException io) { + super(io); + } + +} diff --git a/core-java/src/main/java/com/baeldung/exceptionhandling/PlayerScoreException.java b/core-java/src/main/java/com/baeldung/exceptionhandling/PlayerScoreException.java new file mode 100644 index 0000000000..d11159217e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptionhandling/PlayerScoreException.java @@ -0,0 +1,8 @@ +package com.baeldung.exceptionhandling; + +public class PlayerScoreException extends Exception { + + public PlayerScoreException(Exception e) { + super(e); + } +} diff --git a/core-java/src/main/java/com/baeldung/exceptionhandling/TimeoutException.java b/core-java/src/main/java/com/baeldung/exceptionhandling/TimeoutException.java new file mode 100644 index 0000000000..294ad542d3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptionhandling/TimeoutException.java @@ -0,0 +1,8 @@ +package com.baeldung.exceptionhandling; + +public class TimeoutException extends Exception { + + public TimeoutException(String message) { + super(message); + } +} diff --git a/core-java/src/main/java/com/baeldung/exceptions/Arithmetic.java b/core-java/src/main/java/com/baeldung/exceptions/Arithmetic.java new file mode 100644 index 0000000000..138916ec60 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptions/Arithmetic.java @@ -0,0 +1,20 @@ +package com.baeldung.exceptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Arithmetic { + + private static Logger LOGGER = LoggerFactory.getLogger(Arithmetic.class); + + public static void main(String[] args) { + + try { + int result = 30 / 0; // Trying to divide by zero + } catch (ArithmeticException e) { + LOGGER.error("ArithmeticException caught!"); + } + + } + +} diff --git a/core-java/src/main/java/com/baeldung/exceptions/ArrayIndexOutOfBounds.java b/core-java/src/main/java/com/baeldung/exceptions/ArrayIndexOutOfBounds.java new file mode 100644 index 0000000000..93b53f284c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptions/ArrayIndexOutOfBounds.java @@ -0,0 +1,24 @@ +package com.baeldung.exceptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ArrayIndexOutOfBounds { + + private static Logger LOGGER = LoggerFactory.getLogger(ArrayIndexOutOfBounds.class); + + public static void main(String[] args) { + + int[] nums = new int[] { 1, 2, 3 }; + + try { + int numFromNegativeIndex = nums[-1]; // Trying to access at negative index + int numFromGreaterIndex = nums[4]; // Trying to access at greater index + int numFromLengthIndex = nums[3]; // Trying to access at index equal to size of the array + } catch (ArrayIndexOutOfBoundsException e) { + LOGGER.error("ArrayIndexOutOfBoundsException caught"); + } + + } + +} diff --git a/core-java/src/main/java/com/baeldung/exceptions/ClassCast.java b/core-java/src/main/java/com/baeldung/exceptions/ClassCast.java new file mode 100644 index 0000000000..183f8f54a3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptions/ClassCast.java @@ -0,0 +1,36 @@ +package com.baeldung.exceptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class Animal { + +} + +class Dog extends Animal { + +} + +class Lion extends Animal { + +} + +public class ClassCast { + + private static Logger LOGGER = LoggerFactory.getLogger(ClassCast.class); + + public static void main(String[] args) { + + try { + Animal animalOne = new Dog(); // At runtime the instance is dog + Dog bruno = (Dog) animalOne; // Downcasting + + Animal animalTwo = new Lion(); // At runtime the instance is animal + Dog tommy = (Dog) animalTwo; // Downcasting + } catch (ClassCastException e) { + LOGGER.error("ClassCastException caught!"); + } + + } + +} diff --git a/core-java/src/main/java/com/baeldung/exceptions/FileNotFound.java b/core-java/src/main/java/com/baeldung/exceptions/FileNotFound.java new file mode 100644 index 0000000000..bb9e0bf4ac --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptions/FileNotFound.java @@ -0,0 +1,25 @@ +package com.baeldung.exceptions; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class FileNotFound { + + private static Logger LOGGER = LoggerFactory.getLogger(FileNotFound.class); + + public static void main(String[] args) { + + BufferedReader reader = null; + try { + reader = new BufferedReader(new FileReader(new File("/invalid/file/location"))); + } catch (FileNotFoundException e) { + LOGGER.error("FileNotFoundException caught!"); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/exceptions/GlobalExceptionHandler.java b/core-java/src/main/java/com/baeldung/exceptions/GlobalExceptionHandler.java new file mode 100644 index 0000000000..ab46c83da4 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptions/GlobalExceptionHandler.java @@ -0,0 +1,28 @@ +package com.baeldung.exceptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class GlobalExceptionHandler { + + public static void main(String[] args) { + + Handler globalExceptionHandler = new Handler(); + Thread.setDefaultUncaughtExceptionHandler(globalExceptionHandler); + new GlobalExceptionHandler().performArithmeticOperation(10, 0); + } + + public int performArithmeticOperation(int num1, int num2) { + return num1/num2; + } + +} + +class Handler implements Thread.UncaughtExceptionHandler { + + private static Logger LOGGER = LoggerFactory.getLogger(Handler.class); + + public void uncaughtException(Thread t, Throwable e) { + LOGGER.info("Unhandled exception caught!"); + } +} diff --git a/core-java/src/main/java/com/baeldung/exceptions/IllegalArgument.java b/core-java/src/main/java/com/baeldung/exceptions/IllegalArgument.java new file mode 100644 index 0000000000..801536cb2d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptions/IllegalArgument.java @@ -0,0 +1,18 @@ +package com.baeldung.exceptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class IllegalArgument { + + private static Logger LOGGER = LoggerFactory.getLogger(IllegalArgument.class); + + public static void main(String[] args) { + try { + Thread.sleep(-1000); + } catch (InterruptedException e) { + LOGGER.error("IllegalArgumentException caught!"); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/exceptions/IllegalState.java b/core-java/src/main/java/com/baeldung/exceptions/IllegalState.java new file mode 100644 index 0000000000..e8ddcea3c2 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptions/IllegalState.java @@ -0,0 +1,32 @@ +package com.baeldung.exceptions; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class IllegalState { + + private static Logger LOGGER = LoggerFactory.getLogger(IllegalState.class); + + public static void main(String[] args) { + + List intList = new ArrayList<>(); + + for (int i = 0; i < 10; i++) { + intList.add(i); + } + + Iterator intListIterator = intList.iterator(); // Initialized with index at -1 + + try { + intListIterator.remove(); // IllegalStateException + } catch (IllegalStateException e) { + LOGGER.error("IllegalStateException caught!"); + } + + } + +} diff --git a/core-java/src/main/java/com/baeldung/exceptions/InterruptedExceptionExample.java b/core-java/src/main/java/com/baeldung/exceptions/InterruptedExceptionExample.java new file mode 100644 index 0000000000..319fd33591 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptions/InterruptedExceptionExample.java @@ -0,0 +1,28 @@ +package com.baeldung.exceptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class ChildThread extends Thread { + + private static Logger LOGGER = LoggerFactory.getLogger(ChildThread.class); + + public void run() { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + LOGGER.error("InterruptedException caught!"); + } + } + +} + +public class InterruptedExceptionExample { + + public static void main(String[] args) throws InterruptedException { + ChildThread childThread = new ChildThread(); + childThread.start(); + childThread.interrupt(); + } + +} diff --git a/core-java/src/main/java/com/baeldung/exceptions/MalformedURL.java b/core-java/src/main/java/com/baeldung/exceptions/MalformedURL.java new file mode 100644 index 0000000000..57fcddf76b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptions/MalformedURL.java @@ -0,0 +1,25 @@ +package com.baeldung.exceptions; + +import java.net.MalformedURLException; +import java.net.URL; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MalformedURL { + + private static Logger LOGGER = LoggerFactory.getLogger(MalformedURL.class); + + public static void main(String[] args) { + + URL baeldungURL = null; + + try { + baeldungURL = new URL("malformedurl"); + } catch (MalformedURLException e) { + LOGGER.error("MalformedURLException caught!"); + } + + } + +} diff --git a/core-java/src/main/java/com/baeldung/exceptions/NullPointer.java b/core-java/src/main/java/com/baeldung/exceptions/NullPointer.java new file mode 100644 index 0000000000..2402a786a9 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptions/NullPointer.java @@ -0,0 +1,36 @@ +package com.baeldung.exceptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NullPointer { + + private static Logger LOGGER = LoggerFactory.getLogger(NullPointer.class); + + public static void main(String[] args) { + + Person personObj = null; + + try { + String name = personObj.personName; // Accessing the field of a null object + personObj.personName = "Jon Doe"; // Modifying the field of a null object + } catch (NullPointerException e) { + LOGGER.error("NullPointerException caught!"); + } + + } +} + +class Person { + + public String personName; + + public String getPersonName() { + return personName; + } + + public void setPersonName(String personName) { + this.personName = personName; + } + +} diff --git a/core-java/src/main/java/com/baeldung/exceptions/NumberFormat.java b/core-java/src/main/java/com/baeldung/exceptions/NumberFormat.java new file mode 100644 index 0000000000..7050e70aee --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptions/NumberFormat.java @@ -0,0 +1,23 @@ +package com.baeldung.exceptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NumberFormat { + + private static Logger LOGGER = LoggerFactory.getLogger(NumberFormat.class); + + public static void main(String[] args) { + + String str1 = "100ABCD"; + + try { + int x = Integer.parseInt(str1); // Converting string with inappropriate format + int y = Integer.valueOf(str1); + } catch (NumberFormatException e) { + LOGGER.error("NumberFormatException caught!"); + } + + } + +} diff --git a/core-java/src/main/java/com/baeldung/exceptions/ParseExceptionExample.java b/core-java/src/main/java/com/baeldung/exceptions/ParseExceptionExample.java new file mode 100644 index 0000000000..f7fb4c91e4 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptions/ParseExceptionExample.java @@ -0,0 +1,25 @@ +package com.baeldung.exceptions; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ParseExceptionExample { + + private static Logger LOGGER = LoggerFactory.getLogger(ParseExceptionExample.class); + + public static void main(String[] args) { + + DateFormat format = new SimpleDateFormat("MM, dd, yyyy"); + + try { + format.parse("01, , 2010"); + } catch (ParseException e) { + LOGGER.error("ParseException caught!"); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/exceptions/StringIndexOutOfBounds.java b/core-java/src/main/java/com/baeldung/exceptions/StringIndexOutOfBounds.java new file mode 100644 index 0000000000..bc297be498 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptions/StringIndexOutOfBounds.java @@ -0,0 +1,23 @@ +package com.baeldung.exceptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class StringIndexOutOfBounds { + + private static Logger LOGGER = LoggerFactory.getLogger(StringIndexOutOfBounds.class); + + public static void main(String[] args) { + + String str = "Hello World"; + + try { + char charAtNegativeIndex = str.charAt(-1); // Trying to access at negative index + char charAtLengthIndex = str.charAt(11); // Trying to access at index equal to size of the string + } catch (StringIndexOutOfBoundsException e) { + LOGGER.error("StringIndexOutOfBoundsException caught"); + } + + } + +} diff --git a/core-java/src/main/java/com/baeldung/extension/Extension.java b/core-java/src/main/java/com/baeldung/extension/Extension.java new file mode 100644 index 0000000000..e30084f1cb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/extension/Extension.java @@ -0,0 +1,23 @@ +package com.baeldung.extension; + +import com.google.common.io.Files; +import org.apache.commons.io.FilenameUtils; + +import java.util.Optional; + +public class Extension { + //Instead of file name we can also specify full path of a file eg. /baeldung/com/demo/abc.java + public String getExtensionByApacheCommonLib(String filename) { + return FilenameUtils.getExtension(filename); + } + + public Optional getExtensionByStringHandling(String filename) { + return Optional.ofNullable(filename) + .filter(f -> f.contains(".")) + .map(f -> f.substring(filename.lastIndexOf(".") + 1)); + } + + public String getExtensionByGuava(String filename) { + return Files.getFileExtension(filename); + } +} diff --git a/core-java/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java b/core-java/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java new file mode 100644 index 0000000000..45ff486a79 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java @@ -0,0 +1,24 @@ +package com.baeldung.fileparser; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; + +public class BufferedReaderExample { + + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { + + ArrayList result = new ArrayList<>(); + + try (BufferedReader br = new BufferedReader(new FileReader(filename))) { + + while (br.ready()) { + result.add(br.readLine()); + } + return result; + } + + } + +} diff --git a/core-java/src/main/java/com/baeldung/fileparser/FileReaderExample.java b/core-java/src/main/java/com/baeldung/fileparser/FileReaderExample.java new file mode 100644 index 0000000000..f9dd2a9ec5 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/fileparser/FileReaderExample.java @@ -0,0 +1,31 @@ +package com.baeldung.fileparser; + +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; + +public class FileReaderExample { + + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { + + ArrayList result = new ArrayList<>(); + + try (FileReader f = new FileReader(filename)) { + StringBuffer sb = new StringBuffer(); + while (f.ready()) { + char c = (char) f.read(); + if (c == '\n') { + result.add(sb.toString()); + sb = new StringBuffer(); + } else { + sb.append(c); + } + } + if (sb.length() > 0) { + result.add(sb.toString()); + } + } + + return result; + } +} diff --git a/core-java/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java b/core-java/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java new file mode 100644 index 0000000000..8e74f7d386 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java @@ -0,0 +1,18 @@ +package com.baeldung.fileparser; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +public class FilesReadLinesExample { + + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { + + List result = Files.readAllLines(Paths.get(filename)); + + return (ArrayList) result; + } + +} diff --git a/core-java/src/main/java/com/baeldung/fileparser/ScannerIntExample.java b/core-java/src/main/java/com/baeldung/fileparser/ScannerIntExample.java new file mode 100644 index 0000000000..25d17af4ea --- /dev/null +++ b/core-java/src/main/java/com/baeldung/fileparser/ScannerIntExample.java @@ -0,0 +1,24 @@ +package com.baeldung.fileparser; + +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Scanner; + +public class ScannerIntExample { + + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { + + ArrayList result = new ArrayList<>(); + + try (Scanner s = new Scanner(new FileReader(filename))) { + + while (s.hasNext()) { + result.add(s.nextInt()); + } + return result; + } + + } + +} diff --git a/core-java/src/main/java/com/baeldung/fileparser/ScannerStringExample.java b/core-java/src/main/java/com/baeldung/fileparser/ScannerStringExample.java new file mode 100644 index 0000000000..ec213c9490 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/fileparser/ScannerStringExample.java @@ -0,0 +1,24 @@ +package com.baeldung.fileparser; + +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Scanner; + +public class ScannerStringExample { + + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { + + ArrayList result = new ArrayList<>(); + + try (Scanner s = new Scanner(new FileReader(filename))) { + + while (s.hasNext()) { + result.add(s.nextLine()); + } + return result; + } + + } + +} diff --git a/core-java/src/main/java/com/baeldung/hashcode/entities/User.java b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java index c46c3de65a..524f176e6b 100644 --- a/core-java/src/main/java/com/baeldung/hashcode/entities/User.java +++ b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java @@ -25,7 +25,7 @@ public class User { if (this.getClass() != o.getClass()) return false; User user = (User) o; - return id != user.id && (!name.equals(user.name) && !email.equals(user.email)); + return id == user.id && (name.equals(user.name) && email.equals(user.email)); } @Override @@ -38,4 +38,5 @@ public class User { return hash; } // getters and setters here + } diff --git a/core-java/src/main/java/com/baeldung/immutableobjects/Currency.java b/core-java/src/main/java/com/baeldung/immutableobjects/Currency.java new file mode 100644 index 0000000000..412d105581 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/immutableobjects/Currency.java @@ -0,0 +1,18 @@ +package com.baeldung.immutableobjects; + +public final class Currency { + + private final String value; + + private Currency(String currencyValue) { + value = currencyValue; + } + + public String getValue() { + return value; + } + + public static Currency of(String value) { + return new Currency(value); + } +} diff --git a/core-java/src/main/java/com/baeldung/immutableobjects/Money.java b/core-java/src/main/java/com/baeldung/immutableobjects/Money.java new file mode 100644 index 0000000000..b509d2e797 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/immutableobjects/Money.java @@ -0,0 +1,20 @@ +package com.baeldung.immutableobjects; + +// 4. Immutability in Java +public final class Money { + private final double amount; + private final Currency currency; + + public Money(double amount, Currency currency) { + this.amount = amount; + this.currency = currency; + } + + public Currency getCurrency() { + return currency; + } + + public double getAmount() { + return amount; + } +} diff --git a/core-java/src/main/java/com/baeldung/instrumentation/agent/AtmTransformer.java b/core-java/src/main/java/com/baeldung/instrumentation/agent/AtmTransformer.java new file mode 100644 index 0000000000..3c83912f54 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/instrumentation/agent/AtmTransformer.java @@ -0,0 +1,70 @@ +package com.baeldung.instrumentation.agent; + +import javassist.CannotCompileException; +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtMethod; +import javassist.NotFoundException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.lang.instrument.ClassFileTransformer; +import java.lang.instrument.IllegalClassFormatException; +import java.security.ProtectionDomain; + +public class AtmTransformer implements ClassFileTransformer { + + private static Logger LOGGER = LoggerFactory.getLogger(AtmTransformer.class); + + private static final String WITHDRAW_MONEY_METHOD = "withdrawMoney"; + + /** The internal form class name of the class to transform */ + private String targetClassName; + /** The class loader of the class we want to transform */ + private ClassLoader targetClassLoader; + + public AtmTransformer(String targetClassName, ClassLoader targetClassLoader) { + this.targetClassName = targetClassName; + this.targetClassLoader = targetClassLoader; + } + + @Override + public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, + ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { + byte[] byteCode = classfileBuffer; + + String finalTargetClassName = this.targetClassName.replaceAll("\\.", "/"); //replace . with / + if (!className.equals(finalTargetClassName)) { + return byteCode; + } + + if (className.equals(finalTargetClassName) && loader.equals(targetClassLoader)) { + LOGGER.info("[Agent] Transforming class MyAtm"); + try { + ClassPool cp = ClassPool.getDefault(); + CtClass cc = cp.get(targetClassName); + CtMethod m = cc.getDeclaredMethod(WITHDRAW_MONEY_METHOD); + m.addLocalVariable("startTime", CtClass.longType); + m.insertBefore("startTime = System.currentTimeMillis();"); + + StringBuilder endBlock = new StringBuilder(); + + m.addLocalVariable("endTime", CtClass.longType); + m.addLocalVariable("opTime", CtClass.longType); + endBlock.append("endTime = System.currentTimeMillis();"); + endBlock.append("opTime = (endTime-startTime)/1000;"); + + endBlock.append("LOGGER.info(\"[Application] Withdrawal operation completed in:\" + opTime + \" seconds!\");"); + + m.insertAfter(endBlock.toString()); + + byteCode = cc.toBytecode(); + cc.detach(); + } catch (NotFoundException | CannotCompileException | IOException e) { + LOGGER.error("Exception", e); + } + } + return byteCode; + } +} diff --git a/core-java/src/main/java/com/baeldung/instrumentation/agent/MyInstrumentationAgent.java b/core-java/src/main/java/com/baeldung/instrumentation/agent/MyInstrumentationAgent.java new file mode 100644 index 0000000000..685520276e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/instrumentation/agent/MyInstrumentationAgent.java @@ -0,0 +1,59 @@ +package com.baeldung.instrumentation.agent; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.instrument.Instrumentation; + +public class MyInstrumentationAgent { + private static Logger LOGGER = LoggerFactory.getLogger(MyInstrumentationAgent.class); + + public static void premain(String agentArgs, Instrumentation inst) { + LOGGER.info("[Agent] In premain method"); + + String className = "com.baeldung.instrumentation.application.MyAtm"; + transformClass(className,inst); + } + + public static void agentmain(String agentArgs, Instrumentation inst) { + LOGGER.info("[Agent] In agentmain method"); + + String className = "com.baeldung.instrumentation.application.MyAtm"; + transformClass(className,inst); + } + + private static void transformClass(String className, Instrumentation instrumentation) { + Class targetCls = null; + ClassLoader targetClassLoader = null; + // see if we can get the class using forName + try { + targetCls = Class.forName(className); + targetClassLoader = targetCls.getClassLoader(); + transform(targetCls, targetClassLoader, instrumentation); + return; + } catch (Exception ex) { + LOGGER.error("Class [{}] not found with Class.forName"); + } + // otherwise iterate all loaded classes and find what we want + for(Class clazz: instrumentation.getAllLoadedClasses()) { + if(clazz.getName().equals(className)) { + targetCls = clazz; + targetClassLoader = targetCls.getClassLoader(); + transform(targetCls, targetClassLoader, instrumentation); + return; + } + } + throw new RuntimeException("Failed to find class [" + className + "]"); + } + + private static void transform(Class clazz, ClassLoader classLoader, Instrumentation instrumentation) { + AtmTransformer dt = new AtmTransformer(clazz.getName(), classLoader); + instrumentation.addTransformer(dt, true); + try { + instrumentation.retransformClasses(clazz); + } catch (Exception ex) { + throw new RuntimeException("Transform failed for class: [" + clazz.getName() + "]", ex); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/instrumentation/application/AgentLoader.java b/core-java/src/main/java/com/baeldung/instrumentation/application/AgentLoader.java new file mode 100644 index 0000000000..2c1cd759a5 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/instrumentation/application/AgentLoader.java @@ -0,0 +1,46 @@ +package com.baeldung.instrumentation.application; + +import com.sun.tools.attach.VirtualMachine; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.util.Optional; + +/** + * Created by adi on 6/10/18. + */ +public class AgentLoader { + private static Logger LOGGER = LoggerFactory.getLogger(AgentLoader.class); + + public static void run(String[] args) { + String agentFilePath = "/home/adi/Desktop/agent-1.0.0-jar-with-dependencies.jar"; + String applicationName = "MyAtmApplication"; + + //iterate all jvms and get the first one that matches our application name + Optional jvmProcessOpt = Optional.ofNullable(VirtualMachine.list() + .stream() + .filter(jvm -> { + LOGGER.info("jvm:{}", jvm.displayName()); + return jvm.displayName().contains(applicationName); + }) + .findFirst().get().id()); + + if(!jvmProcessOpt.isPresent()) { + LOGGER.error("Target Application not found"); + return; + } + File agentFile = new File(agentFilePath); + try { + String jvmPid = jvmProcessOpt.get(); + LOGGER.info("Attaching to target JVM with PID: " + jvmPid); + VirtualMachine jvm = VirtualMachine.attach(jvmPid); + jvm.loadAgent(agentFile.getAbsolutePath()); + jvm.detach(); + LOGGER.info("Attached to target JVM and loaded Java agent successfully"); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/instrumentation/application/Launcher.java b/core-java/src/main/java/com/baeldung/instrumentation/application/Launcher.java new file mode 100644 index 0000000000..87e494baab --- /dev/null +++ b/core-java/src/main/java/com/baeldung/instrumentation/application/Launcher.java @@ -0,0 +1,14 @@ +package com.baeldung.instrumentation.application; + +/** + * Created by adi on 6/14/18. + */ +public class Launcher { + public static void main(String[] args) throws Exception { + if(args[0].equals("StartMyAtmApplication")) { + new MyAtmApplication().run(args); + } else if(args[0].equals("LoadAgent")) { + new AgentLoader().run(args); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtm.java b/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtm.java new file mode 100644 index 0000000000..f826e82975 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtm.java @@ -0,0 +1,19 @@ +package com.baeldung.instrumentation.application; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Created by adi on 6/11/18. + */ +public class MyAtm { + private static Logger LOGGER = LoggerFactory.getLogger(MyAtm.class); + + private static final int account = 10; + + public static void withdrawMoney(int amount) throws InterruptedException { + Thread.sleep(2000l); //processing going on here + LOGGER.info("[Application] Successful Withdrawal of [{}] units!", amount); + + } +} diff --git a/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtmApplication.java b/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtmApplication.java new file mode 100644 index 0000000000..425511285e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtmApplication.java @@ -0,0 +1,19 @@ +package com.baeldung.instrumentation.application; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MyAtmApplication { + + private static Logger LOGGER = LoggerFactory.getLogger(MyAtmApplication.class); + + public static void run(String[] args) throws Exception { + LOGGER.info("[Application] Starting ATM application"); + MyAtm.withdrawMoney(Integer.parseInt(args[2])); + + Thread.sleep(Long.valueOf(args[1])); + + MyAtm.withdrawMoney(Integer.parseInt(args[3])); + } + +} diff --git a/core-java/src/main/java/com/baeldung/keyword/KeywordDemo.java b/core-java/src/main/java/com/baeldung/keyword/KeywordDemo.java new file mode 100644 index 0000000000..fd608b424c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keyword/KeywordDemo.java @@ -0,0 +1,16 @@ +package com.baeldung.keyword; + +import com.baeldung.keyword.superkeyword.SuperSub; +import com.baeldung.keyword.thiskeyword.KeywordUnitTest; + +/** + * Created by Gebruiker on 5/14/2018. + */ +public class KeywordDemo { + + public static void main(String[] args) { + KeywordUnitTest keyword = new KeywordUnitTest(); + + SuperSub child = new SuperSub("message from the child class"); + } +} diff --git a/core-java/src/main/java/com/baeldung/keyword/superkeyword/SuperBase.java b/core-java/src/main/java/com/baeldung/keyword/superkeyword/SuperBase.java new file mode 100644 index 0000000000..a5304fcef9 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keyword/superkeyword/SuperBase.java @@ -0,0 +1,20 @@ +package com.baeldung.keyword.superkeyword; + +/** + * Created by Gebruiker on 5/14/2018. + */ +public class SuperBase { + + String message = "super class"; + + public SuperBase() { + } + + public SuperBase(String message) { + this.message = message; + } + + public void printMessage() { + System.out.println(message); + } +} diff --git a/core-java/src/main/java/com/baeldung/keyword/superkeyword/SuperSub.java b/core-java/src/main/java/com/baeldung/keyword/superkeyword/SuperSub.java new file mode 100644 index 0000000000..83bc04ad0f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keyword/superkeyword/SuperSub.java @@ -0,0 +1,26 @@ +package com.baeldung.keyword.superkeyword; + +/** + * Created by Gebruiker on 5/15/2018. + */ +public class SuperSub extends SuperBase { + + String message = "child class"; + + public SuperSub(String message) { + super(message); + } + + public SuperSub() { + super.printMessage(); + printMessage(); + } + + public void getParentMessage() { + System.out.println(super.message); + } + + public void printMessage() { + System.out.println(message); + } +} diff --git a/core-java/src/main/java/com/baeldung/keyword/thiskeyword/KeywordUnitTest.java b/core-java/src/main/java/com/baeldung/keyword/thiskeyword/KeywordUnitTest.java new file mode 100644 index 0000000000..35fd7358af --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keyword/thiskeyword/KeywordUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.keyword.thiskeyword; + +public class KeywordUnitTest { + + private String name; + private int age; + + public KeywordUnitTest() { + this("John", 27); + this.printMessage(); + printInstance(this); + } + + public KeywordUnitTest(String name, int age) { + this.name = name; + this.age = age; + } + + public void printMessage() { + System.out.println("invoked by this"); + } + + public void printInstance(KeywordUnitTest thisKeyword) { + System.out.println(thisKeyword); + } + + public KeywordUnitTest getCurrentInstance() { + return this; + } + + class ThisInnerClass { + + boolean isInnerClass = true; + + public ThisInnerClass() { + KeywordUnitTest thisKeyword = KeywordUnitTest.this; + String outerString = KeywordUnitTest.this.name; + System.out.println(this.isInnerClass); + } + } + + @Override + public String toString() { + return "KeywordTest{" + + "name='" + name + '\'' + + ", age=" + age + + '}'; + } +} diff --git a/core-java/src/main/java/com/baeldung/keywords/finalize/FinalizeObject.java b/core-java/src/main/java/com/baeldung/keywords/finalize/FinalizeObject.java new file mode 100644 index 0000000000..af0449c0da --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keywords/finalize/FinalizeObject.java @@ -0,0 +1,18 @@ +package com.baeldung.keywords.finalize; + +public class FinalizeObject { + + @Override + protected void finalize() throws Throwable { + System.out.println("Execute finalize method"); + super.finalize(); + } + + public static void main(String[] args) throws Exception { + FinalizeObject object = new FinalizeObject(); + object = null; + System.gc(); + Thread.sleep(1000); + } + +} diff --git a/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Child.java b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Child.java new file mode 100644 index 0000000000..8615c78652 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Child.java @@ -0,0 +1,15 @@ +package com.baeldung.keywords.finalkeyword; + +public final class Child extends Parent { + + @Override + void method1(int arg1, final int arg2) { + // OK + } + +/* @Override + void method2() { + // Compilation error + }*/ + +} diff --git a/core-java/src/main/java/com/baeldung/keywords/finalkeyword/GrandChild.java b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/GrandChild.java new file mode 100644 index 0000000000..1530c5037f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/GrandChild.java @@ -0,0 +1,5 @@ +package com.baeldung.keywords.finalkeyword; + +/*public class GrandChild extends Child { + // Compilation error +}*/ diff --git a/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Parent.java b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Parent.java new file mode 100644 index 0000000000..5cd2996e7a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Parent.java @@ -0,0 +1,23 @@ +package com.baeldung.keywords.finalkeyword; + +public class Parent { + + int field1 = 1; + final int field2 = 2; + + Parent() { + field1 = 2; // OK +// field2 = 3; // Compilation error + } + + void method1(int arg1, final int arg2) { + arg1 = 2; // OK +// arg2 = 3; // Compilation error + } + + final void method2() { + final int localVar = 2; // OK +// localVar = 3; // Compilation error + } + +} diff --git a/core-java/src/main/java/com/baeldung/keywords/finallykeyword/FinallyExample.java b/core-java/src/main/java/com/baeldung/keywords/finallykeyword/FinallyExample.java new file mode 100644 index 0000000000..3c0aee3196 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keywords/finallykeyword/FinallyExample.java @@ -0,0 +1,29 @@ +package com.baeldung.keywords.finallykeyword; + +public class FinallyExample { + + public static void main(String args[]) throws Exception { + try { + System.out.println("Execute try block"); + throw new Exception(); + } catch (Exception e) { + System.out.println("Execute catch block"); + } finally { + System.out.println("Execute finally block"); + } + + try { + System.out.println("Execute try block"); + } finally { + System.out.println("Execute finally block"); + } + + try { + System.out.println("Execute try block"); + throw new Exception(); + } finally { + System.out.println("Execute finally block"); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/manifest/AppExample.java b/core-java/src/main/java/com/baeldung/manifest/AppExample.java new file mode 100644 index 0000000000..cb15323b22 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/manifest/AppExample.java @@ -0,0 +1,8 @@ +package com.baeldung.manifest; + +public class AppExample { + + public static void main(String[] args){ + System.out.println("AppExample executed!"); + } +} diff --git a/core-java/src/main/java/com/baeldung/manifest/ExecuteJarFile.java b/core-java/src/main/java/com/baeldung/manifest/ExecuteJarFile.java new file mode 100644 index 0000000000..21e14b96e0 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/manifest/ExecuteJarFile.java @@ -0,0 +1,83 @@ +package com.baeldung.manifest; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; + +public class ExecuteJarFile { + + private static final String DELIMITER = " "; + private static final String WORK_PATH = "src/main/java/com/baeldung/manifest"; + private static final String MANIFEST_MF_PATH = WORK_PATH + "/MANIFEST.MF"; + private static final String MAIN_MANIFEST_ATTRIBUTE = "Main-Class: com.baeldung.manifest.AppExample"; + + private static final String COMPILE_COMMAND = "javac -d . AppExample.java"; + private static final String CREATE_JAR_WITHOUT_MF_ATT_COMMAND = "jar cvf example.jar com/baeldung/manifest/AppExample.class"; + private static final String CREATE_JAR_WITH_MF_ATT_COMMAND = "jar cvmf MANIFEST.MF example.jar com/baeldung/manifest/AppExample.class"; + private static final String EXECUTE_JAR_COMMAND = "java -jar example.jar"; + + public static void main(String[] args) { + System.out.println(executeJarWithoutManifestAttribute()); + System.out.println(executeJarWithManifestAttribute()); + } + + public static String executeJarWithoutManifestAttribute() { + return executeJar(CREATE_JAR_WITHOUT_MF_ATT_COMMAND); + } + + public static String executeJarWithManifestAttribute() { + createManifestFile(); + return executeJar(CREATE_JAR_WITH_MF_ATT_COMMAND); + } + + private static void createManifestFile() { + BufferedWriter writer; + try { + writer = new BufferedWriter(new FileWriter(MANIFEST_MF_PATH)); + writer.write(MAIN_MANIFEST_ATTRIBUTE); + writer.newLine(); + writer.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static String executeJar(String createJarCommand) { + executeCommand(COMPILE_COMMAND); + executeCommand(createJarCommand); + return executeCommand(EXECUTE_JAR_COMMAND); + } + + private static String executeCommand(String command) { + String output = null; + try { + output = collectOutput(runProcess(command)); + } catch (Exception ex) { + System.out.println(ex); + } + return output; + } + + private static String collectOutput(Process process) throws IOException { + StringBuffer output = new StringBuffer(); + BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream())); + String line = ""; + while ((line = outputReader.readLine()) != null) { + output.append(line + "\n"); + } + return output.toString(); + } + + private static Process runProcess(String command) throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder(command.split(DELIMITER)); + builder.directory(new File(WORK_PATH).getAbsoluteFile()); + builder.redirectErrorStream(true); + Process process = builder.start(); + process.waitFor(); + return process; + } + +} diff --git a/core-java/src/main/java/com/baeldung/maths/BigDecimalImpl.java b/core-java/src/main/java/com/baeldung/maths/BigDecimalImpl.java deleted file mode 100644 index 1472dd7d6d..0000000000 --- a/core-java/src/main/java/com/baeldung/maths/BigDecimalImpl.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.maths; - -import java.math.BigDecimal; -import java.math.RoundingMode; - -public class BigDecimalImpl { - - public static void main(String[] args) { - - BigDecimal serviceTax = new BigDecimal("56.0084578639"); - serviceTax = serviceTax.setScale(2, RoundingMode.CEILING); - - BigDecimal entertainmentTax = new BigDecimal("23.00689"); - entertainmentTax = entertainmentTax.setScale(2, RoundingMode.FLOOR); - - BigDecimal totalTax = serviceTax.add(entertainmentTax); - } -} diff --git a/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java b/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java deleted file mode 100644 index 9f46345e04..0000000000 --- a/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.maths; - -import java.math.BigInteger; - -public class BigIntegerImpl { - - public static void main(String[] args) { - - BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476"); - BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476"); - - BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda); - - } - -} diff --git a/core-java/src/main/java/com/baeldung/objectsize/InstrumentationAgent.java b/core-java/src/main/java/com/baeldung/objectsize/InstrumentationAgent.java new file mode 100644 index 0000000000..66e9a44af8 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/objectsize/InstrumentationAgent.java @@ -0,0 +1,18 @@ +package com.baeldung.objectsize; + +import java.lang.instrument.Instrumentation; + +public class InstrumentationAgent { + private static volatile Instrumentation globalInstrumentation; + + public static void premain(final String agentArgs, final Instrumentation inst) { + globalInstrumentation = inst; + } + + public static long getObjectSize(final Object object) { + if (globalInstrumentation == null) { + throw new IllegalStateException("Agent not initialized."); + } + return globalInstrumentation.getObjectSize(object); + } +} diff --git a/core-java/src/main/java/com/baeldung/objectsize/InstrumentationExample.java b/core-java/src/main/java/com/baeldung/objectsize/InstrumentationExample.java new file mode 100644 index 0000000000..f751d954c8 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/objectsize/InstrumentationExample.java @@ -0,0 +1,59 @@ +package com.baeldung.objectsize; + +import java.util.ArrayList; +import java.util.List; + +public class InstrumentationExample { + + public static void printObjectSize(Object object) { + System.out.println("Object type: " + object.getClass() + ", size: " + InstrumentationAgent.getObjectSize(object) + " bytes"); + } + + public static void main(String[] arguments) { + String emptyString = ""; + String string = "Estimating Object Size Using Instrumentation"; + String[] stringArray = { emptyString, string, "com.baeldung" }; + String[] anotherStringArray = new String[100]; + List stringList = new ArrayList<>(); + StringBuilder stringBuilder = new StringBuilder(100); + int maxIntPrimitive = Integer.MAX_VALUE; + int minIntPrimitive = Integer.MIN_VALUE; + Integer maxInteger = Integer.MAX_VALUE; + Integer minInteger = Integer.MIN_VALUE; + long zeroLong = 0L; + double zeroDouble = 0.0; + boolean falseBoolean = false; + Object object = new Object(); + + class EmptyClass { + } + EmptyClass emptyClass = new EmptyClass(); + + class StringClass { + public String s; + } + StringClass stringClass = new StringClass(); + + printObjectSize(emptyString); + printObjectSize(string); + printObjectSize(stringArray); + printObjectSize(anotherStringArray); + printObjectSize(stringList); + printObjectSize(stringBuilder); + printObjectSize(maxIntPrimitive); + printObjectSize(minIntPrimitive); + printObjectSize(maxInteger); + printObjectSize(minInteger); + printObjectSize(zeroLong); + printObjectSize(zeroDouble); + printObjectSize(falseBoolean); + printObjectSize(Day.TUESDAY); + printObjectSize(object); + printObjectSize(emptyClass); + printObjectSize(stringClass); + } + + public enum Day { + MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY + } +} diff --git a/core-java/src/main/java/com/baeldung/objectsize/MANIFEST.MF b/core-java/src/main/java/com/baeldung/objectsize/MANIFEST.MF new file mode 100644 index 0000000000..b814f624d0 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/objectsize/MANIFEST.MF @@ -0,0 +1 @@ +Premain-class: com.baeldung.objectsize.InstrumentationAgent diff --git a/core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java b/core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java new file mode 100644 index 0000000000..bebffe52f1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java @@ -0,0 +1,45 @@ +/** + * + */ +package com.baeldung.string; + +/** + * @author swpraman + * + */ +public class AppendCharAtPositionX { + + public String addCharUsingCharArray(String str, char ch, int position) { + validate(str, position); + int len = str.length(); + char[] updatedArr = new char[len + 1]; + str.getChars(0, position, updatedArr, 0); + updatedArr[position] = ch; + str.getChars(position, len, updatedArr, position + 1); + return new String(updatedArr); + } + + public String addCharUsingSubstring(String str, char ch, int position) { + validate(str, position); + return str.substring(0, position) + ch + str.substring(position); + } + + public String addCharUsingStringBuilder(String str, char ch, int position) { + validate(str, position); + StringBuilder sb = new StringBuilder(str); + sb.insert(position, ch); + return sb.toString(); + } + + private void validate(String str, int position) { + if (str == null) { + throw new IllegalArgumentException("Str should not be null"); + } + int len = str.length(); + if (position < 0 || position > len) { + throw new IllegalArgumentException("position[" + position + "] should be " + + "in the range 0.." + len + " for string " + str); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/synthetic/BridgeMethodDemo.java b/core-java/src/main/java/com/baeldung/synthetic/BridgeMethodDemo.java new file mode 100644 index 0000000000..bdf6684f78 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/synthetic/BridgeMethodDemo.java @@ -0,0 +1,23 @@ +package com.baeldung.synthetic; + +import java.util.Comparator; + +/** + * Class which contains a synthetic bridge method. + * + * @author Donato Rimenti + * + */ +public class BridgeMethodDemo implements Comparator { + + /* + * (non-Javadoc) + * + * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) + */ + @Override + public int compare(Integer o1, Integer o2) { + return 0; + } + +} diff --git a/core-java/src/main/java/com/baeldung/synthetic/SyntheticConstructorDemo.java b/core-java/src/main/java/com/baeldung/synthetic/SyntheticConstructorDemo.java new file mode 100644 index 0000000000..d3d75ac05e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/synthetic/SyntheticConstructorDemo.java @@ -0,0 +1,34 @@ +package com.baeldung.synthetic; + +/** + * Wrapper for a class which contains a synthetic constructor. + * + * @author Donato Rimenti + * + */ +public class SyntheticConstructorDemo { + + /** + * We need to instantiate the {@link NestedClass} using a private + * constructor from the enclosing instance in order to generate a synthetic + * constructor. + */ + private NestedClass nestedClass = new NestedClass(); + + /** + * Class which contains a synthetic constructor. + * + * @author Donato Rimenti + * + */ + class NestedClass { + + /** + * In order to generate a synthetic constructor, this class must have a + * private constructor. + */ + private NestedClass() { + } + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/synthetic/SyntheticFieldDemo.java b/core-java/src/main/java/com/baeldung/synthetic/SyntheticFieldDemo.java new file mode 100644 index 0000000000..1813e03953 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/synthetic/SyntheticFieldDemo.java @@ -0,0 +1,22 @@ +package com.baeldung.synthetic; + +/** + * Wrapper for a class which contains a synthetic field reference to the outer + * class. + * + * @author Donato Rimenti + * + */ +public class SyntheticFieldDemo { + + /** + * Class which contains a synthetic field reference to the outer class. + * + * @author Donato Rimenti + * + */ + class NestedClass { + + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/synthetic/SyntheticMethodDemo.java b/core-java/src/main/java/com/baeldung/synthetic/SyntheticMethodDemo.java new file mode 100644 index 0000000000..59be4e1429 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/synthetic/SyntheticMethodDemo.java @@ -0,0 +1,48 @@ +package com.baeldung.synthetic; + +/** + * Wrapper for a class which contains two synthetic methods accessors to a + * private field. + * + * @author Donato Rimenti + * + */ +public class SyntheticMethodDemo { + + /** + * Class which contains two synthetic methods accessors to a private field. + * + * @author Donato Rimenti + * + */ + class NestedClass { + + /** + * Field for which will be generated synthetic methods accessors. It's + * important that this field is private for this purpose. + */ + private String nestedField; + } + + /** + * Gets the private nested field. We need to read the nested field in order + * to generate the synthetic getter. + * + * @return the {@link NestedClass#nestedField} + */ + public String getNestedField() { + return new NestedClass().nestedField; + } + + /** + * Sets the private nested field. We need to write the nested field in order + * to generate the synthetic setter. + * + * @param nestedField + * the {@link NestedClass#nestedField} + */ + public void setNestedField(String nestedField) { + new NestedClass().nestedField = nestedField; + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/throwsexception/Calculator.java b/core-java/src/main/java/com/baeldung/throwsexception/Calculator.java new file mode 100644 index 0000000000..50dbc9c774 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/throwsexception/Calculator.java @@ -0,0 +1,15 @@ +package com.baeldung.throwsexception; + +public class Calculator { + + public double divide(double a, double b) { + if (b == 0) { + throw new DivideByZeroException("Divider cannot be equal to zero!"); + } + return a/b; + } + +} + + + diff --git a/core-java/src/main/java/com/baeldung/throwsexception/DataAccessException.java b/core-java/src/main/java/com/baeldung/throwsexception/DataAccessException.java new file mode 100644 index 0000000000..0b371dcedb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/throwsexception/DataAccessException.java @@ -0,0 +1,9 @@ +package com.baeldung.throwsexception; + +public class DataAccessException extends RuntimeException { + + public DataAccessException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/core-java/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java b/core-java/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java new file mode 100644 index 0000000000..4413374c99 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java @@ -0,0 +1,9 @@ +package com.baeldung.throwsexception; + +public class DivideByZeroException extends RuntimeException { + + public DivideByZeroException(String message) { + super(message); + } + +} diff --git a/core-java/src/main/java/com/baeldung/throwsexception/Main.java b/core-java/src/main/java/com/baeldung/throwsexception/Main.java new file mode 100644 index 0000000000..17fbf5a582 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/throwsexception/Main.java @@ -0,0 +1,41 @@ +package com.baeldung.throwsexception; + +import com.sun.mail.iap.ConnectionException; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.net.SocketException; + +public class Main { + + public static void main(String[] args) throws FileNotFoundException { + TryCatch tryCatch = new TryCatch(); + + try { + tryCatch.execute(); + } catch (ConnectionException | SocketException ex) { + System.out.println("IOException"); + } catch (Exception ex) { + System.out.println("General exception"); + } + + checkedException(); + checkedExceptionWithThrows(); + } + + private static void checkedExceptionWithThrows() throws FileNotFoundException { + File file = new File("not_existing_file.txt"); + FileInputStream stream = new FileInputStream(file); + } + + private static void checkedException() { + File file = new File("not_existing_file.txt"); + try { + FileInputStream stream = new FileInputStream(file); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java b/core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java new file mode 100644 index 0000000000..7d8345c3c1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.throwsexception; + +import java.sql.SQLException; +import java.util.List; + +public class PersonRepository { + + public List findAll() throws SQLException { + throw new SQLException(); + } + +} diff --git a/core-java/src/main/java/com/baeldung/throwsexception/SimpleService.java b/core-java/src/main/java/com/baeldung/throwsexception/SimpleService.java new file mode 100644 index 0000000000..6bb8b90bf1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/throwsexception/SimpleService.java @@ -0,0 +1,22 @@ +package com.baeldung.throwsexception; + +import java.sql.SQLException; + +public class SimpleService { + + private PersonRepository personRepository = new PersonRepository(); + + public void wrappingException() { + try { + personRepository.findAll(); + } catch (SQLException e) { + throw new DataAccessException("SQL Exception", e); + } + } + + public void runtimeNullPointerException() { + String a = null; + a.length(); + } + +} diff --git a/core-java/src/main/java/com/baeldung/throwsexception/TryCatch.java b/core-java/src/main/java/com/baeldung/throwsexception/TryCatch.java new file mode 100644 index 0000000000..2fd87f124d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/throwsexception/TryCatch.java @@ -0,0 +1,13 @@ +package com.baeldung.throwsexception; + +import com.sun.mail.iap.ConnectionException; + +import java.net.SocketException; + +public class TryCatch { + + public void execute() throws SocketException, ConnectionException, Exception { + //code that would throw any of: SocketException, ConnectionException, Exception + } + +} diff --git a/core-java/src/main/resources/META-INF/MANIFEST.MF b/core-java/src/main/resources/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..988de3193d --- /dev/null +++ b/core-java/src/main/resources/META-INF/MANIFEST.MF @@ -0,0 +1,5 @@ +Agent-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent +Can-Redefine-Classes: true +Can-Retransform-Classes: true +Premain-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent +Main-Class: com.baeldung.instrumentation.application.Launcher diff --git a/core-java/src/main/resources/log4j2.xml b/core-java/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..a824bef9b0 --- /dev/null +++ b/core-java/src/main/resources/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/core-java/src/main/resources/logback.xml b/core-java/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/core-java/src/main/resources/logback.xml +++ b/core-java/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/core-java/src/main/resources/product.png b/core-java/src/main/resources/product.png new file mode 100644 index 0000000000..4edd01c0a1 Binary files /dev/null and b/core-java/src/main/resources/product.png differ diff --git a/core-java/src/test/java/com/baeldung/array/ArrayInitializerTest.java b/core-java/src/test/java/com/baeldung/array/ArrayInitializerTest.java deleted file mode 100644 index 7265fa20e5..0000000000 --- a/core-java/src/test/java/com/baeldung/array/ArrayInitializerTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.array; - -import static com.baeldung.array.ArrayInitializer.initializeArrayAtTimeOfDeclarationMethod1; -import static com.baeldung.array.ArrayInitializer.initializeArrayAtTimeOfDeclarationMethod2; -import static com.baeldung.array.ArrayInitializer.initializeArrayAtTimeOfDeclarationMethod3; -import static com.baeldung.array.ArrayInitializer.initializeArrayInLoop; -import static com.baeldung.array.ArrayInitializer.initializeArrayRangeUsingArraysFill; -import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysCopy; -import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysFill; -import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysSetAll; -import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysUtilClone; -import static com.baeldung.array.ArrayInitializer.initializeLargerArrayUsingArraysCopy; -import static com.baeldung.array.ArrayInitializer.initializeMultiDimensionalArrayInLoop; -import static org.junit.Assert.assertArrayEquals; - -import org.junit.Test; - -public class ArrayInitializerTest { - - @Test - public void whenInitializeArrayInLoop_thenCorrect() { - assertArrayEquals(new int[] { 2, 3, 4, 5, 6 }, initializeArrayInLoop()); - } - - @Test - public void whenInitializeMultiDimensionalArrayInLoop_thenCorrect() { - assertArrayEquals(new int[][] { { 1, 2, 3, 4, 5 }, { 1, 2, 3, 4, 5 } }, initializeMultiDimensionalArrayInLoop()); - } - - @Test - public void whenInitializeArrayAtTimeOfDeclarationMethod1_thenCorrect() { - assertArrayEquals(new String[] { "Toyota", "Mercedes", "BMW", "Volkswagen", "Skoda" }, initializeArrayAtTimeOfDeclarationMethod1()); - } - - @Test - public void whenInitializeArrayAtTimeOfDeclarationMethod2_thenCorrect() { - assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, initializeArrayAtTimeOfDeclarationMethod2()); - } - - @Test - public void whenInitializeArrayAtTimeOfDeclarationMethod3_thenCorrect() { - assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, initializeArrayAtTimeOfDeclarationMethod3()); - } - - @Test - public void whenInitializeArrayUsingArraysFill_thenCorrect() { - assertArrayEquals(new long[] { 30, 30, 30, 30, 30 }, initializeArrayUsingArraysFill()); - } - - @Test - public void whenInitializeArrayRangeUsingArraysFill_thenCorrect() { - assertArrayEquals(new int[] { -50, -50, -50, 0, 0 }, initializeArrayRangeUsingArraysFill()); - } - - @Test - public void whenInitializeArrayRangeUsingArraysCopy_thenCorrect() { - assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, initializeArrayUsingArraysCopy()); - } - - @Test - public void whenInitializeLargerArrayRangeUsingArraysCopy_thenCorrect() { - assertArrayEquals(new int[] { 1, 2, 3, 4, 5, 0 }, initializeLargerArrayUsingArraysCopy()); - } - - @Test - public void whenInitializeLargerArrayRangeUsingArraysSetAll_thenCorrect() { - assertArrayEquals(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, initializeArrayUsingArraysSetAll()); - } - - @Test - public void whenInitializeArrayUsingArraysUtilClone_thenCorrect() { - assertArrayEquals(new char[] { 'a', 'b', 'c' }, initializeArrayUsingArraysUtilClone()); - } -} diff --git a/core-java/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java b/core-java/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java new file mode 100644 index 0000000000..5e764da174 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java @@ -0,0 +1,74 @@ +package com.baeldung.array; + +import static com.baeldung.array.ArrayInitializer.initializeArrayAtTimeOfDeclarationMethod1; +import static com.baeldung.array.ArrayInitializer.initializeArrayAtTimeOfDeclarationMethod2; +import static com.baeldung.array.ArrayInitializer.initializeArrayAtTimeOfDeclarationMethod3; +import static com.baeldung.array.ArrayInitializer.initializeArrayInLoop; +import static com.baeldung.array.ArrayInitializer.initializeArrayRangeUsingArraysFill; +import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysCopy; +import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysFill; +import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysSetAll; +import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysUtilClone; +import static com.baeldung.array.ArrayInitializer.initializeLargerArrayUsingArraysCopy; +import static com.baeldung.array.ArrayInitializer.initializeMultiDimensionalArrayInLoop; +import static org.junit.Assert.assertArrayEquals; + +import org.junit.Test; + +public class ArrayInitializerUnitTest { + + @Test + public void whenInitializeArrayInLoop_thenCorrect() { + assertArrayEquals(new int[] { 2, 3, 4, 5, 6 }, initializeArrayInLoop()); + } + + @Test + public void whenInitializeMultiDimensionalArrayInLoop_thenCorrect() { + assertArrayEquals(new int[][] { { 1, 2, 3, 4, 5 }, { 1, 2, 3, 4, 5 } }, initializeMultiDimensionalArrayInLoop()); + } + + @Test + public void whenInitializeArrayAtTimeOfDeclarationMethod1_thenCorrect() { + assertArrayEquals(new String[] { "Toyota", "Mercedes", "BMW", "Volkswagen", "Skoda" }, initializeArrayAtTimeOfDeclarationMethod1()); + } + + @Test + public void whenInitializeArrayAtTimeOfDeclarationMethod2_thenCorrect() { + assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, initializeArrayAtTimeOfDeclarationMethod2()); + } + + @Test + public void whenInitializeArrayAtTimeOfDeclarationMethod3_thenCorrect() { + assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, initializeArrayAtTimeOfDeclarationMethod3()); + } + + @Test + public void whenInitializeArrayUsingArraysFill_thenCorrect() { + assertArrayEquals(new long[] { 30, 30, 30, 30, 30 }, initializeArrayUsingArraysFill()); + } + + @Test + public void whenInitializeArrayRangeUsingArraysFill_thenCorrect() { + assertArrayEquals(new int[] { -50, -50, -50, 0, 0 }, initializeArrayRangeUsingArraysFill()); + } + + @Test + public void whenInitializeArrayRangeUsingArraysCopy_thenCorrect() { + assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, initializeArrayUsingArraysCopy()); + } + + @Test + public void whenInitializeLargerArrayRangeUsingArraysCopy_thenCorrect() { + assertArrayEquals(new int[] { 1, 2, 3, 4, 5, 0 }, initializeLargerArrayUsingArraysCopy()); + } + + @Test + public void whenInitializeLargerArrayRangeUsingArraysSetAll_thenCorrect() { + assertArrayEquals(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, initializeArrayUsingArraysSetAll()); + } + + @Test + public void whenInitializeArrayUsingArraysUtilClone_thenCorrect() { + assertArrayEquals(new char[] { 'a', 'b', 'c' }, initializeArrayUsingArraysUtilClone()); + } +} diff --git a/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayTest.java b/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayTest.java deleted file mode 100644 index ec916af092..0000000000 --- a/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.array; - -import org.junit.Assert; -import org.junit.Test; - -public class Find2ndLargestInArrayTest { - @Test - public void givenAnIntArray_thenFind2ndLargestElement() { - int[] array = { 1, 3, 24, 16, 87, 20 }; - int expected2ndLargest = 24; - - int actualSecondLargestElement = Find2ndLargestInArray.find2ndLargestElement(array); - - Assert.assertEquals(expected2ndLargest, actualSecondLargestElement); - } -} diff --git a/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayUnitTest.java b/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayUnitTest.java new file mode 100644 index 0000000000..4493f3fbf5 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.array; + +import org.junit.Assert; +import org.junit.Test; + +public class Find2ndLargestInArrayUnitTest { + @Test + public void givenAnIntArray_thenFind2ndLargestElement() { + int[] array = { 1, 3, 24, 16, 87, 20 }; + int expected2ndLargest = 24; + + int actualSecondLargestElement = Find2ndLargestInArray.find2ndLargestElement(array); + + Assert.assertEquals(expected2ndLargest, actualSecondLargestElement); + } +} diff --git a/core-java/src/test/java/com/baeldung/array/FindElementInArrayTest.java b/core-java/src/test/java/com/baeldung/array/FindElementInArrayTest.java deleted file mode 100644 index ba9188fa7b..0000000000 --- a/core-java/src/test/java/com/baeldung/array/FindElementInArrayTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.array; - -import org.junit.Assert; -import org.junit.Test; - -public class FindElementInArrayTest { - @Test - public void givenAnIntArray_whenNotUsingStream_thenFindAnElement() { - int[] array = { 1, 3, 4, 8, 19, 20 }; - int element = 19; - boolean expectedResult = true; - boolean actualResult = FindElementInArray.findGivenElementInArrayWithoutUsingStream(array, element); - Assert.assertEquals(expectedResult, actualResult); - - element = 78; - expectedResult = false; - actualResult = FindElementInArray.findGivenElementInArrayWithoutUsingStream(array, element); - Assert.assertEquals(expectedResult, actualResult); - } - - @Test - public void givenAnIntArray_whenUsingStream_thenFindAnElement() { - int[] array = { 15, 16, 12, 18 }; - int element = 16; - boolean expectedResult = true; - boolean actualResult = FindElementInArray.findGivenElementInArrayUsingStream(array, element); - Assert.assertEquals(expectedResult, actualResult); - - element = 20; - expectedResult = false; - actualResult = FindElementInArray.findGivenElementInArrayUsingStream(array, element); - Assert.assertEquals(expectedResult, actualResult); - } - -} diff --git a/core-java/src/test/java/com/baeldung/array/FindElementInArrayUnitTest.java b/core-java/src/test/java/com/baeldung/array/FindElementInArrayUnitTest.java new file mode 100644 index 0000000000..887f50ebcc --- /dev/null +++ b/core-java/src/test/java/com/baeldung/array/FindElementInArrayUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.array; + +import org.junit.Assert; +import org.junit.Test; + +public class FindElementInArrayUnitTest { + @Test + public void givenAnIntArray_whenNotUsingStream_thenFindAnElement() { + int[] array = { 1, 3, 4, 8, 19, 20 }; + int element = 19; + boolean expectedResult = true; + boolean actualResult = FindElementInArray.findGivenElementInArrayWithoutUsingStream(array, element); + Assert.assertEquals(expectedResult, actualResult); + + element = 78; + expectedResult = false; + actualResult = FindElementInArray.findGivenElementInArrayWithoutUsingStream(array, element); + Assert.assertEquals(expectedResult, actualResult); + } + + @Test + public void givenAnIntArray_whenUsingStream_thenFindAnElement() { + int[] array = { 15, 16, 12, 18 }; + int element = 16; + boolean expectedResult = true; + boolean actualResult = FindElementInArray.findGivenElementInArrayUsingStream(array, element); + Assert.assertEquals(expectedResult, actualResult); + + element = 20; + expectedResult = false; + actualResult = FindElementInArray.findGivenElementInArrayUsingStream(array, element); + Assert.assertEquals(expectedResult, actualResult); + } + +} diff --git a/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java b/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java new file mode 100644 index 0000000000..a4dd7e25c3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.array; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.PrintStream; + +import org.junit.Test; + +public class JaggedArrayUnitTest { + + private JaggedArray obj = new JaggedArray(); + + @Test + public void whenInitializedUsingShortHandForm_thenCorrect() { + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.shortHandFormInitialization()); + } + + @Test + public void whenInitializedWithDeclarationAndThenInitalization_thenCorrect() { + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitialization()); + } + + @Test + public void whenInitializedWithDeclarationAndThenInitalizationUsingUserInputs_thenCorrect() { + InputStream is = new ByteArrayInputStream("1 2 3 4 5 6 7 8 9".getBytes()); + System.setIn(is); + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitializationUsingUserInputs()); + System.setIn(System.in); + } + + @Test + public void givenJaggedArrayAndAnIndex_thenReturnArrayAtGivenIndex() { + int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + assertArrayEquals(new int[] { 1, 2 }, obj.getElementAtGivenIndex(jaggedArr, 0)); + assertArrayEquals(new int[] { 3, 4, 5 }, obj.getElementAtGivenIndex(jaggedArr, 1)); + assertArrayEquals(new int[] { 6, 7, 8, 9 }, obj.getElementAtGivenIndex(jaggedArr, 2)); + } + + @Test + public void givenJaggedArray_whenUsingArraysAPI_thenVerifyPrintedElements() { + int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outContent)); + obj.printElements(jaggedArr); + assertEquals("[1, 2][3, 4, 5][6, 7, 8, 9]", outContent.toString().replace("\r", "").replace("\n", "")); + System.setOut(System.out); + } + +} diff --git a/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java b/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java deleted file mode 100644 index 208075cb57..0000000000 --- a/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.baeldung.array; - -import org.junit.Assert; -import org.junit.Test; - -public class SumAndAverageInArrayTest { - @Test - public void givenAnIntArray_whenNotUsingStream_thenFindSum() { - int[] array = { 1, 3, 4, 8, 19, 20 }; - int expectedSumOfArray = 55; - int actualSumOfArray = SumAndAverageInArray.findSumWithoutUsingStream(array); - Assert.assertEquals(expectedSumOfArray, actualSumOfArray); - } - - @Test - public void givenAnIntArray_whenUsingStream_thenFindSum() { - int[] array = { 1, 3, 4, 8, 19, 20 }; - int expectedSumOfArray = 55; - int actualSumOfArray = SumAndAverageInArray.findSumUsingStream(array); - - Assert.assertEquals(expectedSumOfArray, actualSumOfArray); - } - - @Test - public void givenAnBoxedIntegerArray_whenUsingStream_thenFindSum() { - Integer[] array = new Integer[]{1, 3, 4, 8, 19, 20}; - int expectedSumOfArray = 55; - int actualSumOfArray = SumAndAverageInArray.findSumUsingStream(array); - - Assert.assertEquals(expectedSumOfArray, actualSumOfArray); - } - - @Test - public void givenAnIntArray_whenNotUsingStream_thenFindAverage() { - int[] array = { 1, 3, 4, 8, 19, 20 }; - double expectedAvgOfArray = 9.17; - double actualAvgOfArray = SumAndAverageInArray.findAverageWithoutUsingStream(array); - - Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.0034); - } - - @Test - public void givenAnIntArray_whenUsingStream_thenFindAverage() { - int[] array = { 1, 3, 4, 8, 19, 20 }; - double expectedAvgOfArray = 9.17; - double actualAvgOfArray = SumAndAverageInArray.findAverageUsingStream(array); - - Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.0034); - } - - @Test - public void givenAnEmptyIntArray_whenUsingStream_thenFindAverage() { - int[] array = {}; - double expectedAvgOfArray = Double.NaN; - double actualAvgOfArray = SumAndAverageInArray.findAverageUsingStream(array); - - Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.00); - } -} diff --git a/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java b/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java new file mode 100644 index 0000000000..0f38316ce3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.array; + +import org.junit.Assert; +import org.junit.Test; + +public class SumAndAverageInArrayUnitTest { + @Test + public void givenAnIntArray_whenNotUsingStream_thenFindSum() { + int[] array = { 1, 3, 4, 8, 19, 20 }; + int expectedSumOfArray = 55; + int actualSumOfArray = SumAndAverageInArray.findSumWithoutUsingStream(array); + Assert.assertEquals(expectedSumOfArray, actualSumOfArray); + } + + @Test + public void givenAnIntArray_whenUsingStream_thenFindSum() { + int[] array = { 1, 3, 4, 8, 19, 20 }; + int expectedSumOfArray = 55; + int actualSumOfArray = SumAndAverageInArray.findSumUsingStream(array); + + Assert.assertEquals(expectedSumOfArray, actualSumOfArray); + } + + @Test + public void givenAnBoxedIntegerArray_whenUsingStream_thenFindSum() { + Integer[] array = new Integer[]{1, 3, 4, 8, 19, 20}; + int expectedSumOfArray = 55; + int actualSumOfArray = SumAndAverageInArray.findSumUsingStream(array); + + Assert.assertEquals(expectedSumOfArray, actualSumOfArray); + } + + @Test + public void givenAnIntArray_whenNotUsingStream_thenFindAverage() { + int[] array = { 1, 3, 4, 8, 19, 20 }; + double expectedAvgOfArray = 9.17; + double actualAvgOfArray = SumAndAverageInArray.findAverageWithoutUsingStream(array); + + Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.0034); + } + + @Test + public void givenAnIntArray_whenUsingStream_thenFindAverage() { + int[] array = { 1, 3, 4, 8, 19, 20 }; + double expectedAvgOfArray = 9.17; + double actualAvgOfArray = SumAndAverageInArray.findAverageUsingStream(array); + + Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.0034); + } + + @Test + public void givenAnEmptyIntArray_whenUsingStream_thenFindAverage() { + int[] array = {}; + double expectedAvgOfArray = Double.NaN; + double actualAvgOfArray = SumAndAverageInArray.findAverageUsingStream(array); + + Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.00); + } +} diff --git a/core-java/src/test/java/com/baeldung/arrays/ArraysUnitTest.java b/core-java/src/test/java/com/baeldung/arrays/ArraysUnitTest.java new file mode 100644 index 0000000000..9e6d3d6131 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/arrays/ArraysUnitTest.java @@ -0,0 +1,153 @@ +package com.baeldung.arrays; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Stream; + +public class ArraysUnitTest { + private String[] intro; + + @Rule + public final ExpectedException exception = ExpectedException.none(); + + @Before + public void setup() { + intro = new String[] { "once", "upon", "a", "time" }; + } + + @Test + public void whenCopyOfRange_thenAbridgedArray() { + String[] abridgement = Arrays.copyOfRange(intro, 0, 3); + + assertArrayEquals(new String[] { "once", "upon", "a" }, abridgement); + assertFalse(Arrays.equals(intro, abridgement)); + } + + @Test + public void whenCopyOf_thenNullElement() { + String[] revised = Arrays.copyOf(intro, 3); + String[] expanded = Arrays.copyOf(intro, 5); + + assertArrayEquals(Arrays.copyOfRange(intro, 0, 3), revised); + assertNull(expanded[4]); + } + + @Test + public void whenFill_thenAllMatch() { + String[] stutter = new String[3]; + Arrays.fill(stutter, "once"); + + assertTrue(Stream.of(stutter).allMatch(el -> "once".equals(el))); + } + + @Test + public void whenEqualsContent_thenMatch() { + assertTrue(Arrays.equals(new String[] { "once", "upon", "a", "time" }, intro)); + assertFalse(Arrays.equals(new String[] { "once", "upon", "a", null }, intro)); + } + + @Test + public void whenNestedArrays_thenDeepEqualsPass() { + String[] end = { "the", "end" }; + Object[] story = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end }; + Object[] copy = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end }; + + assertTrue(Arrays.deepEquals(story, copy)); + assertFalse(Arrays.equals(story, copy)); + } + + @Test + public void whenSort_thenArraySorted() { + String[] sorted = Arrays.copyOf(intro, 4); + Arrays.sort(sorted); + + assertArrayEquals(new String[] { "a", "once", "time", "upon" }, sorted); + } + + @Test + public void whenBinarySearch_thenFindElements() { + String[] sorted = Arrays.copyOf(intro, 4); + Arrays.sort(sorted); + int exact = Arrays.binarySearch(sorted, "time"); + int caseInsensitive = Arrays.binarySearch(sorted, "TiMe", String::compareToIgnoreCase); + + assertEquals("time", sorted[exact]); + assertEquals(2, exact); + assertEquals(exact, caseInsensitive); + } + + @Test + public void whenNullElement_thenArraysHashCodeNotEqual() { + int beforeChange = Arrays.hashCode(intro); + int before = intro.hashCode(); + intro[3] = null; + int after = intro.hashCode(); + int afterChange = Arrays.hashCode(intro); + + assertNotEquals(beforeChange, afterChange); + assertEquals(before, after); + } + + @Test + public void whenNestedArrayNullElement_thenEqualsFailDeepHashPass() { + Object[] looping = new Object[] { intro, intro }; + int deepHashBefore = Arrays.deepHashCode(looping); + int hashBefore = Arrays.hashCode(looping); + + intro[3] = null; + + int hashAfter = Arrays.hashCode(looping); + int deepHashAfter = Arrays.deepHashCode(looping); + + assertEquals(hashAfter, hashBefore); + assertNotEquals(deepHashAfter, deepHashBefore); + } + + @Test + public void whenStreamBadIndex_thenException() { + assertEquals(Arrays.stream(intro).count(), 4); + + exception.expect(ArrayIndexOutOfBoundsException.class); + Arrays.stream(intro, 2, 1).count(); + } + + @Test + public void whenSetAllToUpper_thenAppliedToAllElements() { + String[] longAgo = new String[4]; + Arrays.setAll(longAgo, i -> intro[i].toUpperCase()); + + assertArrayEquals(longAgo, new String[] { "ONCE", "UPON", "A", "TIME" }); + } + + @Test + public void whenToString_thenFormattedArrayString() { + assertEquals("[once, upon, a, time]", Arrays.toString(intro)); + } + + @Test + public void whenNestedArrayDeepString_thenFormattedArraysString() { + String[] end = { "the", "end" }; + Object[] story = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end }; + + assertEquals("[[once, upon, a, time], [chapter one, chapter two], [the, end]]", Arrays.deepToString(story)); + } + + @Test + public void whenAsList_thenImmutableArray() { + List rets = Arrays.asList(intro); + + assertTrue(rets.contains("upon")); + assertTrue(rets.contains("time")); + assertEquals(rets.size(), 4); + + exception.expect(UnsupportedOperationException.class); + rets.add("the"); + } +} diff --git a/core-java/src/test/java/com/baeldung/asciiart/AsciiArtIntegrationTest.java b/core-java/src/test/java/com/baeldung/asciiart/AsciiArtIntegrationTest.java new file mode 100644 index 0000000000..8ab1695395 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/asciiart/AsciiArtIntegrationTest.java @@ -0,0 +1,20 @@ +package com.baeldung.asciiart; + +import java.awt.Font; + +import org.junit.Test; + +import com.baeldung.asciiart.AsciiArt.Settings; + +public class AsciiArtIntegrationTest { + + @Test + public void givenTextWithAsciiCharacterAndSettings_shouldPrintAsciiArt() { + AsciiArt asciiArt = new AsciiArt(); + String text = "BAELDUNG"; + Settings settings = asciiArt.new Settings(new Font("SansSerif", Font.BOLD, 24), text.length() * 30, 30); // 30 pixel width per character + + asciiArt.drawString(text, "*", settings); + } + +} diff --git a/core-java/src/test/java/com/baeldung/asciiart/AsciiArtTest.java b/core-java/src/test/java/com/baeldung/asciiart/AsciiArtTest.java deleted file mode 100644 index 103681894e..0000000000 --- a/core-java/src/test/java/com/baeldung/asciiart/AsciiArtTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.asciiart; - -import java.awt.Font; - -import org.junit.Test; - -import com.baeldung.asciiart.AsciiArt.Settings; - -public class AsciiArtTest { - - @Test - public void givenTextWithAsciiCharacterAndSettings_shouldPrintAsciiArt() { - AsciiArt asciiArt = new AsciiArt(); - String text = "BAELDUNG"; - Settings settings = asciiArt.new Settings(new Font("SansSerif", Font.BOLD, 24), text.length() * 30, 30); // 30 pixel width per character - - asciiArt.drawString(text, "*", settings); - } - -} diff --git a/core-java/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java b/core-java/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java new file mode 100644 index 0000000000..41c67ff389 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java @@ -0,0 +1,95 @@ +package com.baeldung.binding; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.LoggingEvent; +import ch.qos.logback.core.Appender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.slf4j.LoggerFactory; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.verify; + +/** + *https://gist.github.com/bloodredsun/a041de13e57bf3c6c040 + */ +@RunWith(MockitoJUnitRunner.class) + +public class AnimalActivityUnitTest { + + @Mock + private Appender mockAppender; + @Captor + private ArgumentCaptor captorLoggingEvent; + + @Before + public void setup() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.addAppender(mockAppender); + } + + @After + public void teardown() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.detachAppender(mockAppender); + } + + @Test + public void givenAnimalReference__whenRefersAnimalObject_shouldCallFunctionWithAnimalParam() { + + Animal animal = new Animal(); + + AnimalActivity.sleep(animal); + + verify(mockAppender).doAppend(captorLoggingEvent.capture()); + + final LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + + assertThat(loggingEvent.getLevel(), is(Level.INFO)); + + assertThat(loggingEvent.getFormattedMessage(), + is("Animal is sleeping")); + } + + @Test + public void givenDogReference__whenRefersCatObject_shouldCallFunctionWithAnimalParam() { + + Cat cat = new Cat(); + + AnimalActivity.sleep(cat); + + verify(mockAppender).doAppend(captorLoggingEvent.capture()); + + final LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + + assertThat(loggingEvent.getLevel(), is(Level.INFO)); + + assertThat(loggingEvent.getFormattedMessage(), + is("Cat is sleeping")); + } + + @Test + public void givenAnimaReference__whenRefersDogObject_shouldCallFunctionWithAnimalParam() { + + Animal cat = new Cat(); + + AnimalActivity.sleep(cat); + + verify(mockAppender).doAppend(captorLoggingEvent.capture()); + + final LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + + assertThat(loggingEvent.getLevel(), is(Level.INFO)); + + assertThat(loggingEvent.getFormattedMessage(), + is("Animal is sleeping")); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java b/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java new file mode 100644 index 0000000000..a34640b58a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.binding; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.LoggingEvent; +import ch.qos.logback.core.Appender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.slf4j.LoggerFactory; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.util.List; + +/** + * Created by madhumita.g on 01-08-2018. + */ + +@RunWith(MockitoJUnitRunner.class) +public class AnimalUnitTest { + @Mock + private Appender mockAppender; + @Captor + private ArgumentCaptor captorLoggingEvent; + + @Before + public void setup() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.addAppender(mockAppender); + } + + @After + public void teardown() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.detachAppender(mockAppender); + } + + @Test + public void whenCalledWithoutParameters_shouldCallFunctionMakeNoiseWithoutParameters() { + + Animal animal = new Animal(); + + animal.makeNoise(); + + verify(mockAppender).doAppend(captorLoggingEvent.capture()); + + final LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + + assertThat(loggingEvent.getLevel(), is(Level.INFO)); + + assertThat(loggingEvent.getFormattedMessage(), + is("generic animal noise")); + } + + @Test + public void whenCalledWithParameters_shouldCallFunctionMakeNoiseWithParameters() { + + Animal animal = new Animal(); + + int testValue = 3; + animal.makeNoise(testValue); + + verify(mockAppender,times(3)).doAppend(captorLoggingEvent.capture()); + + final List loggingEvents = captorLoggingEvent.getAllValues(); + + for(LoggingEvent loggingEvent : loggingEvents) + { + assertThat(loggingEvent.getLevel(), is(Level.INFO)); + + assertThat(loggingEvent.getFormattedMessage(), + is("generic animal noise countdown "+testValue)); + + testValue--; + } + } + +} diff --git a/core-java/src/test/java/com/baeldung/binding/CatUnitTest.java b/core-java/src/test/java/com/baeldung/binding/CatUnitTest.java new file mode 100644 index 0000000000..76ccfb7719 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/binding/CatUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.binding; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.LoggingEvent; +import ch.qos.logback.core.Appender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.slf4j.LoggerFactory; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.verify; + +/** + * Created by madhumita.g on 01-08-2018. + */ +@RunWith(MockitoJUnitRunner.class) +public class CatUnitTest { + + @Mock + private Appender mockAppender; + + @Captor + private ArgumentCaptor captorLoggingEvent; + + @Before + public void setup() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.addAppender(mockAppender); + } + + @After + public void teardown() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.detachAppender(mockAppender); + } + + @Test + public void makeNoiseTest() { + + Cat cat = new Cat(); + + cat.makeNoise(); + + verify(mockAppender).doAppend(captorLoggingEvent.capture()); + + final LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + + assertThat(loggingEvent.getLevel(), is(Level.INFO)); + + assertThat(loggingEvent.getFormattedMessage(), + is("meow")); + + } +} diff --git a/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueTest.java b/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueTest.java deleted file mode 100644 index 1980497cd3..0000000000 --- a/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.breakcontinue; - -import static com.baeldung.breakcontinue.BreakContinue.labeledBreak; -import static com.baeldung.breakcontinue.BreakContinue.labeledContinue; -import static com.baeldung.breakcontinue.BreakContinue.unlabeledBreak; -import static com.baeldung.breakcontinue.BreakContinue.unlabeledBreakNestedLoops; -import static com.baeldung.breakcontinue.BreakContinue.unlabeledContinue; -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class BreakContinueTest { - - @Test - public void whenUnlabeledBreak_ThenEqual() { - assertEquals(4, unlabeledBreak()); - } - - @Test - public void whenUnlabeledBreakNestedLoops_ThenEqual() { - assertEquals(2, unlabeledBreakNestedLoops()); - } - - @Test - public void whenLabeledBreak_ThenEqual() { - assertEquals(1, labeledBreak()); - } - - @Test - public void whenUnlabeledContinue_ThenEqual() { - assertEquals(5, unlabeledContinue()); - } - - @Test - public void whenLabeledContinue_ThenEqual() { - assertEquals(3, labeledContinue()); - } - -} diff --git a/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueUnitTest.java b/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueUnitTest.java new file mode 100644 index 0000000000..2a2f3be2a9 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.breakcontinue; + +import static com.baeldung.breakcontinue.BreakContinue.labeledBreak; +import static com.baeldung.breakcontinue.BreakContinue.labeledContinue; +import static com.baeldung.breakcontinue.BreakContinue.unlabeledBreak; +import static com.baeldung.breakcontinue.BreakContinue.unlabeledBreakNestedLoops; +import static com.baeldung.breakcontinue.BreakContinue.unlabeledContinue; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class BreakContinueUnitTest { + + @Test + public void whenUnlabeledBreak_ThenEqual() { + assertEquals(4, unlabeledBreak()); + } + + @Test + public void whenUnlabeledBreakNestedLoops_ThenEqual() { + assertEquals(2, unlabeledBreakNestedLoops()); + } + + @Test + public void whenLabeledBreak_ThenEqual() { + assertEquals(1, labeledBreak()); + } + + @Test + public void whenUnlabeledContinue_ThenEqual() { + assertEquals(5, unlabeledContinue()); + } + + @Test + public void whenLabeledContinue_ThenEqual() { + assertEquals(3, labeledContinue()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/casting/CastingTest.java b/core-java/src/test/java/com/baeldung/casting/CastingTest.java deleted file mode 100644 index dd95e0dd80..0000000000 --- a/core-java/src/test/java/com/baeldung/casting/CastingTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.baeldung.casting; - -import org.junit.Test; -import static org.junit.Assert.*; -import java.util.ArrayList; -import java.util.List; - -public class CastingTest { - - @Test - public void whenPrimitiveConverted_thenValueChanged() { - double myDouble = 1.1; - int myInt = (int) myDouble; - - assertNotEquals(myDouble, myInt); - } - - @Test - public void whenUpcast_thenInstanceUnchanged() { - Cat cat = new Cat(); - Animal animal = cat; - animal = (Animal) cat; - assertTrue(animal instanceof Cat); - } - - @Test - public void whenUpcastToObject_thenInstanceUnchanged() { - Object object = new Animal(); - assertTrue(object instanceof Animal); - } - - @Test - public void whenUpcastToInterface_thenInstanceUnchanged() { - Mew mew = new Cat(); - assertTrue(mew instanceof Cat); - } - - @Test - public void whenUpcastToAnimal_thenOverridenMethodsCalled() { - List animals = new ArrayList<>(); - animals.add(new Cat()); - animals.add(new Dog()); - new AnimalFeeder().feed(animals); - } - - @Test - public void whenDowncastToCat_thenMeowIsCalled() { - Animal animal = new Cat(); - ((Cat) animal).meow(); - } - - @Test(expected = ClassCastException.class) - public void whenDownCastWithoutCheck_thenExceptionThrown() { - List animals = new ArrayList<>(); - animals.add(new Cat()); - animals.add(new Dog()); - new AnimalFeeder().uncheckedFeed(animals); - } - - @Test - public void whenDowncastToCatWithCastMethod_thenMeowIsCalled() { - Animal animal = new Cat(); - if (Cat.class.isInstance(animal)) { - Cat cat = Cat.class.cast(animal); - cat.meow(); - } - } - - @Test - public void whenParameterCat_thenOnlyCatsFed() { - List animals = new ArrayList<>(); - animals.add(new Cat()); - animals.add(new Dog()); - AnimalFeederGeneric catFeeder = new AnimalFeederGeneric(Cat.class); - List fedAnimals = catFeeder.feed(animals); - - assertTrue(fedAnimals.size() == 1); - assertTrue(fedAnimals.get(0) instanceof Cat); - } -} diff --git a/core-java/src/test/java/com/baeldung/casting/CastingUnitTest.java b/core-java/src/test/java/com/baeldung/casting/CastingUnitTest.java new file mode 100644 index 0000000000..41eaa5dc1b --- /dev/null +++ b/core-java/src/test/java/com/baeldung/casting/CastingUnitTest.java @@ -0,0 +1,80 @@ +package com.baeldung.casting; + +import org.junit.Test; +import static org.junit.Assert.*; +import java.util.ArrayList; +import java.util.List; + +public class CastingUnitTest { + + @Test + public void whenPrimitiveConverted_thenValueChanged() { + double myDouble = 1.1; + int myInt = (int) myDouble; + + assertNotEquals(myDouble, myInt); + } + + @Test + public void whenUpcast_thenInstanceUnchanged() { + Cat cat = new Cat(); + Animal animal = cat; + animal = (Animal) cat; + assertTrue(animal instanceof Cat); + } + + @Test + public void whenUpcastToObject_thenInstanceUnchanged() { + Object object = new Animal(); + assertTrue(object instanceof Animal); + } + + @Test + public void whenUpcastToInterface_thenInstanceUnchanged() { + Mew mew = new Cat(); + assertTrue(mew instanceof Cat); + } + + @Test + public void whenUpcastToAnimal_thenOverridenMethodsCalled() { + List animals = new ArrayList<>(); + animals.add(new Cat()); + animals.add(new Dog()); + new AnimalFeeder().feed(animals); + } + + @Test + public void whenDowncastToCat_thenMeowIsCalled() { + Animal animal = new Cat(); + ((Cat) animal).meow(); + } + + @Test(expected = ClassCastException.class) + public void whenDownCastWithoutCheck_thenExceptionThrown() { + List animals = new ArrayList<>(); + animals.add(new Cat()); + animals.add(new Dog()); + new AnimalFeeder().uncheckedFeed(animals); + } + + @Test + public void whenDowncastToCatWithCastMethod_thenMeowIsCalled() { + Animal animal = new Cat(); + if (Cat.class.isInstance(animal)) { + Cat cat = Cat.class.cast(animal); + cat.meow(); + } + } + + @Test + public void whenParameterCat_thenOnlyCatsFed() { + List animals = new ArrayList<>(); + animals.add(new Cat()); + animals.add(new Dog()); + AnimalFeederGeneric catFeeder = new AnimalFeederGeneric(Cat.class); + List fedAnimals = catFeeder.feed(animals); + + assertTrue(fedAnimals.size() == 1); + assertTrue(fedAnimals.get(0) instanceof Cat); + } +} diff --git a/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderTest.java b/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderTest.java deleted file mode 100644 index 9f3c751805..0000000000 --- a/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.classloader; - -import org.junit.Test; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -public class CustomClassLoaderTest { - - @Test - public void customLoader() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { - - CustomClassLoader customClassLoader = new CustomClassLoader(); - Class c = customClassLoader.getClass(PrintClassLoader.class.getName()); - - Object ob = c.newInstance(); - - Method md = c.getMethod("printClassLoaders"); - md.invoke(ob); - - } - -} diff --git a/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java b/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java new file mode 100644 index 0000000000..ec35885b84 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.classloader; + +import org.junit.Test; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public class CustomClassLoaderUnitTest { + + @Test + public void customLoader() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { + + CustomClassLoader customClassLoader = new CustomClassLoader(); + Class c = customClassLoader.getClass(PrintClassLoader.class.getName()); + + Object ob = c.newInstance(); + + Method md = c.getMethod("printClassLoaders"); + md.invoke(ob); + + } + +} diff --git a/core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderTest.java b/core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderTest.java deleted file mode 100644 index f44a5cef09..0000000000 --- a/core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.classloader; - -import org.junit.Test; - -import static org.junit.Assert.*; - -public class PrintClassLoaderTest { - @Test(expected = ClassNotFoundException.class) - public void givenAppClassLoader_whenParentClassLoader_thenClassNotFoundException() throws Exception { - PrintClassLoader sampleClassLoader = (PrintClassLoader) Class.forName(PrintClassLoader.class.getName()).newInstance(); - sampleClassLoader.printClassLoaders(); - Class.forName(PrintClassLoader.class.getName(), true, PrintClassLoader.class.getClassLoader().getParent()); - } -} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderUnitTest.java b/core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderUnitTest.java new file mode 100644 index 0000000000..f0d69f4326 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderUnitTest.java @@ -0,0 +1,14 @@ +package com.baeldung.classloader; + +import org.junit.Test; + +import static org.junit.Assert.*; + +public class PrintClassLoaderUnitTest { + @Test(expected = ClassNotFoundException.class) + public void givenAppClassLoader_whenParentClassLoader_thenClassNotFoundException() throws Exception { + PrintClassLoader sampleClassLoader = (PrintClassLoader) Class.forName(PrintClassLoader.class.getName()).newInstance(); + sampleClassLoader.printClassLoaders(); + Class.forName(PrintClassLoader.class.getName(), true, PrintClassLoader.class.getClassLoader().getParent()); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionTest.java b/core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionTest.java deleted file mode 100644 index 8714d084ab..0000000000 --- a/core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionTest.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.classnotfoundexception; - -import org.junit.Test; - -public class ClassNotFoundExceptionTest { - - @Test(expected = ClassNotFoundException.class) - public void givenNoDriversInClassPath_whenLoadDrivers_thenClassNotFoundException() throws ClassNotFoundException { - Class.forName("oracle.jdbc.driver.OracleDriver"); - } -} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionUnitTest.java b/core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionUnitTest.java new file mode 100644 index 0000000000..b076b0324a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionUnitTest.java @@ -0,0 +1,11 @@ +package com.baeldung.classnotfoundexception; + +import org.junit.Test; + +public class ClassNotFoundExceptionUnitTest { + + @Test(expected = ClassNotFoundException.class) + public void givenNoDriversInClassPath_whenLoadDrivers_thenClassNotFoundException() throws ClassNotFoundException { + Class.forName("oracle.jdbc.driver.OracleDriver"); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/constructorsstaticfactorymethods/UserUnitTest.java b/core-java/src/test/java/com/baeldung/constructorsstaticfactorymethods/UserUnitTest.java new file mode 100644 index 0000000000..0c0266a111 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/constructorsstaticfactorymethods/UserUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.constructorsstaticfactorymethods; + +import com.baeldung.constructorsstaticfactorymethods.entities.User; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class UserUnitTest { + + @Test + public void givenUserClass_whenCalledcreateWithDefaultCountry_thenCorrect() { + assertThat(User.createWithDefaultCountry("John", "john@domain.com")).isInstanceOf(User.class); + } + + @Test + public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetName_thenCorrect() { + User user = User.createWithDefaultCountry("John", "john@domain.com"); + assertThat(user.getName()).isEqualTo("John"); + } + + @Test + public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetEmail_thenCorrect() { + User user = User.createWithDefaultCountry("John", "john@domain.com"); + assertThat(user.getEmail()).isEqualTo("john@domain.com"); + } + + @Test + public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetCountry_thenCorrect() { + User user = User.createWithDefaultCountry("John", "john@domain.com"); + assertThat(user.getCountry()).isEqualTo("Argentina"); + } + + @Test + public void givenUserInstanceCreatedWithcreateWithInstantiationTime_whenCalledcreateWithInstantiationTime_thenCorrect() { + assertThat(User.createWithLoggedInstantiationTime("John", "john@domain.com", "Argentina")).isInstanceOf(User.class); + } + + @Test + public void givenUserInstanceCreatedWithgetSingletonIntance_whenCalledgetSingletonInstance_thenCorrect() { + User user1 = User.getSingletonInstance("John", "john@domain.com", "Argentina"); + User user2 = User.getSingletonInstance("John", "john@domain.com", "Argentina"); + assertThat(user1).isEqualTo(user2); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/customexception/IncorrectFileExtensionExceptionUnitTest.java b/core-java/src/test/java/com/baeldung/customexception/IncorrectFileExtensionExceptionUnitTest.java new file mode 100644 index 0000000000..230698f719 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/customexception/IncorrectFileExtensionExceptionUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.customexception; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.File; + +import org.junit.Test; + +public class IncorrectFileExtensionExceptionUnitTest { + + @Test + public void testWhenCorrectFileExtensionGiven_ReceivesNoException() throws IncorrectFileNameException { + assertThat(FileManager.getFirstLine("correctFileNameWithProperExtension.txt")).isEqualTo("Default First Line"); + } + + @Test(expected = IncorrectFileExtensionException.class) + public void testWhenCorrectFileNameExceptionThrown_ReceivesNoException() throws IncorrectFileNameException { + StringBuffer sBuffer = new StringBuffer(); + sBuffer.append("src"); + sBuffer.append(File.separator); + sBuffer.append("test"); + sBuffer.append(File.separator); + sBuffer.append("resources"); + sBuffer.append(File.separator); + sBuffer.append("correctFileNameWithoutProperExtension"); + FileManager.getFirstLine(sBuffer.toString()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/customexception/IncorrectFileNameExceptionUnitTest.java b/core-java/src/test/java/com/baeldung/customexception/IncorrectFileNameExceptionUnitTest.java new file mode 100644 index 0000000000..acb05eb763 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/customexception/IncorrectFileNameExceptionUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.customexception; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class IncorrectFileNameExceptionUnitTest { + + @Test(expected = IncorrectFileNameException.class) + public void testWhenIncorrectFileNameExceptionThrown_ReceivesIncorrectFileNameException() throws IncorrectFileNameException { + FileManager.getFirstLine("wrongFileName.txt"); + } + + @Test + public void testWhenCorrectFileNameExceptionThrown_ReceivesNoException() throws IncorrectFileNameException { + assertThat(FileManager.getFirstLine("correctFileName.txt")).isEqualTo("Default First Line"); + } + +} diff --git a/core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesTest.java b/core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesTest.java deleted file mode 100644 index 8acd4e023e..0000000000 --- a/core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesTest.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.baeldung.decimalformat; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.math.BigDecimal; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.Locale; - -import org.junit.Test; - -public class DecimalFormatExamplesTest { - - double d = 1234567.89; - - @Test - public void givenSimpleDecimal_WhenFormatting_ThenCorrectOutput() { - - assertThat(new DecimalFormat("#.##", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) - .isEqualTo("1234567.89"); - - assertThat(new DecimalFormat("0.00", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) - .isEqualTo("1234567.89"); - - assertThat(new DecimalFormat("#########.###", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) - .isEqualTo("1234567.89"); - - assertThat(new DecimalFormat("000000000.000", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) - .isEqualTo("001234567.890"); - - } - - @Test - public void givenSmallerDecimalPattern_WhenFormatting_ThenRounding() { - - assertThat(new DecimalFormat("#.#", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)).isEqualTo("1234567.9"); - - assertThat(new DecimalFormat("#", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)).isEqualTo("1234568"); - - } - - @Test - public void givenGroupingSeparator_WhenFormatting_ThenGroupedOutput() { - - assertThat(new DecimalFormat("#,###.#", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) - .isEqualTo("1,234,567.9"); - - assertThat(new DecimalFormat("#,###", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) - .isEqualTo("1,234,568"); - - } - - @Test - public void givenMixedPattern_WhenFormatting_ThenCorrectOutput() { - - assertThat(new DecimalFormat("The # number", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) - .isEqualTo("The 1234568 number"); - - assertThat(new DecimalFormat("The '#' # number", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) - .isEqualTo("The # 1234568 number"); - - } - - @Test - public void givenLocales_WhenFormatting_ThenCorrectOutput() { - - assertThat(new DecimalFormat("#,###.##", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) - .isEqualTo("1,234,567.89"); - - assertThat(new DecimalFormat("#,###.##", new DecimalFormatSymbols(Locale.ITALIAN)).format(d)) - .isEqualTo("1.234.567,89"); - - assertThat(new DecimalFormat("#,###.##", DecimalFormatSymbols.getInstance(new Locale("it", "IT"))).format(d)) - .isEqualTo("1.234.567,89"); - - } - - @Test - public void givenE_WhenFormatting_ThenScientificNotation() { - - assertThat(new DecimalFormat("00.#######E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) - .isEqualTo("12.3456789E5"); - - assertThat(new DecimalFormat("000.000000E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) - .isEqualTo("123.456789E4"); - - assertThat(new DecimalFormat("##0.######E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) - .isEqualTo("1.23456789E6"); - - assertThat(new DecimalFormat("###.000000E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) - .isEqualTo("1.23456789E6"); - - } - - @Test - public void givenString_WhenParsing_ThenCorrectOutput() throws ParseException { - - assertThat(new DecimalFormat("", new DecimalFormatSymbols(Locale.ENGLISH)).parse("1234567.89")) - .isEqualTo(1234567.89); - - assertThat(new DecimalFormat("", new DecimalFormatSymbols(Locale.ITALIAN)).parse("1.234.567,89")) - .isEqualTo(1234567.89); - - } - - @Test - public void givenStringAndBigDecimalFlag_WhenParsing_ThenCorrectOutput() throws ParseException { - - NumberFormat nf = new DecimalFormat("", new DecimalFormatSymbols(Locale.ENGLISH)); - ((DecimalFormat) nf).setParseBigDecimal(true); - assertThat(nf.parse("1234567.89")).isEqualTo(BigDecimal.valueOf(1234567.89)); - } - -} diff --git a/core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesUnitTest.java b/core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesUnitTest.java new file mode 100644 index 0000000000..6c3393c254 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesUnitTest.java @@ -0,0 +1,116 @@ +package com.baeldung.decimalformat; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.math.BigDecimal; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.text.NumberFormat; +import java.text.ParseException; +import java.util.Locale; + +import org.junit.Test; + +public class DecimalFormatExamplesUnitTest { + + double d = 1234567.89; + + @Test + public void givenSimpleDecimal_WhenFormatting_ThenCorrectOutput() { + + assertThat(new DecimalFormat("#.##", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) + .isEqualTo("1234567.89"); + + assertThat(new DecimalFormat("0.00", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) + .isEqualTo("1234567.89"); + + assertThat(new DecimalFormat("#########.###", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) + .isEqualTo("1234567.89"); + + assertThat(new DecimalFormat("000000000.000", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) + .isEqualTo("001234567.890"); + + } + + @Test + public void givenSmallerDecimalPattern_WhenFormatting_ThenRounding() { + + assertThat(new DecimalFormat("#.#", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)).isEqualTo("1234567.9"); + + assertThat(new DecimalFormat("#", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)).isEqualTo("1234568"); + + } + + @Test + public void givenGroupingSeparator_WhenFormatting_ThenGroupedOutput() { + + assertThat(new DecimalFormat("#,###.#", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) + .isEqualTo("1,234,567.9"); + + assertThat(new DecimalFormat("#,###", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) + .isEqualTo("1,234,568"); + + } + + @Test + public void givenMixedPattern_WhenFormatting_ThenCorrectOutput() { + + assertThat(new DecimalFormat("The # number", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) + .isEqualTo("The 1234568 number"); + + assertThat(new DecimalFormat("The '#' # number", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) + .isEqualTo("The # 1234568 number"); + + } + + @Test + public void givenLocales_WhenFormatting_ThenCorrectOutput() { + + assertThat(new DecimalFormat("#,###.##", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) + .isEqualTo("1,234,567.89"); + + assertThat(new DecimalFormat("#,###.##", new DecimalFormatSymbols(Locale.ITALIAN)).format(d)) + .isEqualTo("1.234.567,89"); + + assertThat(new DecimalFormat("#,###.##", DecimalFormatSymbols.getInstance(new Locale("it", "IT"))).format(d)) + .isEqualTo("1.234.567,89"); + + } + + @Test + public void givenE_WhenFormatting_ThenScientificNotation() { + + assertThat(new DecimalFormat("00.#######E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) + .isEqualTo("12.3456789E5"); + + assertThat(new DecimalFormat("000.000000E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) + .isEqualTo("123.456789E4"); + + assertThat(new DecimalFormat("##0.######E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) + .isEqualTo("1.23456789E6"); + + assertThat(new DecimalFormat("###.000000E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)) + .isEqualTo("1.23456789E6"); + + } + + @Test + public void givenString_WhenParsing_ThenCorrectOutput() throws ParseException { + + assertThat(new DecimalFormat("", new DecimalFormatSymbols(Locale.ENGLISH)).parse("1234567.89")) + .isEqualTo(1234567.89); + + assertThat(new DecimalFormat("", new DecimalFormatSymbols(Locale.ITALIAN)).parse("1.234.567,89")) + .isEqualTo(1234567.89); + + } + + @Test + public void givenStringAndBigDecimalFlag_WhenParsing_ThenCorrectOutput() throws ParseException { + + NumberFormat nf = new DecimalFormat("", new DecimalFormatSymbols(Locale.ENGLISH)); + ((DecimalFormat) nf).setParseBigDecimal(true); + assertThat(nf.parse("1234567.89")).isEqualTo(BigDecimal.valueOf(1234567.89)); + } + +} diff --git a/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesTest.java b/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesTest.java deleted file mode 100644 index 8fec58f111..0000000000 --- a/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.dst; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; - -import org.junit.Ignore; -import org.junit.Test; - -public class DaylightSavingTimeExamplesTest { - - @Test - public void givenItalianTimeZone_WhenDSTHappens_ThenCorrectlyShiftTimeZone() throws ParseException { - TimeZone.setDefault(TimeZone.getTimeZone("Europe/Rome")); - - TimeZone tz = TimeZone.getTimeZone("Europe/Rome"); - Calendar cal = Calendar.getInstance(tz, Locale.ITALIAN); - DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ITALIAN); - Date dateBeforeDST = df.parse("2018-03-25 01:55"); - prettyPrint(cal.getTimeZone()); - - cal.setTime(dateBeforeDST); - System.out.println("Before DST (00:55 UTC - 01:55 GMT+1) = " + dateBeforeDST); - - System.out.println("With this Calendar " + (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / (60 * 1000) + " minutes must be added to UTC (GMT TimeZone) to get a correct date for this TimeZone\n"); - assertThat(cal.get(Calendar.ZONE_OFFSET)).isEqualTo(3600000); - assertThat(cal.get(Calendar.DST_OFFSET)).isEqualTo(0); - - cal.add(Calendar.MINUTE, 10); - - Date dateAfterDST = cal.getTime(); - - System.out.println(" After DST (01:05 UTC - 03:05 GMT+2) = " + dateAfterDST); - System.out.println("With this Calendar " + (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / (60 * 1000) + " minutes must be added to UTC (GMT TimeZone) to get a correct date for this TimeZone\n"); - assertThat(cal.get(Calendar.DST_OFFSET)).isEqualTo(3600000); - assertThat(dateAfterDST).isEqualTo(df.parse("2018-03-25 03:05")); - - Long deltaBetweenDatesInMillis = dateAfterDST.getTime() - dateBeforeDST.getTime(); - Long tenMinutesInMillis = (1000L * 60 * 10); - assertThat(deltaBetweenDatesInMillis).isEqualTo(tenMinutesInMillis); - } - - private void prettyPrint(TimeZone tz) { - - //@formatter:off - System.out.println(String.format( - " Zone ID = %s (%s)\n" - + " RawOffset = %s minutes\n" - + " DST = %s minutes\n" - + " -----------------------------------------", - tz.getID(), tz.getDisplayName(), tz.getRawOffset()/60000, tz.getDSTSavings()/60000)); - //@formatter:on - } - - @Test - @Ignore - public void whenIterating_ThenPrintAllTimeZones() { - for (String id : TimeZone.getAvailableIDs()) { - TimeZone tz = TimeZone.getTimeZone(id); - prettyPrint(tz); - } - } -} diff --git a/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesTest.java b/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesTest.java deleted file mode 100644 index 78847033ac..0000000000 --- a/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.dst; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.text.ParseException; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.time.temporal.ChronoUnit; -import java.util.TimeZone; - -import org.junit.Test; - -public class DaylightSavingTimeJavaTimeExamplesTest { - - @Test - public void givenItalianTimeZone_WhenDSTHappens_ThenCorrectlyShiftTimeZone() throws ParseException { - ZoneId italianZoneId = ZoneId.of("Europe/Rome"); - - LocalDateTime localDateTimeBeforeDST = LocalDateTime.of(2018, 3, 25, 1, 55); - System.out.println(localDateTimeBeforeDST); - assertThat(localDateTimeBeforeDST.toString()).isEqualTo("2018-03-25T01:55"); - - ZonedDateTime zonedDateTimeBeforeDST = localDateTimeBeforeDST.atZone(italianZoneId); - prettyPrint(zonedDateTimeBeforeDST); - assertThat(zonedDateTimeBeforeDST.toString()).isEqualTo("2018-03-25T01:55+01:00[Europe/Rome]"); - - ZonedDateTime zonedDateTimeAfterDST = zonedDateTimeBeforeDST.plus(10, ChronoUnit.MINUTES); - prettyPrint(zonedDateTimeAfterDST); - assertThat(zonedDateTimeAfterDST.toString()).isEqualTo("2018-03-25T03:05+02:00[Europe/Rome]"); - - Long deltaBetweenDatesInMinutes = ChronoUnit.MINUTES.between(zonedDateTimeBeforeDST, zonedDateTimeAfterDST); - assertThat(deltaBetweenDatesInMinutes).isEqualTo(10); - - } - - private void prettyPrint(ZonedDateTime zdt) { - //@formatter:off - System.out.println(String.format( - " ZonedDateTime = %s\n" - + " Zone ID = %s (%s)\n" - + " RawOffset = %s minutes\n" - + " -----------------------------------------", - zdt, zdt.getZone(), zdt.getZone().getId(), zdt.getOffset().getTotalSeconds()/60)); - //@formatter:on - } - - @Test - public void whenCounting_ThenPrintDifferencesBetweenAPIs() { - System.out.println("Total java.time.ZoneId count : " + ZoneId.getAvailableZoneIds() - .size()); - System.out.println("Total java.util.TimeZone Id count : " + TimeZone.getAvailableIDs().length); - } - - -} diff --git a/core-java/src/test/java/com/baeldung/encrypt/FileEncrypterDecrypterIntegrationTest.java b/core-java/src/test/java/com/baeldung/encrypt/FileEncrypterDecrypterIntegrationTest.java new file mode 100644 index 0000000000..b767a24b16 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/encrypt/FileEncrypterDecrypterIntegrationTest.java @@ -0,0 +1,32 @@ +package com.baeldung.encrypt; + +import org.junit.Test; + +import javax.crypto.KeyGenerator; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; +import java.io.File; +import java.io.IOException; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +public class FileEncrypterDecrypterIntegrationTest { + + @Test + public void givenStringAndFilename_whenEncryptingIntoFile_andDecryptingFileAgain_thenOriginalStringIsReturned() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, InvalidAlgorithmParameterException { + String originalContent = "foobar"; + SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); + + FileEncrypterDecrypter fileEncrypterDecrypter = new FileEncrypterDecrypter(secretKey, "AES/CBC/PKCS5Padding"); + fileEncrypterDecrypter.encrypt(originalContent, "baz.enc"); + + String decryptedContent = fileEncrypterDecrypter.decrypt("baz.enc"); + assertThat(decryptedContent, is(originalContent)); + + new File("baz.enc").delete(); // cleanup + } +} diff --git a/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java index 35aa07821c..70bfe168dd 100644 --- a/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java +++ b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java @@ -75,26 +75,5 @@ public class PizzaUnitTest { pz.setStatus(Pizza.PizzaStatusEnum.READY); pz.deliver(); assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED); - } - - @Test - public void whenConvertedIntoEnum_thenGetsConvertedCorrectly() { - String pizzaEnumValue = "READY"; - PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue); - assertTrue(pizzaStatusEnum == PizzaStatusEnum.READY); - } - - @Test(expected = IllegalArgumentException.class) - public void whenConvertedIntoEnum_thenThrowsException() { - String pizzaEnumValue = "rEAdY"; - PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue); - } - - @Test(expected = IllegalArgumentException.class) - public void givenInvalidEnumValueContentWiseAsString_whenConvertedIntoEnum_thenThrowsException() { - String pizzaEnumValue = "invalid"; - PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue); - } - - + } } diff --git a/core-java/src/test/java/com/baeldung/exceptionhandling/ExceptionsUnitTest.java b/core-java/src/test/java/com/baeldung/exceptionhandling/ExceptionsUnitTest.java new file mode 100644 index 0000000000..b3f585cfe4 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/exceptionhandling/ExceptionsUnitTest.java @@ -0,0 +1,80 @@ +package com.baeldung.exceptionhandling; + +import org.junit.Test; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.file.NoSuchFileException; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +public class ExceptionsUnitTest { + + Exceptions exceptions = new Exceptions(); + + @Test + public void getPlayers() { + assertThatThrownBy(() -> exceptions.getPlayers()) + .isInstanceOf(NoSuchFileException.class); + } + + @Test + public void loadAllPlayers() { + assertThatThrownBy(() -> exceptions.loadAllPlayers("")) + .isInstanceOf(IllegalStateException.class); + } + + @Test + public void getPlayerScoreThrows() { + assertThatThrownBy(() -> exceptions.getPlayerScoreThrows("")) + .isInstanceOf(FileNotFoundException.class); + } + + @Test + public void getPlayerScoreTryCatch() { + assertThatThrownBy(() -> exceptions.getPlayerScoreTryCatch("")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void getPlayerScoreFinally() { + assertThatThrownBy(() -> exceptions.getPlayerScoreFinally("")) + .isInstanceOf(FileNotFoundException.class); + } + + @Test + public void loadAllPlayersThrowingChecked() { + assertThatThrownBy(() -> exceptions.loadAllPlayersThrowingChecked("")) + .isInstanceOf(TimeoutException.class); + } + + @Test + public void loadAllPlayersThrowingUnchecked() { + assertThatThrownBy(() -> exceptions.loadAllPlayersThrowingUnchecked("")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void loadAllPlayersWrapping() { + assertThatThrownBy(() -> exceptions.loadAllPlayersWrapping("")) + .isInstanceOf(IOException.class); + } + + @Test + public void loadAllPlayersRethrowing() { + assertThatThrownBy(() -> exceptions.loadAllPlayersRethrowing("")) + .isInstanceOf(PlayerLoadException.class); + } + + @Test + public void loadAllPlayersThrowable() { + assertThatThrownBy(() -> exceptions.loadAllPlayersThrowable("")) + .isInstanceOf(NullPointerException.class); + } + + @Test + public void getPlayerScoreSwallowingExceptionAntiPatternAlternative2() { + assertThatThrownBy(() -> exceptions.getPlayerScoreSwallowingExceptionAntiPatternAlternative2("")) + .isInstanceOf(PlayerScoreException.class); + } +} diff --git a/core-java/src/test/java/com/baeldung/exceptions/GlobalExceptionHandlerUnitTest.java b/core-java/src/test/java/com/baeldung/exceptions/GlobalExceptionHandlerUnitTest.java new file mode 100644 index 0000000000..394de9c576 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/exceptions/GlobalExceptionHandlerUnitTest.java @@ -0,0 +1,64 @@ +package com.baeldung.exceptions; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.slf4j.LoggerFactory; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.classic.spi.LoggingEvent; +import ch.qos.logback.core.Appender; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verify; + +@RunWith(MockitoJUnitRunner.class) +public class GlobalExceptionHandlerUnitTest { + + @Mock + private Appender mockAppender; + + @Captor + private ArgumentCaptor captorLoggingEvent; + + @Before + public void setup() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.addAppender(mockAppender); + + Handler globalExceptionHandler = new Handler(); + Thread.setDefaultUncaughtExceptionHandler(globalExceptionHandler); + } + + @After + public void teardown() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.detachAppender(mockAppender); + } + + @Test + public void whenArithmeticException_thenUseUncaughtExceptionHandler() throws InterruptedException { + + Thread globalExceptionHandlerThread = new Thread() { + public void run() { + GlobalExceptionHandler globalExceptionHandlerObj = new GlobalExceptionHandler(); + globalExceptionHandlerObj.performArithmeticOperation(99, 0); + } + }; + + globalExceptionHandlerThread.start(); + globalExceptionHandlerThread.join(); + + verify(mockAppender).doAppend(captorLoggingEvent.capture()); + LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + + assertThat(loggingEvent.getLevel()).isEqualTo(Level.INFO); + assertThat(loggingEvent.getFormattedMessage()).isEqualTo("Unhandled exception caught!"); + } + +} diff --git a/core-java/src/test/java/com/baeldung/extension/ExtensionUnitTest.java b/core-java/src/test/java/com/baeldung/extension/ExtensionUnitTest.java new file mode 100644 index 0000000000..680eea0cae --- /dev/null +++ b/core-java/src/test/java/com/baeldung/extension/ExtensionUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.extension; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.Optional; + +public class ExtensionUnitTest { + private Extension extension = new Extension(); + + @Test + public void getExtension_whenApacheCommonIO_thenExtensionIsTrue() { + String expectedExtension = "txt"; + String actualExtension = extension.getExtensionByApacheCommonLib("jarvis.txt"); + Assert.assertEquals(expectedExtension, actualExtension); + } + + @Test + public void getExtension_whenStringHandle_thenExtensionIsTrue() { + String expectedExtension = "java"; + Optional actualExtension = extension.getExtensionByStringHandling("Demo.java"); + Assert.assertEquals(expectedExtension, actualExtension.get()); + } + + @Test + public void getExtension_whenGuava_thenExtensionIsTrue() { + String expectedExtension = "class"; + String actualExtension = extension.getExtensionByGuava("baeldung/Demo.class"); + Assert.assertEquals(expectedExtension, actualExtension); + } +} diff --git a/core-java/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java b/core-java/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java new file mode 100644 index 0000000000..78f900d796 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class BufferedReaderUnitTest { + + protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetArrayList() throws IOException { + List lines = BufferedReaderExample.generateArrayListFromFile(TEXT_FILENAME); + assertTrue("File does not has 2 lines", lines.size() == 2); + } +} diff --git a/core-java/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java b/core-java/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java new file mode 100644 index 0000000000..a38e58d348 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class FileReaderUnitTest { + + protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetArrayList() throws IOException { + List lines = FileReaderExample.generateArrayListFromFile(TEXT_FILENAME); + assertTrue("File does not has 2 lines", lines.size() == 2); + } +} diff --git a/core-java/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java b/core-java/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java new file mode 100644 index 0000000000..c0b742fd47 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class FilesReadAllLinesUnitTest { + + protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetArrayList() throws IOException { + List lines = FilesReadLinesExample.generateArrayListFromFile(TEXT_FILENAME); + assertTrue("File does not has 2 lines", lines.size() == 2); + } +} diff --git a/core-java/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java b/core-java/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java new file mode 100644 index 0000000000..0a398ba7c6 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class ScannerIntUnitTest { + + protected static final String NUMBER_FILENAME = "src/test/resources/sampleNumberFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetIntArrayList() throws IOException { + List numbers = ScannerIntExample.generateArrayListFromFile(NUMBER_FILENAME); + assertTrue("File does not has 2 lines", numbers.size() == 2); + } +} diff --git a/core-java/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java b/core-java/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java new file mode 100644 index 0000000000..8f9b0a56c0 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class ScannerStringUnitTest { + + protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetArrayList() throws IOException { + List lines = ScannerStringExample.generateArrayListFromFile(TEXT_FILENAME); + assertTrue("File does not has 2 lines", lines.size() == 2); + } +} diff --git a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java deleted file mode 100644 index 60950fae7a..0000000000 --- a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.hashcode.application; - -import com.baeldung.hashcode.entities.User; -import org.junit.Test; - -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertTrue; - -public class ApplicationTest { - - @Test - public void main_NoInputState_TextPrintedToConsole() throws Exception { - Map users = new HashMap<>(); - User user1 = new User(1L, "John", "john@domain.com"); - User user2 = new User(2L, "Jennifer", "jennifer@domain.com"); - User user3 = new User(3L, "Mary", "mary@domain.com"); - - users.put(user1, user1); - users.put(user2, user2); - users.put(user3, user3); - - assertTrue(users.containsKey(user1)); - } -} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationUnitTest.java b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationUnitTest.java new file mode 100644 index 0000000000..49857f355a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.hashcode.application; + +import com.baeldung.hashcode.entities.User; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertTrue; + +public class ApplicationUnitTest { + + @Test + public void main_NoInputState_TextPrintedToConsole() throws Exception { + Map users = new HashMap<>(); + User user1 = new User(1L, "John", "john@domain.com"); + User user2 = new User(2L, "Jennifer", "jennifer@domain.com"); + User user3 = new User(3L, "Mary", "mary@domain.com"); + + users.put(user1, user1); + users.put(user2, user2); + users.put(user3, user3); + + assertTrue(users.containsKey(user1)); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java b/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java deleted file mode 100644 index e356b4beef..0000000000 --- a/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.hashcode.entities; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -public class UserTest { - - private User user; - private User comparisonUser; - - @Before - public void setUpUserInstances() { - this.user = new User(1L, "test", "test@domain.com"); - this.comparisonUser = this.user; - } - - @After - public void tearDownUserInstances() { - user = null; - comparisonUser = null; - } - - @Test - public void equals_EqualUserInstance_TrueAssertion() { - Assert.assertTrue(user.equals(comparisonUser)); - } - - @Test - public void hashCode_UserHash_TrueAssertion() { - Assert.assertEquals(1792276941, user.hashCode()); - } -} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/hashcode/entities/UserUnitTest.java b/core-java/src/test/java/com/baeldung/hashcode/entities/UserUnitTest.java new file mode 100644 index 0000000000..44ea7efed1 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/hashcode/entities/UserUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.hashcode.entities; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class UserUnitTest { + + private User user; + private User comparisonUser; + + @Before + public void setUpUserInstances() { + this.user = new User(1L, "test", "test@domain.com"); + this.comparisonUser = this.user; + } + + @After + public void tearDownUserInstances() { + user = null; + comparisonUser = null; + } + + @Test + public void equals_EqualUserInstance_TrueAssertion() { + Assert.assertTrue(user.equals(comparisonUser)); + } + + @Test + public void hashCode_UserHash_TrueAssertion() { + Assert.assertEquals(1792276941, user.hashCode()); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/immutableobjects/ImmutableObjectsUnitTest.java b/core-java/src/test/java/com/baeldung/immutableobjects/ImmutableObjectsUnitTest.java new file mode 100644 index 0000000000..01dfeac050 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/immutableobjects/ImmutableObjectsUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.immutableobjects; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +public class ImmutableObjectsUnitTest { + + @Test + public void whenCallingStringReplace_thenStringDoesNotMutate() { + // 2. What's an Immutable Object? + final String name = "baeldung"; + final String newName = name.replace("dung", "----"); + + assertEquals("baeldung", name); + assertEquals("bael----", newName); + } + + public void whenReassignFinalValue_thenCompilerError() { + // 3. The final Keyword in Java (1) + final String name = "baeldung"; + // name = "bael..."; + } + + @Test + public void whenAddingElementToList_thenSizeChange() { + // 3. The final Keyword in Java (2) + final List strings = new ArrayList<>(); + assertEquals(0, strings.size()); + strings.add("baeldung"); + assertEquals(1, strings.size()); + } +} diff --git a/core-java/src/test/java/com/baeldung/inheritance/AppTest.java b/core-java/src/test/java/com/baeldung/inheritance/AppTest.java deleted file mode 100644 index 1235761aba..0000000000 --- a/core-java/src/test/java/com/baeldung/inheritance/AppTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.inheritance; - -import com.baeldung.inheritance.*; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class AppTest extends TestCase { - - public AppTest(String testName) { - super( testName ); - } - - public static Test suite() { - return new TestSuite(AppTest.class); - } - - @SuppressWarnings("static-access") - public void testStaticMethodUsingBaseClassVariable() { - Car first = new ArmoredCar(); - assertEquals("Car", first.msg()); - } - - @SuppressWarnings("static-access") - public void testStaticMethodUsingDerivedClassVariable() { - ArmoredCar second = new ArmoredCar(); - assertEquals("ArmoredCar", second.msg()); - } - - public void testAssignArmoredCarToCar() { - Employee e1 = new Employee("Shreya", new ArmoredCar()); - assertNotNull(e1.getCar()); - } - - public void testAssignSpaceCarToCar() { - Employee e2 = new Employee("Paul", new SpaceCar()); - assertNotNull(e2.getCar()); - } - - public void testBMWToCar() { - Employee e3 = new Employee("Pavni", new BMW()); - assertNotNull(e3.getCar()); - } - -} diff --git a/core-java/src/test/java/com/baeldung/inheritance/AppUnitTest.java b/core-java/src/test/java/com/baeldung/inheritance/AppUnitTest.java new file mode 100644 index 0000000000..1c3c2fff35 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/inheritance/AppUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.inheritance; + +import com.baeldung.inheritance.*; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +public class AppUnitTest extends TestCase { + + public AppUnitTest(String testName) { + super( testName ); + } + + public static Test suite() { + return new TestSuite(AppUnitTest.class); + } + + @SuppressWarnings("static-access") + public void testStaticMethodUsingBaseClassVariable() { + Car first = new ArmoredCar(); + assertEquals("Car", first.msg()); + } + + @SuppressWarnings("static-access") + public void testStaticMethodUsingDerivedClassVariable() { + ArmoredCar second = new ArmoredCar(); + assertEquals("ArmoredCar", second.msg()); + } + + public void testAssignArmoredCarToCar() { + Employee e1 = new Employee("Shreya", new ArmoredCar()); + assertNotNull(e1.getCar()); + } + + public void testAssignSpaceCarToCar() { + Employee e2 = new Employee("Paul", new SpaceCar()); + assertNotNull(e2.getCar()); + } + + public void testBMWToCar() { + Employee e3 = new Employee("Pavni", new BMW()); + assertNotNull(e3.getCar()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/initializationguide/UserTest.java b/core-java/src/test/java/com/baeldung/initializationguide/UserTest.java deleted file mode 100644 index 8d352ba706..0000000000 --- a/core-java/src/test/java/com/baeldung/initializationguide/UserTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.initializationguide; -import org.junit.Before; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.*; - -import java.lang.reflect.InvocationTargetException; - -public class UserTest { - - @Test - public void givenUserInstance_whenIntializedWithNew_thenInstanceIsNotNull() { - User user = new User("Alice", 1); - assertThat(user).isNotNull(); - } - - @Test - public void givenUserInstance_whenInitializedWithReflection_thenInstanceIsNotNull() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - User user = User.class.getConstructor(String.class, int.class) - .newInstance("Alice", 2); - assertThat(user).isNotNull(); - } - - @Test - public void givenUserInstance_whenCopiedWithClone_thenExactMatchIsCreated() throws CloneNotSupportedException { - User user = new User("Alice", 3); - User clonedUser = (User) user.clone(); - assertThat(clonedUser).isEqualTo(user); - } - - @Test - public void givenUserInstance_whenValuesAreNotInitialized_thenUserNameAndIdReturnDefault() { - User user = new User(); - assertThat(user.getName()).isNull(); - assertThat(user.getId() == 0); - } -} diff --git a/core-java/src/test/java/com/baeldung/initializationguide/UserUnitTest.java b/core-java/src/test/java/com/baeldung/initializationguide/UserUnitTest.java new file mode 100644 index 0000000000..f74384e6f7 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/initializationguide/UserUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.initializationguide; +import org.junit.Before; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.*; + +import java.lang.reflect.InvocationTargetException; + +public class UserUnitTest { + + @Test + public void givenUserInstance_whenIntializedWithNew_thenInstanceIsNotNull() { + User user = new User("Alice", 1); + assertThat(user).isNotNull(); + } + + @Test + public void givenUserInstance_whenInitializedWithReflection_thenInstanceIsNotNull() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { + User user = User.class.getConstructor(String.class, int.class) + .newInstance("Alice", 2); + assertThat(user).isNotNull(); + } + + @Test + public void givenUserInstance_whenCopiedWithClone_thenExactMatchIsCreated() throws CloneNotSupportedException { + User user = new User("Alice", 3); + User clonedUser = (User) user.clone(); + assertThat(clonedUser).isEqualTo(user); + } + + @Test + public void givenUserInstance_whenValuesAreNotInitialized_thenUserNameAndIdReturnDefault() { + User user = new User(); + assertThat(user.getName()).isNull(); + assertThat(user.getId() == 0); + } +} diff --git a/core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceTests.java b/core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceTests.java deleted file mode 100644 index b19ed76189..0000000000 --- a/core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceTests.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.interfaces; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -@RunWith(JUnit4.class) -public class InnerInterfaceTests { - @Test - public void whenCustomerListJoined_thenReturnsJoinedNames() { - Customer.List customerList = new CommaSeparatedCustomers(); - customerList.Add(new Customer("customer1")); - customerList.Add(new Customer("customer2")); - assertEquals("customer1,customer2", customerList.getCustomerNames()); - } -} diff --git a/core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceUnitTest.java b/core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceUnitTest.java new file mode 100644 index 0000000000..65d7c860a8 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.interfaces; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class InnerInterfaceUnitTest { + @Test + public void whenCustomerListJoined_thenReturnsJoinedNames() { + Customer.List customerList = new CommaSeparatedCustomers(); + customerList.Add(new Customer("customer1")); + customerList.Add(new Customer("customer2")); + assertEquals("customer1,customer2", customerList.getCustomerNames()); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderTest.java b/core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderTest.java deleted file mode 100644 index 9a231a9a3d..0000000000 --- a/core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.java.currentmethod; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * The class presents various ways of finding the name of currently executed method. - */ -public class CurrentlyExecutedMethodFinderTest { - - @Test - public void givenCurrentThread_whenGetStackTrace_thenFindMethod() { - final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); - assertEquals("givenCurrentThread_whenGetStackTrace_thenFindMethod", stackTrace[1].getMethodName()); - } - - @Test - public void givenException_whenGetStackTrace_thenFindMethod() { - String methodName = new Exception().getStackTrace()[0].getMethodName(); - assertEquals("givenException_whenGetStackTrace_thenFindMethod", methodName); - } - - @Test - public void givenThrowable_whenGetStacktrace_thenFindMethod() { - StackTraceElement[] stackTrace = new Throwable().getStackTrace(); - assertEquals("givenThrowable_whenGetStacktrace_thenFindMethod", stackTrace[0].getMethodName()); - } - - @Test - public void givenObject_whenGetEnclosingMethod_thenFindMethod() { - String methodName = new Object() {}.getClass().getEnclosingMethod().getName(); - assertEquals("givenObject_whenGetEnclosingMethod_thenFindMethod", methodName); - } - - @Test - public void givenLocal_whenGetEnclosingMethod_thenFindMethod() { - class Local {}; - String methodName = Local.class.getEnclosingMethod().getName(); - assertEquals("givenLocal_whenGetEnclosingMethod_thenFindMethod", methodName); - } - -} diff --git a/core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderUnitTest.java b/core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderUnitTest.java new file mode 100644 index 0000000000..43ebdee688 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.java.currentmethod; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * The class presents various ways of finding the name of currently executed method. + */ +public class CurrentlyExecutedMethodFinderUnitTest { + + @Test + public void givenCurrentThread_whenGetStackTrace_thenFindMethod() { + final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); + assertEquals("givenCurrentThread_whenGetStackTrace_thenFindMethod", stackTrace[1].getMethodName()); + } + + @Test + public void givenException_whenGetStackTrace_thenFindMethod() { + String methodName = new Exception().getStackTrace()[0].getMethodName(); + assertEquals("givenException_whenGetStackTrace_thenFindMethod", methodName); + } + + @Test + public void givenThrowable_whenGetStacktrace_thenFindMethod() { + StackTraceElement[] stackTrace = new Throwable().getStackTrace(); + assertEquals("givenThrowable_whenGetStacktrace_thenFindMethod", stackTrace[0].getMethodName()); + } + + @Test + public void givenObject_whenGetEnclosingMethod_thenFindMethod() { + String methodName = new Object() {}.getClass().getEnclosingMethod().getName(); + assertEquals("givenObject_whenGetEnclosingMethod_thenFindMethod", methodName); + } + + @Test + public void givenLocal_whenGetEnclosingMethod_thenFindMethod() { + class Local {}; + String methodName = Local.class.getEnclosingMethod().getName(); + assertEquals("givenLocal_whenGetEnclosingMethod_thenFindMethod", methodName); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java b/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java new file mode 100644 index 0000000000..b484eecef7 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.java.listInitialization; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import lombok.extern.java.Log; + +import org.junit.Assert; +import org.junit.Test; + +@Log +public class ListInitializationUnitTest { + + @Test + public void givenAnonymousInnerClass_thenInitialiseList() { + List cities = new ArrayList() { + { + add("New York"); + add("Rio"); + add("Tokyo"); + } + }; + + Assert.assertTrue(cities.contains("New York")); + } + + @Test + public void givenArraysAsList_thenInitialiseList() { + List list = Arrays.asList("foo", "bar"); + + Assert.assertTrue(list.contains("foo")); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenArraysAsList_whenAdd_thenUnsupportedException() { + List list = Arrays.asList("foo", "bar"); + + list.add("baz"); + } + + @Test + public void givenArrayAsList_whenCreated_thenShareReference() { + String[] array = { "foo", "bar" }; + List list = Arrays.asList(array); + array[0] = "baz"; + Assert.assertEquals("baz", list.get(0)); + } + + @Test + public void givenStream_thenInitializeList() { + List list = Stream.of("foo", "bar") + .collect(Collectors.toList()); + + Assert.assertTrue(list.contains("foo")); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/mimetype/MimeTypeUnitTest.java b/core-java/src/test/java/com/baeldung/java/mimetype/MimeTypeUnitTest.java new file mode 100644 index 0000000000..c8da2c1339 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/mimetype/MimeTypeUnitTest.java @@ -0,0 +1,131 @@ +package com.baeldung.java.mimetype; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; +import java.net.FileNameMap; +import java.net.MalformedURLException; +import java.net.URLConnection; +import java.nio.file.Files; +import java.nio.file.Path; + +import javax.activation.MimetypesFileTypeMap; + +import org.apache.tika.Tika; +import org.junit.Test; + +import net.sf.jmimemagic.Magic; +import net.sf.jmimemagic.MagicException; +import net.sf.jmimemagic.MagicMatch; +import net.sf.jmimemagic.MagicMatchNotFoundException; +import net.sf.jmimemagic.MagicParseException; + +/** + * Test class demonstrating various strategies to resolve MIME type of a file. + * @author tritty + * + */ +public class MimeTypeUnitTest { + /** + * Expected Ouput. + */ + public static final String PNG_EXT = "image/png"; + + /** + * The location of the file. + */ + public static final String FILE_LOC = "src/test/resources/product.png"; + + /** + * Test method, demonstrating usage in Java 7. + * + * @throws IOException + */ + @Test + public void whenUsingJava7_thenSuccess() throws IOException { + final Path path = new File(FILE_LOC).toPath(); + final String mimeType = Files.probeContentType(path); + assertEquals(mimeType, PNG_EXT); + } + + /** + * Test method demonstrating the usage of URLConnection to resolve MIME type. + * + * @throws MalformedURLException + * @throws IOException + */ + @Test + public void whenUsingGetContentType_thenSuccess() throws MalformedURLException, IOException { + final File file = new File(FILE_LOC); + final URLConnection connection = file.toURL() + .openConnection(); + final String mimeType = connection.getContentType(); + assertEquals(mimeType, PNG_EXT); + } + + /** + * Test method demonstrating the usage of URLConnection to resolve MIME type. + * + */ + @Test + public void whenUsingGuessContentTypeFromName_thenSuccess() { + final File file = new File(FILE_LOC); + final String mimeType = URLConnection.guessContentTypeFromName(file.getName()); + assertEquals(mimeType, PNG_EXT); + } + + /** + * Test method demonstrating the usage of FileNameMap from URLConnection + * to resolve MIME type of a file. + * + */ + @Test + public void whenUsingGetFileNameMap_thenSuccess() { + final File file = new File(FILE_LOC); + final FileNameMap fileNameMap = URLConnection.getFileNameMap(); + final String mimeType = fileNameMap.getContentTypeFor(file.getName()); + assertEquals(mimeType, PNG_EXT); + } + + /** + * Test method demonstrating the usage of MimeTypesFileTypeMap for resolution of + * MIME type. + * + */ + @Test + public void whenUsingMimeTypesFileTypeMap_thenSuccess() { + final File file = new File(FILE_LOC); + final MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap(); + final String mimeType = fileTypeMap.getContentType(file.getName()); + assertEquals(mimeType, PNG_EXT); + } + + /** + * Test method demonstrating usage of jMimeMagic. + * + * @throws MagicParseException + * @throws MagicMatchNotFoundException + * @throws MagicException + */ + @Test + public void whenUsingJmimeMagic_thenSuccess() throws MagicParseException, MagicMatchNotFoundException, MagicException { + final File file = new File(FILE_LOC); + final Magic magic = new Magic(); + final MagicMatch match = magic.getMagicMatch(file, false); + assertEquals(match.getMimeType(), PNG_EXT); + } + + /** + * Test method demonstrating usage of Apache Tika. + * + * @throws IOException + */ + @Test + public void whenUsingTika_thenSuccess() throws IOException { + final File file = new File(FILE_LOC); + final Tika tika = new Tika(); + final String mimeType = tika.detect(file); + assertEquals(mimeType, PNG_EXT); + } +} diff --git a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoLiveTest.java b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoLiveTest.java new file mode 100644 index 0000000000..0c312ff613 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoLiveTest.java @@ -0,0 +1,65 @@ +package com.baeldung.javanetworking.uriurl.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; + +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.javanetworking.uriurl.URLDemo; + +@FixMethodOrder +public class URIDemoLiveTest { + private final Logger log = LoggerFactory.getLogger(URIDemoLiveTest.class); + String URISTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484"; + // parsed locator + static String URISCHEME = "https"; + String URISCHEMESPECIFIC; + static String URIHOST = "wordpress.org"; + static String URIAUTHORITY = "wordpress.org:443"; + + static String URIPATH = "/support/topic/page-jumps-within-wordpress/"; + int URIPORT = 443; + static int URIDEFAULTPORT = 443; + static String URIQUERY = "replies=3"; + static String URIFRAGMENT = "post-2278484"; + static String URICOMPOUND = URISCHEME + "://" + URIHOST + ":" + URIDEFAULTPORT + URIPATH + "?" + URIQUERY + "#" + URIFRAGMENT; + + static URI uri; + URL url; + BufferedReader in = null; + String URIContent = ""; + + @BeforeClass + public static void givenEmplyURL_whenInitializeURL_thenSuccess() throws URISyntaxException { + uri = new URI(URICOMPOUND); + } + + // check parsed URL + @Test + public void givenURI_whenURIIsParsed_thenSuccess() { + assertNotNull("URI is null", uri); + assertEquals("URI string is not equal", uri.toString(), URISTRING); + assertEquals("Scheme is not equal", uri.getScheme(), URISCHEME); + assertEquals("Authority is not equal", uri.getAuthority(), URIAUTHORITY); + assertEquals("Host string is not equal", uri.getHost(), URIHOST); + assertEquals("Path string is not equal", uri.getPath(), URIPATH); + assertEquals("Port number is not equal", uri.getPort(), URIPORT); + assertEquals("Query string is not equal", uri.getQuery(), URIQUERY); + assertEquals("Fragment string is not equal", uri.getFragment(), URIFRAGMENT); + } +} diff --git a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoTest.java b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoTest.java deleted file mode 100644 index c429039e3d..0000000000 --- a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.baeldung.javanetworking.uriurl.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLConnection; - -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.baeldung.javanetworking.uriurl.URLDemo; - -@FixMethodOrder -public class URIDemoTest { - private final Logger log = LoggerFactory.getLogger(URIDemoTest.class); - String URISTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484"; - // parsed locator - static String URISCHEME = "https"; - String URISCHEMESPECIFIC; - static String URIHOST = "wordpress.org"; - static String URIAUTHORITY = "wordpress.org:443"; - - static String URIPATH = "/support/topic/page-jumps-within-wordpress/"; - int URIPORT = 443; - static int URIDEFAULTPORT = 443; - static String URIQUERY = "replies=3"; - static String URIFRAGMENT = "post-2278484"; - static String URICOMPOUND = URISCHEME + "://" + URIHOST + ":" + URIDEFAULTPORT + URIPATH + "?" + URIQUERY + "#" + URIFRAGMENT; - - static URI uri; - URL url; - BufferedReader in = null; - String URIContent = ""; - - @BeforeClass - public static void givenEmplyURL_whenInitializeURL_thenSuccess() throws URISyntaxException { - uri = new URI(URICOMPOUND); - } - - // check parsed URL - @Test - public void givenURI_whenURIIsParsed_thenSuccess() { - assertNotNull("URI is null", uri); - assertEquals("URI string is not equal", uri.toString(), URISTRING); - assertEquals("Scheme is not equal", uri.getScheme(), URISCHEME); - assertEquals("Authority is not equal", uri.getAuthority(), URIAUTHORITY); - assertEquals("Host string is not equal", uri.getHost(), URIHOST); - assertEquals("Path string is not equal", uri.getPath(), URIPATH); - assertEquals("Port number is not equal", uri.getPort(), URIPORT); - assertEquals("Query string is not equal", uri.getQuery(), URIQUERY); - assertEquals("Fragment string is not equal", uri.getFragment(), URIFRAGMENT); - } -} diff --git a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoLiveTest.java b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoLiveTest.java new file mode 100644 index 0000000000..15f53ed878 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoLiveTest.java @@ -0,0 +1,106 @@ +package com.baeldung.javanetworking.uriurl.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; + +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.javanetworking.uriurl.URLDemo; + +@FixMethodOrder +public class URLDemoLiveTest { + private final Logger log = LoggerFactory.getLogger(URLDemoLiveTest.class); + static String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484"; + // parsed locator + static String URLPROTOCOL = "https"; + String URLAUTHORITY = "wordpress.org:443"; + static String URLHOST = "wordpress.org"; + static String URLPATH = "/support/topic/page-jumps-within-wordpress/"; + String URLFILENAME = "/support/topic/page-jumps-within-wordpress/?replies=3"; + int URLPORT = 443; + static int URLDEFAULTPORT = 443; + static String URLQUERY = "replies=3"; + static String URLREFERENCE = "post-2278484"; + static String URLCOMPOUND = URLPROTOCOL + "://" + URLHOST + ":" + URLDEFAULTPORT + URLPATH + "?" + URLQUERY + "#" + URLREFERENCE; + + static URL url; + URLConnection urlConnection = null; + HttpURLConnection connection = null; + BufferedReader in = null; + String urlContent = ""; + + @BeforeClass + public static void givenEmplyURL_whenInitializeURL_thenSuccess() throws MalformedURLException { + url = new URL(URLCOMPOUND); + } + + // check parsed URL + @Test + public void givenURL_whenURLIsParsed_thenSuccess() { + assertNotNull("URL is null", url); + assertEquals("URL string is not equal", url.toString(), URLSTRING); + assertEquals("Protocol is not equal", url.getProtocol(), URLPROTOCOL); + assertEquals("Authority is not equal", url.getAuthority(), URLAUTHORITY); + assertEquals("Host string is not equal", url.getHost(), URLHOST); + assertEquals("Path string is not equal", url.getPath(), URLPATH); + assertEquals("File string is not equal", url.getFile(), URLFILENAME); + assertEquals("Port number is not equal", url.getPort(), URLPORT); + assertEquals("Default port number is not equal", url.getDefaultPort(), URLDEFAULTPORT); + assertEquals("Query string is not equal", url.getQuery(), URLQUERY); + assertEquals("Reference string is not equal", url.getRef(), URLREFERENCE); + } + + // Obtain the content from location + @Test + public void givenURL_whenOpenConnectionAndContentIsNotEmpty_thenSuccess() throws IOException { + try { + urlConnection = url.openConnection(); + } catch (IOException ex) { + urlConnection = null; + ex.printStackTrace(); + } + assertNotNull("URL Connection is null", urlConnection); + + connection = null; + assertTrue("URLConnection is not HttpURLConnection", urlConnection instanceof HttpURLConnection); + if (urlConnection instanceof HttpURLConnection) { + connection = (HttpURLConnection) urlConnection; + } + assertNotNull("Connection is null", connection); + + log.info(connection.getResponseCode() + " " + connection.getResponseMessage()); + + try { + in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + } catch (IOException ex) { + in = null; + ex.printStackTrace(); + } + assertNotNull("Input stream failed", in); + + String current; + try { + while ((current = in.readLine()) != null) { + urlContent += current; + } + } catch (IOException ex) { + urlContent = null; + ex.printStackTrace(); + } + assertNotNull("Content is null", urlContent); + assertTrue("Content is empty", urlContent.length() > 0); + } +} diff --git a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoTest.java b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoTest.java deleted file mode 100644 index 47cbf539a5..0000000000 --- a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoTest.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.baeldung.javanetworking.uriurl.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; - -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.baeldung.javanetworking.uriurl.URLDemo; - -@FixMethodOrder -public class URLDemoTest { - private final Logger log = LoggerFactory.getLogger(URLDemoTest.class); - static String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484"; - // parsed locator - static String URLPROTOCOL = "https"; - String URLAUTHORITY = "wordpress.org:443"; - static String URLHOST = "wordpress.org"; - static String URLPATH = "/support/topic/page-jumps-within-wordpress/"; - String URLFILENAME = "/support/topic/page-jumps-within-wordpress/?replies=3"; - int URLPORT = 443; - static int URLDEFAULTPORT = 443; - static String URLQUERY = "replies=3"; - static String URLREFERENCE = "post-2278484"; - static String URLCOMPOUND = URLPROTOCOL + "://" + URLHOST + ":" + URLDEFAULTPORT + URLPATH + "?" + URLQUERY + "#" + URLREFERENCE; - - static URL url; - URLConnection urlConnection = null; - HttpURLConnection connection = null; - BufferedReader in = null; - String urlContent = ""; - - @BeforeClass - public static void givenEmplyURL_whenInitializeURL_thenSuccess() throws MalformedURLException { - url = new URL(URLCOMPOUND); - } - - // check parsed URL - @Test - public void givenURL_whenURLIsParsed_thenSuccess() { - assertNotNull("URL is null", url); - assertEquals("URL string is not equal", url.toString(), URLSTRING); - assertEquals("Protocol is not equal", url.getProtocol(), URLPROTOCOL); - assertEquals("Authority is not equal", url.getAuthority(), URLAUTHORITY); - assertEquals("Host string is not equal", url.getHost(), URLHOST); - assertEquals("Path string is not equal", url.getPath(), URLPATH); - assertEquals("File string is not equal", url.getFile(), URLFILENAME); - assertEquals("Port number is not equal", url.getPort(), URLPORT); - assertEquals("Default port number is not equal", url.getDefaultPort(), URLDEFAULTPORT); - assertEquals("Query string is not equal", url.getQuery(), URLQUERY); - assertEquals("Reference string is not equal", url.getRef(), URLREFERENCE); - } - - // Obtain the content from location - @Test - public void givenURL_whenOpenConnectionAndContentIsNotEmpty_thenSuccess() throws IOException { - try { - urlConnection = url.openConnection(); - } catch (IOException ex) { - urlConnection = null; - ex.printStackTrace(); - } - assertNotNull("URL Connection is null", urlConnection); - - connection = null; - assertTrue("URLConnection is not HttpURLConnection", urlConnection instanceof HttpURLConnection); - if (urlConnection instanceof HttpURLConnection) { - connection = (HttpURLConnection) urlConnection; - } - assertNotNull("Connection is null", connection); - - log.info(connection.getResponseCode() + " " + connection.getResponseMessage()); - - try { - in = new BufferedReader(new InputStreamReader(connection.getInputStream())); - } catch (IOException ex) { - in = null; - ex.printStackTrace(); - } - assertNotNull("Input stream failed", in); - - String current; - try { - while ((current = in.readLine()) != null) { - urlContent += current; - } - } catch (IOException ex) { - urlContent = null; - ex.printStackTrace(); - } - assertNotNull("Content is null", urlContent); - assertTrue("Content is empty", urlContent.length() > 0); - } -} diff --git a/core-java/src/test/java/com/baeldung/jdbc/BatchProcessingTest.java b/core-java/src/test/java/com/baeldung/jdbc/BatchProcessingTest.java deleted file mode 100644 index 90f2ea133f..0000000000 --- a/core-java/src/test/java/com/baeldung/jdbc/BatchProcessingTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.baeldung.jdbc; - - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.junit.MockitoJUnitRunner; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.Statement; - -@RunWith(MockitoJUnitRunner.class) -public class BatchProcessingTest { - - - @InjectMocks - private BatchProcessing target = new BatchProcessing(); - - @Mock - private Connection connection; - - @Mock - private Statement statement; - - @Mock - private PreparedStatement employeeStatement; - - @Mock - private PreparedStatement employeeAddressStatement; - - @Before - public void before(){ - MockitoAnnotations.initMocks(this); - } - - - @Test - public void when_useStatement_thenInsertData_success() throws Exception { - Mockito.when(connection.createStatement()).thenReturn(statement); - target.useStatement(); - } - - @Test - public void when_useStatement_ifThrowException_thenCatchException() throws Exception { - Mockito.when(connection.createStatement()).thenThrow(new RuntimeException()); - target.useStatement(); - } - - @Test - public void when_usePreparedStatement_thenInsertData_success() throws Exception { - String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES (?,?,?);"; - String insertEmployeeAddrSQL = "INSERT INTO EMP_ADDRESS(ID, EMP_ID, ADDRESS) VALUES (?,?,?);"; - Mockito.when(connection.prepareStatement(insertEmployeeSQL)).thenReturn(employeeStatement); - Mockito.when(connection.prepareStatement(insertEmployeeAddrSQL)).thenReturn(employeeAddressStatement); - target.usePreparedStatement(); - } - - @Test - public void when_usePreparedStatement_ifThrowException_thenCatchException() throws Exception { - String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES (?,?,?);"; - String insertEmployeeAddrSQL = "INSERT INTO EMP_ADDRESS(ID, EMP_ID, ADDRESS) VALUES (?,?,?);"; - Mockito.when(connection.prepareStatement(insertEmployeeSQL)).thenReturn(employeeStatement); - Mockito.when(connection.prepareStatement(insertEmployeeAddrSQL)).thenThrow(new RuntimeException()); - target.usePreparedStatement(); - } -} diff --git a/core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetTest.java b/core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetTest.java deleted file mode 100644 index cb455c213a..0000000000 --- a/core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetTest.java +++ /dev/null @@ -1,157 +0,0 @@ -package com.baeldung.jdbcrowset; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Statement; - -import javax.sql.rowset.CachedRowSet; -import javax.sql.rowset.FilteredRowSet; -import javax.sql.rowset.JdbcRowSet; -import javax.sql.rowset.JoinRowSet; -import javax.sql.rowset.RowSetFactory; -import javax.sql.rowset.RowSetProvider; -import javax.sql.rowset.WebRowSet; - -import org.junit.Before; -import org.junit.Test; - -import com.sun.rowset.CachedRowSetImpl; -import com.sun.rowset.JdbcRowSetImpl; -import com.sun.rowset.JoinRowSetImpl; -import com.sun.rowset.WebRowSetImpl; - -public class JdbcRowSetTest { - Statement stmt = null; - String username = "sa"; - String password = ""; - String url = "jdbc:h2:mem:testdb"; - String sql = "SELECT * FROM customers"; - - @Before - public void setup() throws Exception { - Connection conn = DatabaseConfiguration.geth2Connection(); - - String drop = "DROP TABLE IF EXISTS customers, associates;"; - String schema = "CREATE TABLE customers (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id)); "; - String schemapartb = "CREATE TABLE associates (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id));"; - stmt = conn.createStatement(); - stmt.executeUpdate(drop); - stmt.executeUpdate(schema); - stmt.executeUpdate(schemapartb); - DatabaseConfiguration.initDatabase(stmt); - - } - - // JdbcRowSet Example - @Test - public void createJdbcRowSet_SelectCustomers_ThenCorrect() throws Exception { - - String sql = "SELECT * FROM customers"; - JdbcRowSet jdbcRS; - Connection conn = DatabaseConfiguration.geth2Connection(); - jdbcRS = new JdbcRowSetImpl(conn); - jdbcRS.setType(ResultSet.TYPE_SCROLL_INSENSITIVE); - jdbcRS.setCommand(sql); - jdbcRS.execute(); - jdbcRS.addRowSetListener(new ExampleListener()); - - while (jdbcRS.next()) { - // each call to next, generates a cursorMoved event - System.out.println("id=" + jdbcRS.getString(1)); - System.out.println("name=" + jdbcRS.getString(2)); - } - - } - - // CachedRowSet Example - @Test - public void createCachedRowSet_DeleteRecord_ThenCorrect() throws Exception { - - CachedRowSet crs = new CachedRowSetImpl(); - crs.setUsername(username); - crs.setPassword(password); - crs.setUrl(url); - crs.setCommand(sql); - crs.execute(); - crs.addRowSetListener(new ExampleListener()); - while (crs.next()) { - if (crs.getInt("id") == 1) { - System.out.println("CRS found customer1 and will remove the record."); - crs.deleteRow(); - break; - } - } - } - - // WebRowSet example - @Test - public void createWebRowSet_SelectCustomers_WritetoXML_ThenCorrect() throws SQLException, IOException { - - WebRowSet wrs = new WebRowSetImpl(); - wrs.setUsername(username); - wrs.setPassword(password); - wrs.setUrl(url); - wrs.setCommand(sql); - wrs.execute(); - FileOutputStream ostream = new FileOutputStream("customers.xml"); - wrs.writeXml(ostream); - } - - // JoinRowSet example - @Test - public void createCachedRowSets_DoJoinRowSet_ThenCorrect() throws Exception { - - CachedRowSetImpl customers = new CachedRowSetImpl(); - customers.setUsername(username); - customers.setPassword(password); - customers.setUrl(url); - customers.setCommand(sql); - customers.execute(); - - CachedRowSetImpl associates = new CachedRowSetImpl(); - associates.setUsername(username); - associates.setPassword(password); - associates.setUrl(url); - String associatesSQL = "SELECT * FROM associates"; - associates.setCommand(associatesSQL); - associates.execute(); - - JoinRowSet jrs = new JoinRowSetImpl(); - final String ID = "id"; - final String NAME = "name"; - jrs.addRowSet(customers, ID); - jrs.addRowSet(associates, ID); - jrs.last(); - System.out.println("Total rows: " + jrs.getRow()); - jrs.beforeFirst(); - while (jrs.next()) { - - String string1 = jrs.getString(ID); - String string2 = jrs.getString(NAME); - System.out.println("ID: " + string1 + ", NAME: " + string2); - } - } - - // FilteredRowSet example - @Test - public void createFilteredRowSet_filterByRegexExpression_thenCorrect() throws Exception { - RowSetFactory rsf = RowSetProvider.newFactory(); - FilteredRowSet frs = rsf.createFilteredRowSet(); - frs.setCommand("select * from customers"); - Connection conn = DatabaseConfiguration.geth2Connection(); - frs.execute(conn); - frs.setFilter(new FilterExample("^[A-C].*")); - - ResultSetMetaData rsmd = frs.getMetaData(); - int columncount = rsmd.getColumnCount(); - while (frs.next()) { - for (int i = 1; i <= columncount; i++) { - System.out.println(rsmd.getColumnLabel(i) + " = " + frs.getObject(i) + " "); - } - } - } -} diff --git a/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteTest.java b/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteTest.java deleted file mode 100644 index 5095217efc..0000000000 --- a/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteTest.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.junit4vstestng; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses({ RegistrationUnitTest.class, SignInUnitTest.class }) -public class SuiteTest { - -} diff --git a/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteUnitTest.java b/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteUnitTest.java new file mode 100644 index 0000000000..3e02309636 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteUnitTest.java @@ -0,0 +1,10 @@ +package com.baeldung.junit4vstestng; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +@RunWith(Suite.class) +@Suite.SuiteClasses({ RegistrationUnitTest.class, SignInUnitTest.class }) +public class SuiteUnitTest { + +} diff --git a/core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreTest.java b/core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreTest.java deleted file mode 100644 index ff1d337597..0000000000 --- a/core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreTest.java +++ /dev/null @@ -1,205 +0,0 @@ -package com.baeldung.keystore; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import sun.security.x509.AlgorithmId; -import sun.security.x509.CertificateAlgorithmId; -import sun.security.x509.CertificateSerialNumber; -import sun.security.x509.CertificateValidity; -import sun.security.x509.CertificateVersion; -import sun.security.x509.CertificateX509Key; -import sun.security.x509.X500Name; -import sun.security.x509.X509CertImpl; -import sun.security.x509.X509CertInfo; - -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; -import java.io.IOException; -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.KeyStore; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.SecureRandom; -import java.security.SignatureException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.Date; - -/** - * Created by adi on 4/14/18. - */ -public class JavaKeyStoreTest { - - private JavaKeyStore keyStore; - - private static final String KEYSTORE_PWD = "abc123"; - private static final String KEYSTORE_NAME = "myKeyStore"; - private static final String KEY_STORE_TYPE = "JCEKS"; - - private static final String MY_SECRET_ENTRY = "mySecretEntry"; - private static final String DN_NAME = "CN=test, OU=test, O=test, L=test, ST=test, C=CY"; - private static final String SHA1WITHRSA = "SHA1withRSA"; - private static final String MY_PRIVATE_KEY = "myPrivateKey"; - private static final String MY_CERTIFICATE = "myCertificate"; - - @Before - public void setUp() throws Exception { - //using java cryptography extension keyStore instead of Keystore.getDefaultType - keyStore = new JavaKeyStore(KEY_STORE_TYPE, KEYSTORE_PWD, KEYSTORE_NAME); - } - - @After - public void tearDown() throws Exception { - if (keyStore.getKeyStore() != null) { - keyStore.deleteKeyStore(); - } - } - - @Test - public void givenNoKeyStore_whenCreateEmptyKeyStore_thenGetKeyStoreNotNull() throws Exception { - keyStore.createEmptyKeyStore(); - KeyStore result = keyStore.getKeyStore(); - Assert.assertNotNull(result); - } - - @Test - public void givenEmptyKeystore_whenLoadKeyStore_thenKeyStoreLoadedAndSizeZero() throws Exception { - keyStore.createEmptyKeyStore(); - keyStore.loadKeyStore(); - KeyStore result = keyStore.getKeyStore(); - Assert.assertNotNull(result); - Assert.assertTrue(result.size() == 0); - } - - @Test - public void givenLoadedKeyStore_whenSetEntry_thenSizeIsOneAndGetKeyNotNull() throws Exception { - keyStore.createEmptyKeyStore(); - keyStore.loadKeyStore(); - - KeyGenerator keygen = KeyGenerator.getInstance("HmacSHA256"); - SecretKey secretKey = keygen.generateKey(); - //ideally, password should be different for every key - KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(KEYSTORE_PWD.toCharArray()); - KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(secretKey); - keyStore.setEntry(MY_SECRET_ENTRY, secretKeyEntry, protParam); - - KeyStore result = keyStore.getKeyStore(); - Assert.assertTrue(result.size() == 1); - KeyStore.Entry entry = keyStore.getEntry(MY_SECRET_ENTRY); - Assert.assertTrue(entry != null); - } - - @Test - public void givenLoadedKeyStore_whenSetKeyEntry_thenSizeIsOneAndGetEntryNotNull() throws Exception { - keyStore.createEmptyKeyStore(); - keyStore.loadKeyStore(); - - // Generate the key pair - KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); - keyPairGenerator.initialize(1024); - KeyPair keyPair = keyPairGenerator.generateKeyPair(); - - // Generate a self signed certificate - X509Certificate certificate = generateSelfSignedCertificate(keyPair); - - X509Certificate[] certificateChain = new X509Certificate[1]; - certificateChain[0] = certificate; - keyStore.setKeyEntry(MY_PRIVATE_KEY, keyPair.getPrivate(), KEYSTORE_PWD, certificateChain); - - KeyStore result = keyStore.getKeyStore(); - Assert.assertTrue(result.size() == 1); - KeyStore.Entry entry = keyStore.getEntry(MY_PRIVATE_KEY); - Assert.assertTrue(entry != null); - } - - @Test - public void givenLoadedKeyStore_whenSetCertificateEntry_thenSizeIsOneAndGetCertificateEntryNotNull() throws Exception { - keyStore.createEmptyKeyStore(); - keyStore.loadKeyStore(); - - // Generate the key pair - KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); - keyPairGenerator.initialize(1024); - KeyPair keyPair = keyPairGenerator.generateKeyPair(); - - // Generate a self signed certificate - X509Certificate certificate = generateSelfSignedCertificate(keyPair); - - keyStore.setCertificateEntry(MY_CERTIFICATE, certificate); - - KeyStore result = this.keyStore.getKeyStore(); - Assert.assertTrue(result.size() == 1); - java.security.cert.Certificate resultCertificate = keyStore.getCertificate(MY_CERTIFICATE); - Assert.assertNotNull(resultCertificate); - } - - @Test - public void givenLoadedKeyStoreWithOneEntry_whenDeleteEntry_thenKeyStoreSizeIsZero() throws Exception { - keyStore.createEmptyKeyStore(); - keyStore.loadKeyStore(); - - KeyGenerator keygen = KeyGenerator.getInstance("HmacSHA256"); - SecretKey secretKey = keygen.generateKey(); - //ideally, password should be different for every key - KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(KEYSTORE_PWD.toCharArray()); - KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(secretKey); - keyStore.setEntry(MY_SECRET_ENTRY, secretKeyEntry, protParam); - - keyStore.deleteEntry(MY_SECRET_ENTRY); - - KeyStore result = this.keyStore.getKeyStore(); - Assert.assertTrue(result.size() == 0); - } - - @Test - public void givenLoadedKeystore_whenDeleteKeyStore_thenKeyStoreIsNull() throws Exception { - keyStore.createEmptyKeyStore(); - keyStore.loadKeyStore(); - - keyStore.deleteKeyStore(); - - KeyStore result = this.keyStore.getKeyStore(); - Assert.assertTrue(result == null); - } - - private X509Certificate generateSelfSignedCertificate(KeyPair keyPair) throws CertificateException, IOException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { - X509CertInfo certInfo = new X509CertInfo(); - // Serial number and version - certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(new BigInteger(64, new SecureRandom()))); - certInfo.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3)); - - // Subject & Issuer - X500Name owner = new X500Name(DN_NAME); - certInfo.set(X509CertInfo.SUBJECT, owner); - certInfo.set(X509CertInfo.ISSUER, owner); - - // Key and algorithm - certInfo.set(X509CertInfo.KEY, new CertificateX509Key(keyPair.getPublic())); - AlgorithmId algorithm = new AlgorithmId(AlgorithmId.sha1WithRSAEncryption_oid); - certInfo.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algorithm)); - - // Validity - Date validFrom = new Date(); - Date validTo = new Date(validFrom.getTime() + 50L * 365L * 24L * 60L * 60L * 1000L); //50 years - CertificateValidity validity = new CertificateValidity(validFrom, validTo); - certInfo.set(X509CertInfo.VALIDITY, validity); - - // Create certificate and sign it - X509CertImpl cert = new X509CertImpl(certInfo); - cert.sign(keyPair.getPrivate(), SHA1WITHRSA); - - // Since the SHA1withRSA provider may have a different algorithm ID to what we think it should be, - // we need to reset the algorithm ID, and resign the certificate - AlgorithmId actualAlgorithm = (AlgorithmId) cert.get(X509CertImpl.SIG_ALG); - certInfo.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, actualAlgorithm); - X509CertImpl newCert = new X509CertImpl(certInfo); - newCert.sign(keyPair.getPrivate(), SHA1WITHRSA); - - return newCert; - } -} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreUnitTest.java b/core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreUnitTest.java new file mode 100644 index 0000000000..cb2a9f1c49 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreUnitTest.java @@ -0,0 +1,205 @@ +package com.baeldung.keystore; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import sun.security.x509.AlgorithmId; +import sun.security.x509.CertificateAlgorithmId; +import sun.security.x509.CertificateSerialNumber; +import sun.security.x509.CertificateValidity; +import sun.security.x509.CertificateVersion; +import sun.security.x509.CertificateX509Key; +import sun.security.x509.X500Name; +import sun.security.x509.X509CertImpl; +import sun.security.x509.X509CertInfo; + +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import java.io.IOException; +import java.math.BigInteger; +import java.security.InvalidKeyException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.KeyStore; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.SecureRandom; +import java.security.SignatureException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Date; + +/** + * Created by adi on 4/14/18. + */ +public class JavaKeyStoreUnitTest { + + private JavaKeyStore keyStore; + + private static final String KEYSTORE_PWD = "abc123"; + private static final String KEYSTORE_NAME = "myKeyStore"; + private static final String KEY_STORE_TYPE = "JCEKS"; + + private static final String MY_SECRET_ENTRY = "mySecretEntry"; + private static final String DN_NAME = "CN=test, OU=test, O=test, L=test, ST=test, C=CY"; + private static final String SHA1WITHRSA = "SHA1withRSA"; + private static final String MY_PRIVATE_KEY = "myPrivateKey"; + private static final String MY_CERTIFICATE = "myCertificate"; + + @Before + public void setUp() throws Exception { + //using java cryptography extension keyStore instead of Keystore.getDefaultType + keyStore = new JavaKeyStore(KEY_STORE_TYPE, KEYSTORE_PWD, KEYSTORE_NAME); + } + + @After + public void tearDown() throws Exception { + if (keyStore.getKeyStore() != null) { + keyStore.deleteKeyStore(); + } + } + + @Test + public void givenNoKeyStore_whenCreateEmptyKeyStore_thenGetKeyStoreNotNull() throws Exception { + keyStore.createEmptyKeyStore(); + KeyStore result = keyStore.getKeyStore(); + Assert.assertNotNull(result); + } + + @Test + public void givenEmptyKeystore_whenLoadKeyStore_thenKeyStoreLoadedAndSizeZero() throws Exception { + keyStore.createEmptyKeyStore(); + keyStore.loadKeyStore(); + KeyStore result = keyStore.getKeyStore(); + Assert.assertNotNull(result); + Assert.assertTrue(result.size() == 0); + } + + @Test + public void givenLoadedKeyStore_whenSetEntry_thenSizeIsOneAndGetKeyNotNull() throws Exception { + keyStore.createEmptyKeyStore(); + keyStore.loadKeyStore(); + + KeyGenerator keygen = KeyGenerator.getInstance("HmacSHA256"); + SecretKey secretKey = keygen.generateKey(); + //ideally, password should be different for every key + KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(KEYSTORE_PWD.toCharArray()); + KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(secretKey); + keyStore.setEntry(MY_SECRET_ENTRY, secretKeyEntry, protParam); + + KeyStore result = keyStore.getKeyStore(); + Assert.assertTrue(result.size() == 1); + KeyStore.Entry entry = keyStore.getEntry(MY_SECRET_ENTRY); + Assert.assertTrue(entry != null); + } + + @Test + public void givenLoadedKeyStore_whenSetKeyEntry_thenSizeIsOneAndGetEntryNotNull() throws Exception { + keyStore.createEmptyKeyStore(); + keyStore.loadKeyStore(); + + // Generate the key pair + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); + keyPairGenerator.initialize(1024); + KeyPair keyPair = keyPairGenerator.generateKeyPair(); + + // Generate a self signed certificate + X509Certificate certificate = generateSelfSignedCertificate(keyPair); + + X509Certificate[] certificateChain = new X509Certificate[1]; + certificateChain[0] = certificate; + keyStore.setKeyEntry(MY_PRIVATE_KEY, keyPair.getPrivate(), KEYSTORE_PWD, certificateChain); + + KeyStore result = keyStore.getKeyStore(); + Assert.assertTrue(result.size() == 1); + KeyStore.Entry entry = keyStore.getEntry(MY_PRIVATE_KEY); + Assert.assertTrue(entry != null); + } + + @Test + public void givenLoadedKeyStore_whenSetCertificateEntry_thenSizeIsOneAndGetCertificateEntryNotNull() throws Exception { + keyStore.createEmptyKeyStore(); + keyStore.loadKeyStore(); + + // Generate the key pair + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); + keyPairGenerator.initialize(1024); + KeyPair keyPair = keyPairGenerator.generateKeyPair(); + + // Generate a self signed certificate + X509Certificate certificate = generateSelfSignedCertificate(keyPair); + + keyStore.setCertificateEntry(MY_CERTIFICATE, certificate); + + KeyStore result = this.keyStore.getKeyStore(); + Assert.assertTrue(result.size() == 1); + java.security.cert.Certificate resultCertificate = keyStore.getCertificate(MY_CERTIFICATE); + Assert.assertNotNull(resultCertificate); + } + + @Test + public void givenLoadedKeyStoreWithOneEntry_whenDeleteEntry_thenKeyStoreSizeIsZero() throws Exception { + keyStore.createEmptyKeyStore(); + keyStore.loadKeyStore(); + + KeyGenerator keygen = KeyGenerator.getInstance("HmacSHA256"); + SecretKey secretKey = keygen.generateKey(); + //ideally, password should be different for every key + KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(KEYSTORE_PWD.toCharArray()); + KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(secretKey); + keyStore.setEntry(MY_SECRET_ENTRY, secretKeyEntry, protParam); + + keyStore.deleteEntry(MY_SECRET_ENTRY); + + KeyStore result = this.keyStore.getKeyStore(); + Assert.assertTrue(result.size() == 0); + } + + @Test + public void givenLoadedKeystore_whenDeleteKeyStore_thenKeyStoreIsNull() throws Exception { + keyStore.createEmptyKeyStore(); + keyStore.loadKeyStore(); + + keyStore.deleteKeyStore(); + + KeyStore result = this.keyStore.getKeyStore(); + Assert.assertTrue(result == null); + } + + private X509Certificate generateSelfSignedCertificate(KeyPair keyPair) throws CertificateException, IOException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { + X509CertInfo certInfo = new X509CertInfo(); + // Serial number and version + certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(new BigInteger(64, new SecureRandom()))); + certInfo.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3)); + + // Subject & Issuer + X500Name owner = new X500Name(DN_NAME); + certInfo.set(X509CertInfo.SUBJECT, owner); + certInfo.set(X509CertInfo.ISSUER, owner); + + // Key and algorithm + certInfo.set(X509CertInfo.KEY, new CertificateX509Key(keyPair.getPublic())); + AlgorithmId algorithm = new AlgorithmId(AlgorithmId.sha1WithRSAEncryption_oid); + certInfo.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algorithm)); + + // Validity + Date validFrom = new Date(); + Date validTo = new Date(validFrom.getTime() + 50L * 365L * 24L * 60L * 60L * 1000L); //50 years + CertificateValidity validity = new CertificateValidity(validFrom, validTo); + certInfo.set(X509CertInfo.VALIDITY, validity); + + // Create certificate and sign it + X509CertImpl cert = new X509CertImpl(certInfo); + cert.sign(keyPair.getPrivate(), SHA1WITHRSA); + + // Since the SHA1withRSA provider may have a different algorithm ID to what we think it should be, + // we need to reset the algorithm ID, and resign the certificate + AlgorithmId actualAlgorithm = (AlgorithmId) cert.get(X509CertImpl.SIG_ALG); + certInfo.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, actualAlgorithm); + X509CertImpl newCert = new X509CertImpl(certInfo); + newCert.sign(keyPair.getPrivate(), SHA1WITHRSA); + + return newCert; + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/manifest/ExecuteJarFileUnitTest.java b/core-java/src/test/java/com/baeldung/manifest/ExecuteJarFileUnitTest.java new file mode 100644 index 0000000000..a5a499c98c --- /dev/null +++ b/core-java/src/test/java/com/baeldung/manifest/ExecuteJarFileUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.manifest; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class ExecuteJarFileUnitTest { + + private static final String ERROR_MESSAGE = "no main manifest attribute, in example.jar\n"; + private static final String SUCCESS_MESSAGE = "AppExample executed!\n"; + + @Test + public final void givenDefaultManifest_whenManifestAttributeIsNotPresent_thenGetErrorMessage() { + String output = ExecuteJarFile.executeJarWithoutManifestAttribute(); + assertEquals(ERROR_MESSAGE, output); + } + + @Test + public final void givenCustomManifest_whenManifestAttributeIsPresent_thenGetSuccessMessage() { + String output = ExecuteJarFile.executeJarWithManifestAttribute(); + assertEquals(SUCCESS_MESSAGE, output); + } + +} diff --git a/core-java/src/test/java/com/baeldung/maths/BigDecimalImplTest.java b/core-java/src/test/java/com/baeldung/maths/BigDecimalImplTest.java deleted file mode 100644 index 788fbd7047..0000000000 --- a/core-java/src/test/java/com/baeldung/maths/BigDecimalImplTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.maths; - -import org.junit.Assert; -import org.junit.Test; - -import java.math.BigDecimal; -import java.math.RoundingMode; - -public class BigDecimalImplTest { - - @Test - public void givenBigDecimalNumbers_whenAddedTogether_thenGetExpectedResult() { - BigDecimal serviceTax = new BigDecimal("56.0084578639"); - serviceTax = serviceTax.setScale(2, RoundingMode.CEILING); - - BigDecimal entertainmentTax = new BigDecimal("23.00689"); - entertainmentTax = entertainmentTax.setScale(2, RoundingMode.FLOOR); - - BigDecimal totalTax = serviceTax.add(entertainmentTax); - BigDecimal result = BigDecimal.valueOf(79.01); - - Assert.assertEquals(result, totalTax); - - } -} diff --git a/core-java/src/test/java/com/baeldung/maths/BigIntegerImplTest.java b/core-java/src/test/java/com/baeldung/maths/BigIntegerImplTest.java deleted file mode 100644 index aa8eaa9909..0000000000 --- a/core-java/src/test/java/com/baeldung/maths/BigIntegerImplTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.maths; - -import org.junit.Assert; -import org.junit.Test; - -import java.math.BigInteger; - -public class BigIntegerImplTest { - - @Test - public void givenBigIntegerNumbers_whenAddedTogether_thenGetExpectedResult() { - BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476"); - BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476"); - - BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda); - BigInteger result = new BigInteger("14110718640342675608722521633212952"); - - Assert.assertEquals(result, totalStars); - } - -} diff --git a/core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticTest.java b/core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticTest.java deleted file mode 100644 index 2066f13c6d..0000000000 --- a/core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticTest.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.maths; - -import java.math.BigDecimal; - -import org.junit.Assert; -import org.junit.Test; - -public class FloatingPointArithmeticTest { - - @Test - public void givenDecimalNumbers_whenAddedTogether_thenGetExpectedResult() { - double a = 13.22; - double b = 4.88; - double c = 21.45; - double result = 39.55; - - double abc = a + b + c; - double acb = a + c + b; - - Assert.assertEquals(result, abc, 0); - Assert.assertNotEquals(result, acb, 0); - - double ab = 18.1; - double ac = 34.67; - - double ab_c = ab + c; - double ac_b = ac + b; - - Assert.assertEquals(result, ab_c, 0); - Assert.assertNotEquals(result, ac_b, 0); - - BigDecimal d = new BigDecimal(String.valueOf(a)); - BigDecimal e = new BigDecimal(String.valueOf(b)); - BigDecimal f = new BigDecimal(String.valueOf(c)); - BigDecimal sum = new BigDecimal("39.55"); - - BigDecimal def = d.add(e).add(f); - BigDecimal dfe = d.add(f).add(e); - - Assert.assertEquals(0, def.compareTo(sum)); - Assert.assertEquals(0, dfe.compareTo(sum)); - - Assert.assertNotEquals(0, sum.compareTo(new BigDecimal(String.valueOf(acb)))); - } -} diff --git a/core-java/src/test/java/com/baeldung/maths/RoundTest.java b/core-java/src/test/java/com/baeldung/maths/RoundTest.java deleted file mode 100644 index 5ce9523e21..0000000000 --- a/core-java/src/test/java/com/baeldung/maths/RoundTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.maths; - -import org.apache.commons.math3.util.Precision; -import org.decimal4j.util.DoubleRounder; -import org.junit.Assert; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - -public class RoundTest { - private double value = 2.03456d; - private int places = 2; - private double delta = 0.0d; - private double expected = 2.03d; - - @Test - 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; - 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 ! - Assert.assertEquals(expected, Precision.round(value, places), delta); - Assert.assertEquals(expected, DoubleRounder.round(value, places), delta); - } -} diff --git a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java index fe2747bcee..04d2886a82 100644 --- a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java +++ b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java @@ -179,7 +179,7 @@ public class JavaMoneyUnitManualTest { MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder .of(Locale.US) .set(CurrencyStyle.NAME) - .set("pattern", "00000.00 �") + .set("pattern", "00000.00 US Dollar") .build()); String customFormatted = customFormat.format(oneDollar); diff --git a/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorTest.java b/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorTest.java deleted file mode 100644 index aa11aaa788..0000000000 --- a/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.noclassdeffounderror; - -import org.junit.Test; - -public class NoClassDefFoundErrorTest { - - @Test(expected = NoClassDefFoundError.class) - public void givenInitErrorInClass_whenloadClass_thenNoClassDefFoundError() { - NoClassDefFoundErrorExample sample = new NoClassDefFoundErrorExample(); - sample.getClassWithInitErrors(); - } -} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorUnitTest.java b/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorUnitTest.java new file mode 100644 index 0000000000..ccc8c1f69c --- /dev/null +++ b/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorUnitTest.java @@ -0,0 +1,12 @@ +package com.baeldung.noclassdeffounderror; + +import org.junit.Test; + +public class NoClassDefFoundErrorUnitTest { + + @Test(expected = NoClassDefFoundError.class) + public void givenInitErrorInClass_whenloadClass_thenNoClassDefFoundError() { + NoClassDefFoundErrorExample sample = new NoClassDefFoundErrorExample(); + sample.getClassWithInitErrors(); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/recursion/RecursionExampleTest.java b/core-java/src/test/java/com/baeldung/recursion/RecursionExampleTest.java deleted file mode 100644 index c65be24240..0000000000 --- a/core-java/src/test/java/com/baeldung/recursion/RecursionExampleTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.recursion; - -import org.junit.Assert; -import org.junit.Test; - -public class RecursionExampleTest { - - RecursionExample recursion = new RecursionExample(); - - @Test - public void testPowerOf10() { - int p0 = recursion.powerOf10(0); - int p1 = recursion.powerOf10(1); - int p4 = recursion.powerOf10(4); - - Assert.assertEquals(1, p0); - Assert.assertEquals(10, p1); - Assert.assertEquals(10000, p4); - } - - @Test - public void testFibonacci() { - int n0 = recursion.fibonacci(0); - int n1 = recursion.fibonacci(1); - int n7 = recursion.fibonacci(7); - - Assert.assertEquals(0, n0); - Assert.assertEquals(1, n1); - Assert.assertEquals(13, n7); - } - - @Test - public void testToBinary() { - String b0 = recursion.toBinary(0); - String b1 = recursion.toBinary(1); - String b10 = recursion.toBinary(10); - - Assert.assertEquals("0", b0); - Assert.assertEquals("1", b1); - Assert.assertEquals("1010", b10); - } - - @Test - public void testCalculateTreeHeight() { - BinaryNode root = new BinaryNode(1); - root.setLeft(new BinaryNode(1)); - root.setRight(new BinaryNode(1)); - - root.getLeft().setLeft(new BinaryNode(1)); - root.getLeft().getLeft().setRight(new BinaryNode(1)); - root.getLeft().getLeft().getRight().setLeft(new BinaryNode(1)); - - root.getRight().setLeft(new BinaryNode(1)); - root.getRight().getLeft().setRight(new BinaryNode(1)); - - int height = recursion.calculateTreeHeight(root); - - Assert.assertEquals(4, height); - } - -} diff --git a/core-java/src/test/java/com/baeldung/recursion/RecursionExampleUnitTest.java b/core-java/src/test/java/com/baeldung/recursion/RecursionExampleUnitTest.java new file mode 100644 index 0000000000..6c560c9c37 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/recursion/RecursionExampleUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.recursion; + +import org.junit.Assert; +import org.junit.Test; + +public class RecursionExampleUnitTest { + + RecursionExample recursion = new RecursionExample(); + + @Test + public void testPowerOf10() { + int p0 = recursion.powerOf10(0); + int p1 = recursion.powerOf10(1); + int p4 = recursion.powerOf10(4); + + Assert.assertEquals(1, p0); + Assert.assertEquals(10, p1); + Assert.assertEquals(10000, p4); + } + + @Test + public void testFibonacci() { + int n0 = recursion.fibonacci(0); + int n1 = recursion.fibonacci(1); + int n7 = recursion.fibonacci(7); + + Assert.assertEquals(0, n0); + Assert.assertEquals(1, n1); + Assert.assertEquals(13, n7); + } + + @Test + public void testToBinary() { + String b0 = recursion.toBinary(0); + String b1 = recursion.toBinary(1); + String b10 = recursion.toBinary(10); + + Assert.assertEquals("0", b0); + Assert.assertEquals("1", b1); + Assert.assertEquals("1010", b10); + } + + @Test + public void testCalculateTreeHeight() { + BinaryNode root = new BinaryNode(1); + root.setLeft(new BinaryNode(1)); + root.setRight(new BinaryNode(1)); + + root.getLeft().setLeft(new BinaryNode(1)); + root.getLeft().getLeft().setRight(new BinaryNode(1)); + root.getLeft().getLeft().getRight().setLeft(new BinaryNode(1)); + + root.getRight().setLeft(new BinaryNode(1)); + root.getRight().getLeft().setRight(new BinaryNode(1)); + + int height = recursion.calculateTreeHeight(root); + + Assert.assertEquals(4, height); + } + +} diff --git a/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsTest.java b/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsTest.java deleted file mode 100644 index bba867f50f..0000000000 --- a/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.reflection; - -import org.junit.Test; - -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertTrue; - -public class BaeldungReflectionUtilsTest { - - @Test - public void givenCustomer_whenAFieldIsNull_thenFieldNameInResult() throws Exception { - Customer customer = new Customer(1, "Himanshu", null, null); - - List result = BaeldungReflectionUtils.getNullPropertiesList(customer); - List expectedFieldNames = Arrays.asList("emailId", "phoneNumber"); - - assertTrue(result.size() == expectedFieldNames.size()); - assertTrue(result.containsAll(expectedFieldNames)); - - } - -} diff --git a/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsUnitTest.java b/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsUnitTest.java new file mode 100644 index 0000000000..77cdd0279d --- /dev/null +++ b/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.reflection; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertTrue; + +public class BaeldungReflectionUtilsUnitTest { + + @Test + public void givenCustomer_whenAFieldIsNull_thenFieldNameInResult() throws Exception { + Customer customer = new Customer(1, "Himanshu", null, null); + + List result = BaeldungReflectionUtils.getNullPropertiesList(customer); + List expectedFieldNames = Arrays.asList("emailId", "phoneNumber"); + + assertTrue(result.size() == expectedFieldNames.size()); + assertTrue(result.containsAll(expectedFieldNames)); + + } + +} diff --git a/core-java/src/test/java/com/baeldung/regexp/EscapingCharsTest.java b/core-java/src/test/java/com/baeldung/regexp/EscapingCharsTest.java deleted file mode 100644 index 47c9cfc621..0000000000 --- a/core-java/src/test/java/com/baeldung/regexp/EscapingCharsTest.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.baeldung.regexp; - -import org.junit.Test; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static junit.framework.TestCase.assertEquals; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.not; -import static org.junit.Assert.assertThat; - -public class EscapingCharsTest { - @Test - public void givenRegexWithDot_whenMatchingStr_thenMatches() { - String strInput = "foof"; - String strRegex = "foo."; - - assertEquals(true, strInput.matches(strRegex)); - } - - @Test - public void givenRegexWithDotEsc_whenMatchingStr_thenNotMatching() { - String strInput = "foof"; - String strRegex = "foo\\."; - - assertEquals(false, strInput.matches(strRegex)); - } - - @Test - public void givenRegexWithPipeEscaped_whenSplitStr_thenSplits() { - String strInput = "foo|bar|hello|world"; - String strRegex = "\\Q|\\E"; - - assertEquals(4, strInput.split(strRegex).length); - } - - @Test - public void givenRegexWithPipeEscQuoteMeth_whenSplitStr_thenSplits() { - String strInput = "foo|bar|hello|world"; - String strRegex = "|"; - - assertEquals(4, strInput.split(Pattern.quote(strRegex)).length); - } - - @Test - public void givenRegexWithDollar_whenReplacing_thenNotReplace() { - String strInput = "I gave $50 to my brother." - + "He bought candy for $35. Now he has $15 left."; - String strRegex = "$"; - String strReplacement = "£"; - String output = "I gave £50 to my brother." - + "He bought candy for £35. Now he has £15 left."; - Pattern p = Pattern.compile(strRegex); - Matcher m = p.matcher(strInput); - - assertThat(output, not(equalTo(m.replaceAll(strReplacement)))); - } - - @Test - public void givenRegexWithDollarEsc_whenReplacing_thenReplace() { - String strInput = "I gave $50 to my brother." - + "He bought candy for $35. Now he has $15 left."; - String strRegex = "\\$"; - String strReplacement = "£"; - String output = "I gave £50 to my brother." - + "He bought candy for £35. Now he has £15 left."; - Pattern p = Pattern.compile(strRegex); - Matcher m = p.matcher(strInput); - - assertEquals(output, m.replaceAll(strReplacement)); - } -} diff --git a/core-java/src/test/java/com/baeldung/regexp/EscapingCharsUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/EscapingCharsUnitTest.java new file mode 100644 index 0000000000..d903a02589 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/regexp/EscapingCharsUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.regexp; + +import org.junit.Test; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static junit.framework.TestCase.assertEquals; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.not; +import static org.junit.Assert.assertThat; + +public class EscapingCharsUnitTest { + @Test + public void givenRegexWithDot_whenMatchingStr_thenMatches() { + String strInput = "foof"; + String strRegex = "foo."; + + assertEquals(true, strInput.matches(strRegex)); + } + + @Test + public void givenRegexWithDotEsc_whenMatchingStr_thenNotMatching() { + String strInput = "foof"; + String strRegex = "foo\\."; + + assertEquals(false, strInput.matches(strRegex)); + } + + @Test + public void givenRegexWithPipeEscaped_whenSplitStr_thenSplits() { + String strInput = "foo|bar|hello|world"; + String strRegex = "\\Q|\\E"; + + assertEquals(4, strInput.split(strRegex).length); + } + + @Test + public void givenRegexWithPipeEscQuoteMeth_whenSplitStr_thenSplits() { + String strInput = "foo|bar|hello|world"; + String strRegex = "|"; + + assertEquals(4, strInput.split(Pattern.quote(strRegex)).length); + } + + @Test + public void givenRegexWithDollar_whenReplacing_thenNotReplace() { + String strInput = "I gave $50 to my brother." + + "He bought candy for $35. Now he has $15 left."; + String strRegex = "$"; + String strReplacement = "£"; + String output = "I gave £50 to my brother." + + "He bought candy for £35. Now he has £15 left."; + Pattern p = Pattern.compile(strRegex); + Matcher m = p.matcher(strInput); + + assertThat(output, not(equalTo(m.replaceAll(strReplacement)))); + } + + @Test + public void givenRegexWithDollarEsc_whenReplacing_thenReplace() { + String strInput = "I gave $50 to my brother." + + "He bought candy for $35. Now he has $15 left."; + String strRegex = "\\$"; + String strReplacement = "£"; + String output = "I gave £50 to my brother." + + "He bought candy for £35. Now he has £15 left."; + Pattern p = Pattern.compile(strRegex); + Matcher m = p.matcher(strInput); + + assertEquals(output, m.replaceAll(strReplacement)); + } +} diff --git a/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java new file mode 100644 index 0000000000..f21a755b01 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java @@ -0,0 +1,109 @@ +package com.baeldung.regexp.optmization; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.junit.Assert.assertTrue; + +public class OptimizedMatcherUnitTest { + + private long time; + private long mstimePreCompiled; + private long mstimeNotPreCompiled; + + private String action; + + private List items; + + @Before + public void setup() { + Random random = new Random(); + items = new ArrayList(); + long average = 0; + + for (int i = 0; i < 100000; ++i) { + StringBuilder s = new StringBuilder(); + int characters = random.nextInt(7) + 1; + for (int k = 0; k < characters; ++ k) { + char c = (char)(random.nextInt('Z' - 'A') + 'A'); + int rep = random.nextInt(95) + 5; + for (int j = 0; j < rep; ++ j) + s.append(c); + average += rep; + } + items.add(s.toString()); + } + + average /= 100000; + System.out.println("generated data, average length: " + average); + } + + + @Test + public void givenANotPreCompiledAndAPreCompiledPatternA_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() { + + testPatterns("A*"); + assertTrue(mstimePreCompiled < mstimeNotPreCompiled); + } + + @Test + public void givenANotPreCompiledAndAPreCompiledPatternABC_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() { + + testPatterns("A*B*C*"); + assertTrue(mstimePreCompiled < mstimeNotPreCompiled); + } + + @Test + public void givenANotPreCompiledAndAPreCompiledPatternECWF_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() { + + testPatterns("E*C*W*F*"); + assertTrue(mstimePreCompiled < mstimeNotPreCompiled); + } + + private void testPatterns(String regex) { + time = System.nanoTime(); + int matched = 0; + int unmatched = 0; + + for (String item : this.items) { + if (item.matches(regex)) { + ++matched; + } + else { + ++unmatched; + } + } + + this.action = "uncompiled: regex=" + regex + " matched=" + matched + " unmatched=" + unmatched; + + this.mstimeNotPreCompiled = (System.nanoTime() - time) / 1000000; + System.out.println(this.action + ": " + mstimeNotPreCompiled + "ms"); + + time = System.nanoTime(); + + Matcher matcher = Pattern.compile(regex).matcher(""); + matched = 0; + unmatched = 0; + + for (String item : this.items) { + if (matcher.reset(item).matches()) { + ++matched; + } + else { + ++unmatched; + } + } + + this.action = "compiled: regex=" + regex + " matched=" + matched + " unmatched=" + unmatched; + + this.mstimePreCompiled = (System.nanoTime() - time) / 1000000; + System.out.println(this.action + ": " + mstimePreCompiled + "ms"); + } +} diff --git a/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java b/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java index 7f165cec86..9abe8a927c 100644 --- a/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java +++ b/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java @@ -104,7 +104,7 @@ public class NashornUnitTest { public void loadExamples() throws ScriptException { Object loadResult = engine.eval("load('classpath:js/script.js');" + "increment(5)"); - Assert.assertEquals(6.0, loadResult); + Assert.assertEquals(6, ((Double) loadResult).intValue()); Object math = engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.increment(5);"); diff --git a/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableTest.java b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableTest.java deleted file mode 100644 index cd31f545b9..0000000000 --- a/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableTest.java +++ /dev/null @@ -1,17 +0,0 @@ -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/SneakyRunnableUnitTest.java b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableUnitTest.java new file mode 100644 index 0000000000..8d8e4f14fe --- /dev/null +++ b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.sneakythrows; + +import org.junit.Test; + +import static junit.framework.TestCase.assertEquals; + +public class SneakyRunnableUnitTest { + + @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 deleted file mode 100644 index e033ca062d..0000000000 --- a/core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsTest.java +++ /dev/null @@ -1,18 +0,0 @@ -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/sneakythrows/SneakyThrowsUnitTest.java b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsUnitTest.java new file mode 100644 index 0000000000..da1b2e617b --- /dev/null +++ b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.sneakythrows; + +import org.junit.Test; + +import static junit.framework.TestCase.assertEquals; + +public class SneakyThrowsUnitTest { + + @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/socket/EchoIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java index 70c6e88c49..103824b6aa 100644 --- a/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java @@ -1,21 +1,29 @@ package com.baeldung.socket; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.net.ServerSocket; +import java.util.concurrent.Executors; + import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import java.util.concurrent.Executors; - -import static org.junit.Assert.assertEquals; - public class EchoIntegrationTest { - private static final Integer PORT = 4444; + private static int port; @BeforeClass - public static void start() throws InterruptedException { + public static void start() throws InterruptedException, IOException { + + // Take an available port + ServerSocket s = new ServerSocket(0); + port = s.getLocalPort(); + s.close(); + Executors.newSingleThreadExecutor() - .submit(() -> new EchoServer().start(PORT)); + .submit(() -> new EchoServer().start(port)); Thread.sleep(500); } @@ -23,7 +31,7 @@ public class EchoIntegrationTest { @Before public void init() { - client.startConnection("127.0.0.1", PORT); + client.startConnection("127.0.0.1", port); } @After diff --git a/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java index 4367ed26a2..2bded156c5 100644 --- a/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java @@ -1,31 +1,39 @@ package com.baeldung.socket; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.net.ServerSocket; +import java.util.concurrent.Executors; + import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import java.util.concurrent.Executors; - -import static org.junit.Assert.assertEquals; - public class GreetServerIntegrationTest { private GreetClient client; - private static final Integer PORT = 6666; + private static int port; @BeforeClass - public static void start() throws InterruptedException { + public static void start() throws InterruptedException, IOException { + + // Take an available port + ServerSocket s = new ServerSocket(0); + port = s.getLocalPort(); + s.close(); + Executors.newSingleThreadExecutor() - .submit(() -> new GreetServer().start(PORT)); + .submit(() -> new GreetServer().start(port)); Thread.sleep(500); } @Before public void init() { client = new GreetClient(); - client.startConnection("127.0.0.1", PORT); + client.startConnection("127.0.0.1", port); } diff --git a/core-java/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java index 6ebc0946c5..62e2dd44ae 100644 --- a/core-java/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java @@ -1,26 +1,35 @@ package com.baeldung.socket; import org.junit.BeforeClass; +import org.junit.Ignore; import org.junit.Test; +import java.io.IOException; +import java.net.ServerSocket; import java.util.concurrent.Executors; import static org.junit.Assert.assertEquals; public class SocketEchoMultiIntegrationTest { - private static final Integer PORT = 5555; + private static int port; @BeforeClass - public static void start() throws InterruptedException { - Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(PORT)); + public static void start() throws InterruptedException, IOException { + + // Take an available port + ServerSocket s = new ServerSocket(0); + port = s.getLocalPort(); + s.close(); + + Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(port)); Thread.sleep(500); } @Test public void givenClient1_whenServerResponds_thenCorrect() { EchoClient client = new EchoClient(); - client.startConnection("127.0.0.1", PORT); + client.startConnection("127.0.0.1", port); String msg1 = client.sendMessage("hello"); String msg2 = client.sendMessage("world"); String terminate = client.sendMessage("."); @@ -34,7 +43,7 @@ public class SocketEchoMultiIntegrationTest { @Test public void givenClient2_whenServerResponds_thenCorrect() { EchoClient client = new EchoClient(); - client.startConnection("127.0.0.1", PORT); + client.startConnection("127.0.0.1", port); String msg1 = client.sendMessage("hello"); String msg2 = client.sendMessage("world"); String terminate = client.sendMessage("."); @@ -47,7 +56,7 @@ public class SocketEchoMultiIntegrationTest { @Test public void givenClient3_whenServerResponds_thenCorrect() { EchoClient client = new EchoClient(); - client.startConnection("127.0.0.1", PORT); + client.startConnection("127.0.0.1", port); String msg1 = client.sendMessage("hello"); String msg2 = client.sendMessage("world"); String terminate = client.sendMessage("."); diff --git a/core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java b/core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java new file mode 100644 index 0000000000..2cdf6145d3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java @@ -0,0 +1,110 @@ +/** + * + */ +package com.baeldung.string; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +/** + * @author swpraman + * + */ +public class AppendCharAtPositionXUnitTest { + + private AppendCharAtPositionX appendCharAtPosition = new AppendCharAtPositionX(); + private String word = "Titanc"; + private char letter = 'i'; + + @Test + public void whenUsingCharacterArrayAndCharacterAddedAtBeginning_shouldAddCharacter() { + assertEquals("iTitanc", appendCharAtPosition.addCharUsingCharArray(word, letter, 0)); + } + + @Test + public void whenUsingSubstringAndCharacterAddedAtBeginning_shouldAddCharacter() { + assertEquals("iTitanc", appendCharAtPosition.addCharUsingSubstring(word, letter, 0)); + } + + @Test + public void whenUsingStringBuilderAndCharacterAddedAtBeginning_shouldAddCharacter() { + assertEquals("iTitanc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 0)); + } + + @Test + public void whenUsingCharacterArrayAndCharacterAddedAtMiddle_shouldAddCharacter() { + assertEquals("Titianc", appendCharAtPosition.addCharUsingCharArray(word, letter, 3)); + } + + @Test + public void whenUsingSubstringAndCharacterAddedAtMiddle_shouldAddCharacter() { + assertEquals("Titianc", appendCharAtPosition.addCharUsingSubstring(word, letter, 3)); + } + + @Test + public void whenUsingStringBuilderAndCharacterAddedAtMiddle_shouldAddCharacter() { + assertEquals("Titianc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 3)); + } + + @Test + public void whenUsingCharacterArrayAndCharacterAddedAtEnd_shouldAddCharacter() { + assertEquals("Titanci", appendCharAtPosition.addCharUsingCharArray(word, letter, word.length())); + } + + @Test + public void whenUsingSubstringAndCharacterAddedAtEnd_shouldAddCharacter() { + assertEquals("Titanci", appendCharAtPosition.addCharUsingSubstring(word, letter, word.length())); + } + + @Test + public void whenUsingStringBuilderAndCharacterAddedAtEnd_shouldAddCharacter() { + assertEquals("Titanci", appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length())); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingCharacterArrayAndCharacterAddedAtNegativePosition_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingSubstringAndCharacterAddedAtNegativePosition_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingStringBuilderAndCharacterAddedAtNegativePosition_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingCharacterArrayAndCharacterAddedAtInvalidPosition_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingSubstringAndCharacterAddedAtInvalidPosition_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingStringBuilderAndCharacterAddedAtInvalidPosition_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingCharacterArrayAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingSubstringAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingStringBuilderAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3); + } + +} diff --git a/core-java/src/test/java/com/baeldung/string/PalindromeTest.java b/core-java/src/test/java/com/baeldung/string/PalindromeTest.java deleted file mode 100644 index bc6fee2cd9..0000000000 --- a/core-java/src/test/java/com/baeldung/string/PalindromeTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.baeldung.string; - -import static org.junit.Assert.*; -import org.junit.Test; - -public class PalindromeTest { - - private String[] words = { - "Anna", - "Civic", - "Kayak", - "Level", - "Madam", - }; - - private String[] sentences = { - "Sore was I ere I saw Eros", - "Euston saw I was not Sue", - "Too hot to hoot", - "No mists or frost Simon", - "Stella won no wallets" - }; - - private Palindrome palindrome = new Palindrome(); - - @Test - public void whenWord_shouldBePalindrome() { - for (String word : words) - assertTrue(palindrome.isPalindrome(word)); - } - - @Test - public void whenSentence_shouldBePalindrome() { - for (String sentence : sentences) - assertTrue(palindrome.isPalindrome(sentence)); - } - - @Test - public void whenReverseWord_shouldBePalindrome() { - for (String word : words) - assertTrue(palindrome.isPalindromeReverseTheString(word)); - } - - @Test - public void whenReverseSentence_shouldBePalindrome() { - for (String sentence : sentences) - assertTrue(palindrome.isPalindromeReverseTheString(sentence)); - } - - @Test - public void whenStringBuilderWord_shouldBePalindrome() { - for (String word : words) - assertTrue(palindrome.isPalindromeUsingStringBuilder(word)); - } - - @Test - public void whenStringBuilderSentence_shouldBePalindrome() { - for (String sentence : sentences) - assertTrue(palindrome.isPalindromeUsingStringBuilder(sentence)); - } - - @Test - public void whenStringBufferWord_shouldBePalindrome() { - for (String word : words) - assertTrue(palindrome.isPalindromeUsingStringBuffer(word)); - } - - @Test - public void whenStringBufferSentence_shouldBePalindrome() { - for (String sentence : sentences) - assertTrue(palindrome.isPalindromeUsingStringBuffer(sentence)); - } - - @Test - public void whenPalindromeRecursive_wordShouldBePalindrome() { - for (String word : words) - assertTrue(palindrome.isPalindromeRecursive(word)); - } - - @Test - public void whenPalindromeRecursive_sentenceShouldBePalindrome() { - for (String sentence : sentences) - assertTrue(palindrome.isPalindromeRecursive(sentence)); - } - - @Test - public void whenPalindromeStreams_wordShouldBePalindrome() { - for (String word : words) - assertTrue(palindrome.isPalindromeUsingIntStream(word)); - } - - @Test - public void whenPalindromeStreams_sentenceShouldBePalindrome() { - for (String sentence : sentences) - assertTrue(palindrome.isPalindromeUsingIntStream(sentence)); - } -} diff --git a/core-java/src/test/java/com/baeldung/string/StringComparisonTest.java b/core-java/src/test/java/com/baeldung/string/StringComparisonTest.java deleted file mode 100644 index 5869676004..0000000000 --- a/core-java/src/test/java/com/baeldung/string/StringComparisonTest.java +++ /dev/null @@ -1,154 +0,0 @@ -package com.baeldung.string; - -import org.apache.commons.lang3.StringUtils; -import org.junit.Test; - -import java.util.Objects; - -import static org.assertj.core.api.Assertions.assertThat; - -public class StringComparisonTest { - - @Test - public void whenUsingComparisonOperator_ThenComparingStrings(){ - - String string1 = "using comparison operator"; - String string2 = "using comparison operator"; - String string3 = new String("using comparison operator"); - - assertThat(string1 == string2).isTrue(); - assertThat(string1 == string3).isFalse(); - } - - @Test - public void whenUsingEqualsMethod_ThenComparingStrings(){ - - String string1 = "using equals method"; - String string2 = "using equals method"; - - String string3 = "using EQUALS method"; - String string4 = new String("using equals method"); - - assertThat(string1.equals(string2)).isTrue(); - assertThat(string1.equals(string4)).isTrue(); - - assertThat(string1.equals(null)).isFalse(); - assertThat(string1.equals(string3)).isFalse(); - } - - @Test - public void whenUsingEqualsIgnoreCase_ThenComparingStrings(){ - - String string1 = "using equals ignore case"; - String string2 = "USING EQUALS IGNORE CASE"; - - assertThat(string1.equalsIgnoreCase(string2)).isTrue(); - } - - @Test - public void whenUsingCompareTo_ThenComparingStrings(){ - - String author = "author"; - String book = "book"; - String duplicateBook = "book"; - - assertThat(author.compareTo(book)).isEqualTo(-1); - assertThat(book.compareTo(author)).isEqualTo(1); - assertThat(duplicateBook.compareTo(book)).isEqualTo(0); - } - - @Test - public void whenUsingCompareToIgnoreCase_ThenComparingStrings(){ - - String author = "Author"; - String book = "book"; - String duplicateBook = "BOOK"; - - assertThat(author.compareToIgnoreCase(book)).isEqualTo(-1); - assertThat(book.compareToIgnoreCase(author)).isEqualTo(1); - assertThat(duplicateBook.compareToIgnoreCase(book)).isEqualTo(0); - } - - @Test - public void whenUsingObjectsEqualsMethod_ThenComparingStrings(){ - - String string1 = "using objects equals"; - String string2 = "using objects equals"; - String string3 = new String("using objects equals"); - - assertThat(Objects.equals(string1, string2)).isTrue(); - assertThat(Objects.equals(string1, string3)).isTrue(); - - assertThat(Objects.equals(null, null)).isTrue(); - assertThat(Objects.equals(null, string1)).isFalse(); - } - - @Test - public void whenUsingEqualsOfApacheCommons_ThenComparingStrings(){ - - assertThat(StringUtils.equals(null, null)).isTrue(); - assertThat(StringUtils.equals(null, "equals method")).isFalse(); - assertThat(StringUtils.equals("equals method", "equals method")).isTrue(); - assertThat(StringUtils.equals("equals method", "EQUALS METHOD")).isFalse(); - } - - @Test - public void whenUsingEqualsIgnoreCaseOfApacheCommons_ThenComparingStrings(){ - - assertThat(StringUtils.equalsIgnoreCase(null, null)).isTrue(); - assertThat(StringUtils.equalsIgnoreCase(null, "equals method")).isFalse(); - assertThat(StringUtils.equalsIgnoreCase("equals method", "equals method")).isTrue(); - assertThat(StringUtils.equalsIgnoreCase("equals method", "EQUALS METHOD")).isTrue(); - } - - @Test - public void whenUsingEqualsAnyOf_ThenComparingStrings(){ - - assertThat(StringUtils.equalsAny(null, null, null)).isTrue(); - assertThat(StringUtils.equalsAny("equals any", "equals any", "any")).isTrue(); - assertThat(StringUtils.equalsAny("equals any", null, "equals any")).isTrue(); - assertThat(StringUtils.equalsAny(null, "equals", "any")).isFalse(); - assertThat(StringUtils.equalsAny("equals any", "EQUALS ANY", "ANY")).isFalse(); - } - - @Test - public void whenUsingEqualsAnyIgnoreCase_ThenComparingStrings(){ - - assertThat(StringUtils.equalsAnyIgnoreCase(null, null, null)).isTrue(); - assertThat(StringUtils.equalsAnyIgnoreCase("equals any", "equals any", "any")).isTrue(); - assertThat(StringUtils.equalsAnyIgnoreCase("equals any", null, "equals any")).isTrue(); - assertThat(StringUtils.equalsAnyIgnoreCase(null, "equals", "any")).isFalse(); - assertThat(StringUtils.equalsAnyIgnoreCase( - "equals any ignore case", "EQUALS ANY IGNORE CASE", "any")).isTrue(); - } - - @Test - public void whenUsingCompare_thenComparingStringsWithNulls(){ - - assertThat(StringUtils.compare(null, null)).isEqualTo(0); - assertThat(StringUtils.compare(null, "abc")).isEqualTo(-1); - - assertThat(StringUtils.compare("abc", "bbc")).isEqualTo(-1); - assertThat(StringUtils.compare("bbc", "abc")).isEqualTo(1); - assertThat(StringUtils.compare("abc", "abc")).isEqualTo(0); - } - - @Test - public void whenUsingCompareIgnoreCase_ThenComparingStringsWithNulls(){ - - assertThat(StringUtils.compareIgnoreCase(null, null)).isEqualTo(0); - assertThat(StringUtils.compareIgnoreCase(null, "abc")).isEqualTo(-1); - - assertThat(StringUtils.compareIgnoreCase("Abc", "bbc")).isEqualTo(-1); - assertThat(StringUtils.compareIgnoreCase("bbc", "ABC")).isEqualTo(1); - assertThat(StringUtils.compareIgnoreCase("abc", "ABC")).isEqualTo(0); - } - - @Test - public void whenUsingCompareWithNullIsLessOption_ThenComparingStrings(){ - - assertThat(StringUtils.compare(null, "abc", true)).isEqualTo(-1); - assertThat(StringUtils.compare(null, "abc", false)).isEqualTo(1); - } - -} diff --git a/core-java/src/test/java/com/baeldung/string/StringTest.java b/core-java/src/test/java/com/baeldung/string/StringTest.java deleted file mode 100644 index e88b2d7c2c..0000000000 --- a/core-java/src/test/java/com/baeldung/string/StringTest.java +++ /dev/null @@ -1,226 +0,0 @@ -package com.baeldung.string; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.UnsupportedEncodingException; -import java.nio.charset.StandardCharsets; -import java.util.IllegalFormatException; -import java.util.regex.PatternSyntaxException; - -import org.junit.Test; - -public class StringTest { - - @Test - public void whenCallCodePointAt_thenDecimalUnicodeReturned() { - assertEquals(97, "abcd".codePointAt(0)); - } - - @Test(expected = StringIndexOutOfBoundsException.class) - public void whenPassNonExistingIndex_thenExceptionThrown() { - int a = "abcd".codePointAt(4); - } - - @Test - public void whenCallConcat_thenCorrect() { - assertEquals("elephant", "elep".concat("hant")); - } - - @Test - public void whenGetBytes_thenCorrect() throws UnsupportedEncodingException { - byte[] byteArray1 = "abcd".getBytes(); - byte[] byteArray2 = "efgh".getBytes(StandardCharsets.US_ASCII); - byte[] byteArray3 = "ijkl".getBytes("UTF-8"); - byte[] expected1 = new byte[] { 97, 98, 99, 100 }; - byte[] expected2 = new byte[] { 101, 102, 103, 104 }; - byte[] expected3 = new byte[] { 105, 106, 107, 108 }; - - assertArrayEquals(expected1, byteArray1); - assertArrayEquals(expected2, byteArray2); - assertArrayEquals(expected3, byteArray3); - } - - @Test - public void whenGetBytesUsingASCII_thenCorrect() { - byte[] byteArray = "efgh".getBytes(StandardCharsets.US_ASCII); - byte[] expected = new byte[] { 101, 102, 103, 104 }; - - assertArrayEquals(expected, byteArray); - } - - @Test - public void whenCreateStringUsingByteArray_thenCorrect() { - byte[] array = new byte[] { 97, 98, 99, 100 }; - String s = new String(array); - - assertEquals("abcd", s); - } - - @Test - public void whenCallCharAt_thenCorrect() { - assertEquals('P', "Paul".charAt(0)); - } - - @Test(expected = IndexOutOfBoundsException.class) - public void whenCharAtOnNonExistingIndex_thenIndexOutOfBoundsExceptionThrown() { - char character = "Paul".charAt(4); - } - - @Test - public void whenCallCodePointCount_thenCorrect() { - assertEquals(2, "abcd".codePointCount(0, 2)); - } - - @Test(expected = IndexOutOfBoundsException.class) - public void whenSecondIndexEqualToLengthOfString_thenIndexOutOfBoundsExceptionThrown() { - char character = "Paul".charAt(4); - } - - @Test - public void whenCallContains_thenCorrect() { - String s = "abcd"; - - assertTrue(s.contains("abc")); - assertFalse(s.contains("cde")); - } - - @Test - public void whenCallCopyValueOf_thenStringConstructed() { - char[] array = new char[] { 'a', 'b', 'c', 'd' }; - - assertEquals("abcd", String.copyValueOf(array)); - } - - @Test - public void whenCallEndsWith_thenCorrect() { - String s1 = "test"; - - assertTrue(s1.endsWith("t")); - } - - @Test - public void whenFormat_thenCorrect() { - String value = "Baeldung"; - String formatted = String.format("Welcome to %s!", value); - - assertEquals("Welcome to Baeldung!", formatted); - } - - @Test(expected = IllegalFormatException.class) - public void whenInvalidFormatSyntax_thenIllegalFormatExceptionThrown() { - String value = "Baeldung"; - String formatted = String.format("Welcome to %x!", value); - } - - @Test - public void whenCallIndexOf_thenCorrect() { - assertEquals(1, "foo".indexOf("o")); - } - - @Test - public void whenCallIsEmpty_thenCorrect() { - String s1 = ""; - - assertTrue(s1.isEmpty()); - } - - @Test - public void whenCallLastIndexOf_thenCorrect() { - assertEquals(2, "foo".lastIndexOf("o")); - assertEquals(2, "foo".lastIndexOf(111)); - } - - @Test - public void whenCallRegionMatches_thenCorrect() { - assertTrue("welcome to baeldung".regionMatches(false, 11, "baeldung", 0, 8)); - } - - @Test - public void whenCallStartsWith_thenCorrect() { - assertTrue("foo".startsWith("f")); - } - - @Test - public void whenTrim_thenCorrect() { - assertEquals("foo", " foo ".trim()); - } - - @Test - public void whenSplit_thenCorrect() { - String s = "Welcome to Baeldung"; - String[] array = new String[] { "Welcome", "to", "Baeldung" }; - - assertArrayEquals(array, s.split(" ")); - } - - @Test(expected = PatternSyntaxException.class) - public void whenPassInvalidParameterToSplit_thenPatternSyntaxExceptionThrown() { - String s = "Welcome*to Baeldung"; - - String[] result = s.split("*"); - } - - @Test - public void whenCallSubSequence_thenCorrect() { - String s = "Welcome to Baeldung"; - - assertEquals("Welcome", s.subSequence(0, 7)); - } - - @Test - public void whenCallSubstring_thenCorrect() { - String s = "Welcome to Baeldung"; - - assertEquals("Welcome", s.substring(0, 7)); - } - - @Test(expected = IndexOutOfBoundsException.class) - public void whenSecondIndexEqualToLengthOfString_thenCorrect() { - String s = "Welcome to Baeldung"; - - String sub = s.substring(0, 20); - } - - @Test - public void whenConvertToUpperCase_thenCorrect() { - String s = "Welcome to Baeldung!"; - - assertEquals("WELCOME TO BAELDUNG!", s.toUpperCase()); - } - - @Test - public void whenConvertToLowerCase_thenCorrect() { - String s = "WELCOME to BAELDUNG!"; - - assertEquals("welcome to baeldung!", s.toLowerCase()); - } - - @Test - public void whenCallReplace_thenCorrect() { - String s = "I learn Spanish"; - - assertEquals("I learn French", s.replaceAll("Spanish", "French")); - } - - @Test - public void whenIntern_thenCorrect() { - String s1 = "abc"; - String s2 = new String("abc"); - String s3 = new String("foo"); - String s4 = s1.intern(); - String s5 = s2.intern(); - - assertFalse(s3 == s4); - assertTrue(s1 == s5); - } - - @Test - public void whenCallValueOf_thenCorrect() { - long l = 200L; - - assertEquals("200", String.valueOf(l)); - } -} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java b/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java deleted file mode 100644 index ad4f5dce7e..0000000000 --- a/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java +++ /dev/null @@ -1,141 +0,0 @@ -package com.baeldung.string.formatter; - -import java.util.Calendar; -import java.util.Formatter; -import java.util.GregorianCalendar; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import org.junit.Test; - -public class StringFormatterExampleTests { - - @Test - public void givenString_whenFormatSpecifierForCalendar_thenGotExpected() { - //Syntax of Format Specifiers for Date/Time Representation - Calendar c = new GregorianCalendar(2017, 11, 10); - String s = String.format("The date is: %tm %1$te,%1$tY", c); - - - assertEquals("The date is: 12 10,2017", s); - } - - @Test - public void givenString_whenGeneralConversion_thenConvertedString() { - //General Conversions - String s = String.format("The correct answer is %s", false); - assertEquals("The correct answer is false", s); - - s = String.format("The correct answer is %b", null); - assertEquals("The correct answer is false", s); - - s = String.format("The correct answer is %B", true); - assertEquals("The correct answer is TRUE", s); - } - - @Test - public void givenString_whenCharConversion_thenConvertedString() { - //Character Conversions - String s = String.format("The correct answer is %c", 'a'); - assertEquals("The correct answer is a", s); - - s = String.format("The correct answer is %c", null); - assertEquals("The correct answer is null", s); - - s = String.format("The correct answer is %C", 'b'); - assertEquals("The correct answer is B", s); - - s = String.format("The valid unicode character: %c", 0x0400); - assertTrue(Character.isValidCodePoint(0x0400)); - assertEquals("The valid unicode character: Ѐ", s); - } - - @Test(expected = java.util.IllegalFormatCodePointException.class) - public void givenString_whenIllegalCodePointForConversion_thenError() { - String s = String.format("The valid unicode character: %c", 0x11FFFF); - assertFalse(Character.isValidCodePoint(0x11FFFF)); - assertEquals("The valid unicode character: Ä€", s); - } - - @Test - public void givenString_whenNumericIntegralConversion_thenConvertedString() { - //Numeric Integral Conversions - String s = String.format("The number 25 in decimal = %d", 25); - assertEquals("The number 25 in decimal = 25", s); - - s = String.format("The number 25 in octal = %o", 25); - assertEquals("The number 25 in octal = 31", s); - - s = String.format("The number 25 in hexadecimal = %x", 25); - assertEquals("The number 25 in hexadecimal = 19", s); - } - - @Test - public void givenString_whenNumericFloatingConversion_thenConvertedString() { - //Numeric Floating-point Conversions - String s = String.format("The computerized scientific format of 10000.00 " - + "= %e", 10000.00); - assertEquals("The computerized scientific format of 10000.00 = 1.000000e+04", s); - - s = String.format("The decimal format of 10.019 = %f", 10.019); - assertEquals("The decimal format of 10.019 = 10.019000", s); - } - - @Test - public void givenString_whenLineSeparatorConversion_thenConvertedString() { - //Line Separator Conversion - String s = String.format("First Line %nSecond Line"); - assertEquals("First Line " + System.getProperty("line.separator") - + "Second Line", s); - } - - @Test - public void givenString_whenSpecifyFlag_thenGotFormattedString() { - //Without left-justified flag - String s = String.format("Without left justified flag: %5d", 25); - assertEquals("Without left justified flag: 25", s); - - //Using left-justified flag - s = String.format("With left justified flag: %-5d", 25); - assertEquals("With left justified flag: 25 ", s); - } - - @Test - public void givenString_whenSpecifyPrecision_thenGotExpected() { - - //Precision - String s = String.format("Output of 25.09878 with Precision 2: %.2f", 25.09878); - assertEquals("Output of 25.09878 with Precision 2: 25.10", s); - - s = String.format("Output of general conversion type with Precision 2: %.2b", true); - assertEquals("Output of general conversion type with Precision 2: tr", s); - } - - @Test - public void givenString_whenSpecifyArgumentIndex_thenGotExpected() { - Calendar c = new GregorianCalendar(2017, 11, 10); - //Argument_Index - String s = String.format("The date is: %tm %1$te,%1$tY", c); - assertEquals("The date is: 12 10,2017", s); - - s = String.format("The date is: %tm %[] constructors = SyntheticConstructorDemo.NestedClass.class.getDeclaredConstructors(); + Assert.assertEquals("This class should contain only two constructors", 2, constructors.length); + + for (Constructor c : constructors) { + System.out.println("Constructor: " + c.getName() + ", isSynthetic: " + c.isSynthetic()); + + // Counts the synthetic constructors. + if (c.isSynthetic()) { + syntheticConstructors++; + } + } + + // Checks that there's exactly one synthetic constructor. + Assert.assertEquals(1, syntheticConstructors); + } + + /** + * Tests that {@link SyntheticFieldDemo.NestedClass} contains a synthetic field. + */ + @Test + public void givenSyntheticField_whenIsSinthetic_thenTrue() { + // This class should contain exactly one synthetic field. + Field[] fields = SyntheticFieldDemo.NestedClass.class.getDeclaredFields(); + Assert.assertEquals("This class should contain only one field", 1, fields.length); + + for (Field f : fields) { + System.out.println("Field: " + f.getName() + ", isSynthetic: " + f.isSynthetic()); + Assert.assertTrue("All the fields of this class should be synthetic", f.isSynthetic()); + } + } + + /** + * Tests that {@link BridgeMethodDemo} contains a synthetic bridge method. + */ + @Test + public void givenBridgeMethod_whenIsBridge_thenTrue() { + // This class should contain exactly one synthetic bridge method. + int syntheticMethods = 0; + Method[] methods = BridgeMethodDemo.class.getDeclaredMethods(); + for (Method m : methods) { + System.out.println( + "Method: " + m.getName() + ", isSynthetic: " + m.isSynthetic() + ", isBridge: " + m.isBridge()); + + // Counts the synthetic methods and checks that they are also bridge + // methods. + if (m.isSynthetic()) { + syntheticMethods++; + Assert.assertTrue("The synthetic method in this class should also be a bridge method", m.isBridge()); + } + } + + // Checks that there's exactly one synthetic bridge method. + Assert.assertEquals("There should be exactly 1 synthetic bridge method in this class", 1, syntheticMethods); + } + +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/system/DateTimeServiceTest.java b/core-java/src/test/java/com/baeldung/system/DateTimeServiceTest.java deleted file mode 100644 index 587cd4ef20..0000000000 --- a/core-java/src/test/java/com/baeldung/system/DateTimeServiceTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.system; - -import org.junit.Assert; -import org.junit.Test; - -public class DateTimeServiceTest { - - @Test - public void givenClass_whenCalledMethods_thenNotNullInResult() { - DateTimeService dateTimeService = new DateTimeService(); - - Assert.assertNotNull(dateTimeService.nowPlusOneHour()); - Assert.assertNotNull(dateTimeService.nowPrettyPrinted()); - } -} diff --git a/core-java/src/test/java/com/baeldung/system/DateTimeServiceUnitTest.java b/core-java/src/test/java/com/baeldung/system/DateTimeServiceUnitTest.java new file mode 100644 index 0000000000..ef083dd25e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/system/DateTimeServiceUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.system; + +import org.junit.Assert; +import org.junit.Test; + +public class DateTimeServiceUnitTest { + + @Test + public void givenClass_whenCalledMethods_thenNotNullInResult() { + DateTimeService dateTimeService = new DateTimeService(); + + Assert.assertNotNull(dateTimeService.nowPlusOneHour()); + Assert.assertNotNull(dateTimeService.nowPrettyPrinted()); + } +} diff --git a/core-java/src/test/java/com/baeldung/system/EnvironmentVariablesTest.java b/core-java/src/test/java/com/baeldung/system/EnvironmentVariablesTest.java deleted file mode 100644 index 3722fea88f..0000000000 --- a/core-java/src/test/java/com/baeldung/system/EnvironmentVariablesTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.system; - -import org.junit.Assert; -import org.junit.Test; - -public class EnvironmentVariablesTest { - - @Test - public void givenEnvVars_whenReadPath_thenGetValueinResult() { - EnvironmentVariables environmentVariables = new EnvironmentVariables(); - - Assert.assertNotNull(environmentVariables.getPath()); - } -} diff --git a/core-java/src/test/java/com/baeldung/system/EnvironmentVariablesUnitTest.java b/core-java/src/test/java/com/baeldung/system/EnvironmentVariablesUnitTest.java new file mode 100644 index 0000000000..5e4db747be --- /dev/null +++ b/core-java/src/test/java/com/baeldung/system/EnvironmentVariablesUnitTest.java @@ -0,0 +1,14 @@ +package com.baeldung.system; + +import org.junit.Assert; +import org.junit.Test; + +public class EnvironmentVariablesUnitTest { + + @Test + public void givenEnvVars_whenReadPath_thenGetValueinResult() { + EnvironmentVariables environmentVariables = new EnvironmentVariables(); + + Assert.assertNotNull(environmentVariables.getPath()); + } +} diff --git a/core-java/src/test/java/com/baeldung/system/SystemArrayCopyTest.java b/core-java/src/test/java/com/baeldung/system/SystemArrayCopyTest.java deleted file mode 100644 index f54e3702c8..0000000000 --- a/core-java/src/test/java/com/baeldung/system/SystemArrayCopyTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.system; - -import org.junit.Assert; -import org.junit.Test; - -public class SystemArrayCopyTest { - - @Test - public void givenTwoArraysAB_whenUseArrayCopy_thenArrayCopiedFromAToBInResult() { - int[] a = {34, 22, 44, 2, 55, 3}; - int[] b = new int[a.length]; - - // copy all elements from a to b - System.arraycopy(a, 0, b, 0, a.length); - Assert.assertArrayEquals(a, b); - } - - @Test - public void givenTwoArraysAB_whenUseArrayCopyPosition_thenArrayCopiedFromAToBInResult() { - int[] a = {34, 22, 44, 2, 55, 3}; - int[] b = new int[a.length]; - - // copy 2 elements from a, starting at a[1] to b, starting at b[3] - System.arraycopy(a, 1, b, 3, 2); - Assert.assertArrayEquals(new int[] {0, 0, 0, 22, 44, 0}, b); - } -} diff --git a/core-java/src/test/java/com/baeldung/system/SystemArrayCopyUnitTest.java b/core-java/src/test/java/com/baeldung/system/SystemArrayCopyUnitTest.java new file mode 100644 index 0000000000..bf715f3ac3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/system/SystemArrayCopyUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.system; + +import org.junit.Assert; +import org.junit.Test; + +public class SystemArrayCopyUnitTest { + + @Test + public void givenTwoArraysAB_whenUseArrayCopy_thenArrayCopiedFromAToBInResult() { + int[] a = {34, 22, 44, 2, 55, 3}; + int[] b = new int[a.length]; + + // copy all elements from a to b + System.arraycopy(a, 0, b, 0, a.length); + Assert.assertArrayEquals(a, b); + } + + @Test + public void givenTwoArraysAB_whenUseArrayCopyPosition_thenArrayCopiedFromAToBInResult() { + int[] a = {34, 22, 44, 2, 55, 3}; + int[] b = new int[a.length]; + + // copy 2 elements from a, starting at a[1] to b, starting at b[3] + System.arraycopy(a, 1, b, 3, 2); + Assert.assertArrayEquals(new int[] {0, 0, 0, 22, 44, 0}, b); + } +} diff --git a/core-java/src/test/java/com/baeldung/system/SystemNanoTest.java b/core-java/src/test/java/com/baeldung/system/SystemNanoTest.java deleted file mode 100644 index bf6590da0a..0000000000 --- a/core-java/src/test/java/com/baeldung/system/SystemNanoTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.system; - -import org.junit.Assert; -import org.junit.Test; - -public class SystemNanoTest { - - @Test - public void givenSystem_whenCalledNanoTime_thenGivesTimeinResult() { - long startTime = System.nanoTime(); - // do something that takes time - long endTime = System.nanoTime(); - - Assert.assertTrue(endTime - startTime < 10000); - } -} diff --git a/core-java/src/test/java/com/baeldung/system/SystemNanoUnitTest.java b/core-java/src/test/java/com/baeldung/system/SystemNanoUnitTest.java new file mode 100644 index 0000000000..cd9543212e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/system/SystemNanoUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.system; + +import org.junit.Assert; +import org.junit.Test; + +public class SystemNanoUnitTest { + + @Test + public void givenSystem_whenCalledNanoTime_thenGivesTimeinResult() { + long startTime = System.nanoTime(); + // do something that takes time + long endTime = System.nanoTime(); + + Assert.assertTrue(endTime - startTime < 10000); + } +} diff --git a/core-java/src/test/java/com/baeldung/system/SystemPropertiesTest.java b/core-java/src/test/java/com/baeldung/system/SystemPropertiesTest.java deleted file mode 100644 index 4fca27f96c..0000000000 --- a/core-java/src/test/java/com/baeldung/system/SystemPropertiesTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.system; - -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - -import java.util.Properties; - -public class SystemPropertiesTest { - - @Test - public void givenSystem_whenCalledGetProperty_thenReturnPropertyinResult() { - Assert.assertNotNull(System.getProperty("java.vm.vendor")); - } - - @Test - public void givenSystem_whenCalledSetProperty_thenSetPropertyasResult() { - - // set a particular property - System.setProperty("abckey", "abcvaluefoo"); - Assert.assertEquals("abcvaluefoo", System.getProperty("abckey")); - } - - @Test - public void givenSystem_whenCalledClearProperty_thenDeletePropertyasResult() { - - // Delete a property - System.clearProperty("abckey"); - Assert.assertNull(System.getProperty("abckey")); - } - - @Test - public void givenSystem_whenCalledGetPropertyDefaultValue_thenReturnPropertyinResult() { - - System.clearProperty("dbHost"); - String myKey = System.getProperty("dbHost", "db.host.com"); - Assert.assertEquals("db.host.com", myKey); - } - - @Test - public void givenSystem_whenCalledGetProperties_thenReturnPropertiesinResult() { - Properties properties = System.getProperties(); - - Assert.assertNotNull(properties); - } - - @Test - @Ignore - public void givenSystem_whenCalledClearProperties_thenDeleteAllPropertiesasResult() { - - // Clears all system properties. Use with care! - System.getProperties().clear(); - - Assert.assertTrue(System.getProperties().isEmpty()); - } -} diff --git a/core-java/src/test/java/com/baeldung/system/SystemPropertiesUnitTest.java b/core-java/src/test/java/com/baeldung/system/SystemPropertiesUnitTest.java new file mode 100644 index 0000000000..4940e39238 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/system/SystemPropertiesUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.system; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +import java.util.Properties; + +public class SystemPropertiesUnitTest { + + @Test + public void givenSystem_whenCalledGetProperty_thenReturnPropertyinResult() { + Assert.assertNotNull(System.getProperty("java.vm.vendor")); + } + + @Test + public void givenSystem_whenCalledSetProperty_thenSetPropertyasResult() { + + // set a particular property + System.setProperty("abckey", "abcvaluefoo"); + Assert.assertEquals("abcvaluefoo", System.getProperty("abckey")); + } + + @Test + public void givenSystem_whenCalledClearProperty_thenDeletePropertyasResult() { + + // Delete a property + System.clearProperty("abckey"); + Assert.assertNull(System.getProperty("abckey")); + } + + @Test + public void givenSystem_whenCalledGetPropertyDefaultValue_thenReturnPropertyinResult() { + + System.clearProperty("dbHost"); + String myKey = System.getProperty("dbHost", "db.host.com"); + Assert.assertEquals("db.host.com", myKey); + } + + @Test + public void givenSystem_whenCalledGetProperties_thenReturnPropertiesinResult() { + Properties properties = System.getProperties(); + + Assert.assertNotNull(properties); + } + + @Test + @Ignore + public void givenSystem_whenCalledClearProperties_thenDeleteAllPropertiesasResult() { + + // Clears all system properties. Use with care! + System.getProperties().clear(); + + Assert.assertTrue(System.getProperties().isEmpty()); + } +} diff --git a/core-java/src/test/java/com/baeldung/system/WhenDetectingOSTest.java b/core-java/src/test/java/com/baeldung/system/WhenDetectingOSTest.java deleted file mode 100644 index 77901f6524..0000000000 --- a/core-java/src/test/java/com/baeldung/system/WhenDetectingOSTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.system; - -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - -@Ignore -public class WhenDetectingOSTest { - - private DetectOS os = new DetectOS(); - - @Test - public void whenUsingSystemProperty_shouldReturnOS() { - String expected = "Windows 10"; - String actual = os.getOperatingSystem(); - Assert.assertEquals(expected, actual); - } - - @Test - public void whenUsingSystemUtils_shouldReturnOS() { - String expected = "Windows 10"; - String actual = os.getOperatingSystemSystemUtils(); - Assert.assertEquals(expected, actual); - } -} diff --git a/core-java/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java b/core-java/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java new file mode 100644 index 0000000000..27a6dd43c6 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.system; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +@Ignore +public class WhenDetectingOSUnitTest { + + private DetectOS os = new DetectOS(); + + @Test + public void whenUsingSystemProperty_shouldReturnOS() { + String expected = "Windows 10"; + String actual = os.getOperatingSystem(); + Assert.assertEquals(expected, actual); + } + + @Test + public void whenUsingSystemUtils_shouldReturnOS() { + String expected = "Windows 10"; + String actual = os.getOperatingSystemSystemUtils(); + Assert.assertEquals(expected, actual); + } +} diff --git a/core-java/src/test/java/com/baeldung/thread/join/ThreadJoinUnitTest.java b/core-java/src/test/java/com/baeldung/thread/join/ThreadJoinUnitTest.java new file mode 100644 index 0000000000..85cff51eb3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/thread/join/ThreadJoinUnitTest.java @@ -0,0 +1,95 @@ +package com.baeldung.thread.join; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.logging.Logger; + +import org.junit.Ignore; +import org.junit.Test; + +/** + * Demonstrates Thread.join behavior. + * + */ +public class ThreadJoinUnitTest { + + final static Logger LOGGER = Logger.getLogger(ThreadJoinUnitTest.class.getName()); + + class SampleThread extends Thread { + public int processingCount = 0; + + SampleThread(int processingCount) { + this.processingCount = processingCount; + LOGGER.info("Thread " + this.getName() + " created"); + } + + @Override + public void run() { + LOGGER.info("Thread " + this.getName() + " started"); + while (processingCount > 0) { + try { + Thread.sleep(1000); // Simulate some work being done by thread + } catch (InterruptedException e) { + LOGGER.info("Thread " + this.getName() + " interrupted."); + } + processingCount--; + LOGGER.info("Inside Thread " + this.getName() + ", processingCount = " + processingCount); + } + LOGGER.info("Thread " + this.getName() + " exiting"); + } + } + + @Test + public void givenNewThread_whenJoinCalled_returnsImmediately() throws InterruptedException { + Thread t1 = new SampleThread(0); + LOGGER.info("Invoking join."); + t1.join(); + LOGGER.info("Returned from join"); + LOGGER.info("Thread state is" + t1.getState()); + assertFalse(t1.isAlive()); + } + + @Test + public void givenStartedThread_whenJoinCalled_waitsTillCompletion() + throws InterruptedException { + Thread t2 = new SampleThread(1); + t2.start(); + LOGGER.info("Invoking join."); + t2.join(); + LOGGER.info("Returned from join"); + assertFalse(t2.isAlive()); + } + + @Test + public void givenStartedThread_whenTimedJoinCalled_waitsUntilTimedout() + throws InterruptedException { + Thread t3 = new SampleThread(10); + t3.start(); + t3.join(1000); + assertTrue(t3.isAlive()); + } + + @Test + @Ignore + public void givenThreadTerminated_checkForEffect_notGuaranteed() + throws InterruptedException { + SampleThread t4 = new SampleThread(10); + t4.start(); + //not guaranteed to stop even if t4 finishes. + do { + + } while (t4.processingCount > 0); + } + + @Test + public void givenJoinWithTerminatedThread_checkForEffect_guaranteed() + throws InterruptedException { + SampleThread t4 = new SampleThread(10); + t4.start(); + do { + t4.join(100); + } while (t4.processingCount > 0); + } + +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomIntegrationTest.java b/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomIntegrationTest.java new file mode 100644 index 0000000000..56c77f923f --- /dev/null +++ b/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomIntegrationTest.java @@ -0,0 +1,63 @@ +package com.baeldung.threadlocalrandom; + +import java.util.concurrent.ThreadLocalRandom; + +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class ThreadLocalRandomIntegrationTest { + + @Test + public void givenUsingThreadLocalRandom_whenGeneratingRandomIntBounded_thenCorrect() { + int leftLimit = 1; + int rightLimit = 100; + int generatedInt = ThreadLocalRandom.current().nextInt(leftLimit, rightLimit); + + assertTrue(generatedInt < rightLimit && generatedInt >= leftLimit); + } + + @Test + public void givenUsingThreadLocalRandom_whenGeneratingRandomIntUnbounded_thenCorrect() { + int generatedInt = ThreadLocalRandom.current().nextInt(); + + assertTrue(generatedInt < Integer.MAX_VALUE && generatedInt >= Integer.MIN_VALUE); + } + + @Test + public void givenUsingThreadLocalRandom_whenGeneratingRandomLongBounded_thenCorrect() { + long leftLimit = 1L; + long rightLimit = 100L; + long generatedLong = ThreadLocalRandom.current().nextLong(leftLimit, rightLimit); + + assertTrue(generatedLong < rightLimit && generatedLong >= leftLimit); + } + + @Test + public void givenUsingThreadLocalRandom_whenGeneratingRandomLongUnbounded_thenCorrect() { + long generatedInt = ThreadLocalRandom.current().nextLong(); + + assertTrue(generatedInt < Long.MAX_VALUE && generatedInt >= Long.MIN_VALUE); + } + + @Test + public void givenUsingThreadLocalRandom_whenGeneratingRandomDoubleBounded_thenCorrect() { + double leftLimit = 1D; + double rightLimit = 100D; + double generatedInt = ThreadLocalRandom.current().nextDouble(leftLimit, rightLimit); + + assertTrue(generatedInt < rightLimit && generatedInt >= leftLimit); + } + + @Test + public void givenUsingThreadLocalRandom_whenGeneratingRandomDoubleUnbounded_thenCorrect() { + double generatedInt = ThreadLocalRandom.current().nextDouble(); + + assertTrue(generatedInt < Double.MAX_VALUE && generatedInt >= Double.MIN_VALUE); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenUsingThreadLocalRandom_whenSettingSeed_thenThrowUnsupportedOperationException() { + ThreadLocalRandom.current().setSeed(0l); + } + +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java b/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java deleted file mode 100644 index c75813baba..0000000000 --- a/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.baeldung.threadlocalrandom; - -import java.util.concurrent.ThreadLocalRandom; - -import static org.junit.Assert.assertTrue; -import org.junit.Test; - -public class ThreadLocalRandomTest { - - @Test - public void givenUsingThreadLocalRandom_whenGeneratingRandomIntBounded_thenCorrect() { - int leftLimit = 1; - int rightLimit = 100; - int generatedInt = ThreadLocalRandom.current().nextInt(leftLimit, rightLimit); - - assertTrue(generatedInt < rightLimit && generatedInt >= leftLimit); - } - - @Test - public void givenUsingThreadLocalRandom_whenGeneratingRandomIntUnbounded_thenCorrect() { - int generatedInt = ThreadLocalRandom.current().nextInt(); - - assertTrue(generatedInt < Integer.MAX_VALUE && generatedInt >= Integer.MIN_VALUE); - } - - @Test - public void givenUsingThreadLocalRandom_whenGeneratingRandomLongBounded_thenCorrect() { - long leftLimit = 1L; - long rightLimit = 100L; - long generatedLong = ThreadLocalRandom.current().nextLong(leftLimit, rightLimit); - - assertTrue(generatedLong < rightLimit && generatedLong >= leftLimit); - } - - @Test - public void givenUsingThreadLocalRandom_whenGeneratingRandomLongUnbounded_thenCorrect() { - long generatedInt = ThreadLocalRandom.current().nextLong(); - - assertTrue(generatedInt < Long.MAX_VALUE && generatedInt >= Long.MIN_VALUE); - } - - @Test - public void givenUsingThreadLocalRandom_whenGeneratingRandomDoubleBounded_thenCorrect() { - double leftLimit = 1D; - double rightLimit = 100D; - double generatedInt = ThreadLocalRandom.current().nextDouble(leftLimit, rightLimit); - - assertTrue(generatedInt < rightLimit && generatedInt >= leftLimit); - } - - @Test - public void givenUsingThreadLocalRandom_whenGeneratingRandomDoubleUnbounded_thenCorrect() { - double generatedInt = ThreadLocalRandom.current().nextDouble(); - - assertTrue(generatedInt < Double.MAX_VALUE && generatedInt >= Double.MIN_VALUE); - } - - @Test(expected = UnsupportedOperationException.class) - public void givenUsingThreadLocalRandom_whenSettingSeed_thenThrowUnsupportedOperationException() { - ThreadLocalRandom.current().setSeed(0l); - } - -} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java b/core-java/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java new file mode 100644 index 0000000000..ef838ed304 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.throwsexception; + +import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class CalculatorUnitTest { + + @Test + public void whenDividerIsZero_thenDivideByZeroExceptionIsThrown() { + Calculator calculator = new Calculator(); + + assertThrows(DivideByZeroException.class, + () -> calculator.divide(10, 0)); + } + +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/throwsexception/SimpleServiceUnitTest.java b/core-java/src/test/java/com/baeldung/throwsexception/SimpleServiceUnitTest.java new file mode 100644 index 0000000000..b9a658a960 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/throwsexception/SimpleServiceUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.throwsexception; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class SimpleServiceUnitTest { + + SimpleService simpleService = new SimpleService(); + + @Test + void whenSQLExceptionIsThrown_thenShouldBeRethrownWithWrappedException() { + assertThrows(DataAccessException.class, + () -> simpleService.wrappingException()); + } + + @Test + void whenCalled_thenNullPointerExceptionIsThrown() { + assertThrows(NullPointerException.class, + () -> simpleService.runtimeNullPointerException()); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java b/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java index 6aa59e68d0..22fe0f5e57 100644 --- a/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java +++ b/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.unsafe; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import sun.misc.Unsafe; @@ -56,6 +57,7 @@ public class UnsafeUnitTest { } @Test + @Ignore // Uncomment for local public void givenArrayBiggerThatMaxInt_whenAllocateItOffHeapMemory_thenSuccess() throws NoSuchFieldException, IllegalAccessException { //given long SUPER_SIZE = (long) Integer.MAX_VALUE * 2; diff --git a/core-java/src/test/java/com/baeldung/util/PropertiesLoaderTest.java b/core-java/src/test/java/com/baeldung/util/PropertiesLoaderTest.java deleted file mode 100644 index fa3c425156..0000000000 --- a/core-java/src/test/java/com/baeldung/util/PropertiesLoaderTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.util; - -import org.junit.Test; - -import java.io.IOException; -import java.util.Properties; - -import static org.junit.Assert.assertEquals; - -public class PropertiesLoaderTest { - - @Test - public void loadProperties_whenPropertyReaded_thenSuccess() throws IOException { - //given - final String RESOURCE_FILE_NAME = "configuration.properties"; - - final String SAMPLE_CONF_ENTRY = "sampleConfEntry"; - final String COLON_SEPARATED_CONF_ENTRY = "colonSeparatedEntry"; - - final String GIVEN_CONF_ENTRY_VALUE = "sample String value"; - final String COLON_SEPARATED_CONF_ENTRY_VALUE = "colon separated entry value"; - - //when - Properties config = PropertiesLoader.loadProperties(RESOURCE_FILE_NAME); - - String sampleConfEntryValue = config.getProperty(SAMPLE_CONF_ENTRY); - String colonSeparatedConfEntryValue = config.getProperty(COLON_SEPARATED_CONF_ENTRY); - - //then - assertEquals(GIVEN_CONF_ENTRY_VALUE, sampleConfEntryValue); - assertEquals(COLON_SEPARATED_CONF_ENTRY_VALUE, colonSeparatedConfEntryValue); - - } -} diff --git a/core-java/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java b/core-java/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java new file mode 100644 index 0000000000..eea3068253 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.util; + +import org.junit.Test; + +import java.io.IOException; +import java.util.Properties; + +import static org.junit.Assert.assertEquals; + +public class PropertiesLoaderUnitTest { + + @Test + public void loadProperties_whenPropertyReaded_thenSuccess() throws IOException { + //given + final String RESOURCE_FILE_NAME = "configuration.properties"; + + final String SAMPLE_CONF_ENTRY = "sampleConfEntry"; + final String COLON_SEPARATED_CONF_ENTRY = "colonSeparatedEntry"; + + final String GIVEN_CONF_ENTRY_VALUE = "sample String value"; + final String COLON_SEPARATED_CONF_ENTRY_VALUE = "colon separated entry value"; + + //when + Properties config = PropertiesLoader.loadProperties(RESOURCE_FILE_NAME); + + String sampleConfEntryValue = config.getProperty(SAMPLE_CONF_ENTRY); + String colonSeparatedConfEntryValue = config.getProperty(COLON_SEPARATED_CONF_ENTRY); + + //then + assertEquals(GIVEN_CONF_ENTRY_VALUE, sampleConfEntryValue); + assertEquals(COLON_SEPARATED_CONF_ENTRY_VALUE, colonSeparatedConfEntryValue); + + } +} diff --git a/core-java/src/test/java/com/baeldung/varargs/FormatterTest.java b/core-java/src/test/java/com/baeldung/varargs/FormatterTest.java deleted file mode 100644 index 509c8764d2..0000000000 --- a/core-java/src/test/java/com/baeldung/varargs/FormatterTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.varargs; - -import org.junit.Test; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; - -public class FormatterTest { - - private final static String FORMAT = "%s %s %s"; - - @Test - public void givenNoArgument_thenEmptyAndTwoSpacesAreReturned() { - String actualResult = format(); - - assertThat(actualResult, is("empty ")); - } - - @Test - public void givenOneArgument_thenResultHasTwoTrailingSpace() { - String actualResult = format("baeldung"); - - assertThat(actualResult, is("baeldung ")); - } - - @Test - public void givenTwoArguments_thenOneTrailingSpaceExists() { - String actualResult = format("baeldung", "rocks"); - - assertThat(actualResult, is("baeldung rocks ")); - } - - @Test - public void givenMoreThanThreeArguments_thenTheFirstThreeAreUsed() { - String actualResult = formatWithVarArgs("baeldung", "rocks", "java", "and", "spring"); - - assertThat(actualResult, is("baeldung rocks java")); - } - - public String format() { - return format("empty", ""); - } - - public String format(String value) { - return format(value, ""); - } - - public String format(String val1, String val2) { - return String.format(FORMAT, val1, val2, ""); - } - - public String formatWithVarArgs(String... values) { - if (values.length == 0) { - return "no arguments given"; - } - - return String.format(FORMAT, values); - } - -} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/varargs/FormatterUnitTest.java b/core-java/src/test/java/com/baeldung/varargs/FormatterUnitTest.java new file mode 100644 index 0000000000..e9018afd62 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/varargs/FormatterUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.varargs; + +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +public class FormatterUnitTest { + + private final static String FORMAT = "%s %s %s"; + + @Test + public void givenNoArgument_thenEmptyAndTwoSpacesAreReturned() { + String actualResult = format(); + + assertThat(actualResult, is("empty ")); + } + + @Test + public void givenOneArgument_thenResultHasTwoTrailingSpace() { + String actualResult = format("baeldung"); + + assertThat(actualResult, is("baeldung ")); + } + + @Test + public void givenTwoArguments_thenOneTrailingSpaceExists() { + String actualResult = format("baeldung", "rocks"); + + assertThat(actualResult, is("baeldung rocks ")); + } + + @Test + public void givenMoreThanThreeArguments_thenTheFirstThreeAreUsed() { + String actualResult = formatWithVarArgs("baeldung", "rocks", "java", "and", "spring"); + + assertThat(actualResult, is("baeldung rocks java")); + } + + public String format() { + return format("empty", ""); + } + + public String format(String value) { + return format(value, ""); + } + + public String format(String val1, String val2) { + return String.format(FORMAT, val1, val2, ""); + } + + public String formatWithVarArgs(String... values) { + if (values.length == 0) { + return "no arguments given"; + } + + return String.format(FORMAT, values); + } + +} \ No newline at end of file diff --git a/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java b/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java deleted file mode 100644 index bb3abff28d..0000000000 --- a/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.baeldung.java.enums; - -import static junit.framework.TestCase.assertTrue; - -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; - -import org.junit.Test; - -import com.baeldung.enums.Pizza; - -public class PizzaUnitTest { - - @Test - public void givenPizaOrder_whenReady_thenDeliverable() { - Pizza testPz = new Pizza(); - testPz.setStatus(Pizza.PizzaStatusEnum.READY); - assertTrue(testPz.isDeliverable()); - } - - @Test - public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() { - List pzList = new ArrayList<>(); - Pizza pz1 = new Pizza(); - pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED); - - Pizza pz2 = new Pizza(); - pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED); - - Pizza pz3 = new Pizza(); - pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED); - - Pizza pz4 = new Pizza(); - pz4.setStatus(Pizza.PizzaStatusEnum.READY); - - pzList.add(pz1); - pzList.add(pz2); - pzList.add(pz3); - pzList.add(pz4); - - List undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList); - assertTrue(undeliveredPzs.size() == 3); - } - - @Test - public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() { - - List pzList = new ArrayList<>(); - Pizza pz1 = new Pizza(); - pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED); - - Pizza pz2 = new Pizza(); - pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED); - - Pizza pz3 = new Pizza(); - pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED); - - Pizza pz4 = new Pizza(); - pz4.setStatus(Pizza.PizzaStatusEnum.READY); - - pzList.add(pz1); - pzList.add(pz2); - pzList.add(pz3); - pzList.add(pz4); - - EnumMap> map = Pizza.groupPizzaByStatus(pzList); - assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1); - assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2); - assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1); - } - - @Test - public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() { - Pizza pz = new Pizza(); - pz.setStatus(Pizza.PizzaStatusEnum.READY); - pz.deliver(); - assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED); - } - -} 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 deleted file mode 100644 index 2b36786abf..0000000000 --- a/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesTest.java +++ /dev/null @@ -1,17 +0,0 @@ -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/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesUnitTest.java b/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesUnitTest.java new file mode 100644 index 0000000000..161c053cea --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesUnitTest.java @@ -0,0 +1,17 @@ +package org.baeldung.java.rawtypes; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +public class RawTypesUnitTest { + @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/core-java/src/test/resources/META-INF/mime.types b/core-java/src/test/resources/META-INF/mime.types new file mode 100644 index 0000000000..5175242626 --- /dev/null +++ b/core-java/src/test/resources/META-INF/mime.types @@ -0,0 +1,1588 @@ +# This file maps Internet media types to unique file extension(s). +# Although created for httpd, this file is used by many software systems +# and has been placed in the public domain for unlimited redisribution. +# +# The table below contains both registered and (common) unregistered types. +# A type that has no unique extension can be ignored -- they are listed +# here to guide configurations toward known types and to make it easier to +# identify "new" types. File extensions are also commonly used to indicate +# content languages and encodings, so choose them carefully. +# +# Internet media types should be registered as described in RFC 4288. +# The registry is at . +# +# MIME type (lowercased) Extensions +# ============================================ ========== +# application/1d-interleaved-parityfec +# application/3gpp-ims+xml +# application/activemessage +application/andrew-inset ez +# application/applefile +application/applixware aw +application/atom+xml atom +application/atomcat+xml atomcat +# application/atomicmail +application/atomsvc+xml atomsvc +# application/auth-policy+xml +# application/batch-smtp +# application/beep+xml +# application/calendar+xml +# application/cals-1840 +# application/ccmp+xml +application/ccxml+xml ccxml +application/cdmi-capability cdmia +application/cdmi-container cdmic +application/cdmi-domain cdmid +application/cdmi-object cdmio +application/cdmi-queue cdmiq +# application/cea-2018+xml +# application/cellml+xml +# application/cfw +# application/cnrp+xml +# application/commonground +# application/conference-info+xml +# application/cpl+xml +# application/csta+xml +# application/cstadata+xml +application/cu-seeme cu +# application/cybercash +application/davmount+xml davmount +# application/dca-rft +# application/dec-dx +# application/dialog-info+xml +# application/dicom +# application/dns +application/docbook+xml dbk +# application/dskpp+xml +application/dssc+der dssc +application/dssc+xml xdssc +# application/dvcs +application/ecmascript ecma +# application/edi-consent +# application/edi-x12 +# application/edifact +application/emma+xml emma +# application/epp+xml +application/epub+zip epub +# application/eshop +# application/example +application/exi exi +# application/fastinfoset +# application/fastsoap +# application/fits +application/font-tdpfr pfr +# application/framework-attributes+xml +application/gml+xml gml +application/gpx+xml gpx +application/gxf gxf +# application/h224 +# application/held+xml +# application/http +application/hyperstudio stk +# application/ibe-key-request+xml +# application/ibe-pkg-reply+xml +# application/ibe-pp-data +# application/iges +# application/im-iscomposing+xml +# application/index +# application/index.cmd +# application/index.obj +# application/index.response +# application/index.vnd +application/inkml+xml ink inkml +# application/iotp +application/ipfix ipfix +# application/ipp +# application/isup +application/java-archive jar +application/java-serialized-object ser +application/java-vm class +application/javascript js +application/json json +application/jsonml+json jsonml +# application/kpml-request+xml +# application/kpml-response+xml +application/lost+xml lostxml +application/mac-binhex40 hqx +application/mac-compactpro cpt +# application/macwriteii +application/mads+xml mads +application/marc mrc +application/marcxml+xml mrcx +application/mathematica ma nb mb +# application/mathml-content+xml +# application/mathml-presentation+xml +application/mathml+xml mathml +# application/mbms-associated-procedure-description+xml +# application/mbms-deregister+xml +# application/mbms-envelope+xml +# application/mbms-msk+xml +# application/mbms-msk-response+xml +# application/mbms-protection-description+xml +# application/mbms-reception-report+xml +# application/mbms-register+xml +# application/mbms-register-response+xml +# application/mbms-user-service-description+xml +application/mbox mbox +# application/media_control+xml +application/mediaservercontrol+xml mscml +application/metalink+xml metalink +application/metalink4+xml meta4 +application/mets+xml mets +# application/mikey +application/mods+xml mods +# application/moss-keys +# application/moss-signature +# application/mosskey-data +# application/mosskey-request +application/mp21 m21 mp21 +application/mp4 mp4s +# application/mpeg4-generic +# application/mpeg4-iod +# application/mpeg4-iod-xmt +# application/msc-ivr+xml +# application/msc-mixer+xml +application/msword doc dot +application/mxf mxf +# application/nasdata +# application/news-checkgroups +# application/news-groupinfo +# application/news-transmission +# application/nss +# application/ocsp-request +# application/ocsp-response +application/octet-stream bin dms lrf mar so dist distz pkg bpk dump elc deploy +application/oda oda +application/oebps-package+xml opf +application/ogg ogx +application/omdoc+xml omdoc +application/onenote onetoc onetoc2 onetmp onepkg +application/oxps oxps +# application/parityfec +application/patch-ops-error+xml xer +application/pdf pdf +application/pgp-encrypted pgp +# application/pgp-keys +application/pgp-signature asc sig +application/pics-rules prf +# application/pidf+xml +# application/pidf-diff+xml +application/pkcs10 p10 +application/pkcs7-mime p7m p7c +application/pkcs7-signature p7s +application/pkcs8 p8 +application/pkix-attr-cert ac +application/pkix-cert cer +application/pkix-crl crl +application/pkix-pkipath pkipath +application/pkixcmp pki +application/pls+xml pls +# application/poc-settings+xml +application/postscript ai eps ps +# application/prs.alvestrand.titrax-sheet +application/prs.cww cww +# application/prs.nprend +# application/prs.plucker +# application/prs.rdf-xml-crypt +# application/prs.xsf+xml +application/pskc+xml pskcxml +# application/qsig +application/rdf+xml rdf +application/reginfo+xml rif +application/relax-ng-compact-syntax rnc +# application/remote-printing +application/resource-lists+xml rl +application/resource-lists-diff+xml rld +# application/riscos +# application/rlmi+xml +application/rls-services+xml rs +application/rpki-ghostbusters gbr +application/rpki-manifest mft +application/rpki-roa roa +# application/rpki-updown +application/rsd+xml rsd +application/rss+xml rss +application/rtf rtf +# application/rtx +# application/samlassertion+xml +# application/samlmetadata+xml +application/sbml+xml sbml +application/scvp-cv-request scq +application/scvp-cv-response scs +application/scvp-vp-request spq +application/scvp-vp-response spp +application/sdp sdp +# application/set-payment +application/set-payment-initiation setpay +# application/set-registration +application/set-registration-initiation setreg +# application/sgml +# application/sgml-open-catalog +application/shf+xml shf +# application/sieve +# application/simple-filter+xml +# application/simple-message-summary +# application/simplesymbolcontainer +# application/slate +# application/smil +application/smil+xml smi smil +# application/soap+fastinfoset +# application/soap+xml +application/sparql-query rq +application/sparql-results+xml srx +# application/spirits-event+xml +application/srgs gram +application/srgs+xml grxml +application/sru+xml sru +application/ssdl+xml ssdl +application/ssml+xml ssml +# application/tamp-apex-update +# application/tamp-apex-update-confirm +# application/tamp-community-update +# application/tamp-community-update-confirm +# application/tamp-error +# application/tamp-sequence-adjust +# application/tamp-sequence-adjust-confirm +# application/tamp-status-query +# application/tamp-status-response +# application/tamp-update +# application/tamp-update-confirm +application/tei+xml tei teicorpus +application/thraud+xml tfi +# application/timestamp-query +# application/timestamp-reply +application/timestamped-data tsd +# application/tve-trigger +# application/ulpfec +# application/vcard+xml +# application/vemmi +# application/vividence.scriptfile +# application/vnd.3gpp.bsf+xml +application/vnd.3gpp.pic-bw-large plb +application/vnd.3gpp.pic-bw-small psb +application/vnd.3gpp.pic-bw-var pvb +# application/vnd.3gpp.sms +# application/vnd.3gpp2.bcmcsinfo+xml +# application/vnd.3gpp2.sms +application/vnd.3gpp2.tcap tcap +application/vnd.3m.post-it-notes pwn +application/vnd.accpac.simply.aso aso +application/vnd.accpac.simply.imp imp +application/vnd.acucobol acu +application/vnd.acucorp atc acutc +application/vnd.adobe.air-application-installer-package+zip air +application/vnd.adobe.formscentral.fcdt fcdt +application/vnd.adobe.fxp fxp fxpl +# application/vnd.adobe.partial-upload +application/vnd.adobe.xdp+xml xdp +application/vnd.adobe.xfdf xfdf +# application/vnd.aether.imp +# application/vnd.ah-barcode +application/vnd.ahead.space ahead +application/vnd.airzip.filesecure.azf azf +application/vnd.airzip.filesecure.azs azs +application/vnd.amazon.ebook azw +application/vnd.americandynamics.acc acc +application/vnd.amiga.ami ami +# application/vnd.amundsen.maze+xml +application/vnd.android.package-archive apk +application/vnd.anser-web-certificate-issue-initiation cii +application/vnd.anser-web-funds-transfer-initiation fti +application/vnd.antix.game-component atx +application/vnd.apple.installer+xml mpkg +application/vnd.apple.mpegurl m3u8 +# application/vnd.arastra.swi +application/vnd.aristanetworks.swi swi +application/vnd.astraea-software.iota iota +application/vnd.audiograph aep +# application/vnd.autopackage +# application/vnd.avistar+xml +application/vnd.blueice.multipass mpm +# application/vnd.bluetooth.ep.oob +application/vnd.bmi bmi +application/vnd.businessobjects rep +# application/vnd.cab-jscript +# application/vnd.canon-cpdl +# application/vnd.canon-lips +# application/vnd.cendio.thinlinc.clientconf +application/vnd.chemdraw+xml cdxml +application/vnd.chipnuts.karaoke-mmd mmd +application/vnd.cinderella cdy +# application/vnd.cirpack.isdn-ext +application/vnd.claymore cla +application/vnd.cloanto.rp9 rp9 +application/vnd.clonk.c4group c4g c4d c4f c4p c4u +application/vnd.cluetrust.cartomobile-config c11amc +application/vnd.cluetrust.cartomobile-config-pkg c11amz +# application/vnd.collection+json +# application/vnd.commerce-battelle +application/vnd.commonspace csp +application/vnd.contact.cmsg cdbcmsg +application/vnd.cosmocaller cmc +application/vnd.crick.clicker clkx +application/vnd.crick.clicker.keyboard clkk +application/vnd.crick.clicker.palette clkp +application/vnd.crick.clicker.template clkt +application/vnd.crick.clicker.wordbank clkw +application/vnd.criticaltools.wbs+xml wbs +application/vnd.ctc-posml pml +# application/vnd.ctct.ws+xml +# application/vnd.cups-pdf +# application/vnd.cups-postscript +application/vnd.cups-ppd ppd +# application/vnd.cups-raster +# application/vnd.cups-raw +# application/vnd.curl +application/vnd.curl.car car +application/vnd.curl.pcurl pcurl +# application/vnd.cybank +application/vnd.dart dart +application/vnd.data-vision.rdz rdz +application/vnd.dece.data uvf uvvf uvd uvvd +application/vnd.dece.ttml+xml uvt uvvt +application/vnd.dece.unspecified uvx uvvx +application/vnd.dece.zip uvz uvvz +application/vnd.denovo.fcselayout-link fe_launch +# application/vnd.dir-bi.plate-dl-nosuffix +application/vnd.dna dna +application/vnd.dolby.mlp mlp +# application/vnd.dolby.mobile.1 +# application/vnd.dolby.mobile.2 +application/vnd.dpgraph dpg +application/vnd.dreamfactory dfac +application/vnd.ds-keypoint kpxx +application/vnd.dvb.ait ait +# application/vnd.dvb.dvbj +# application/vnd.dvb.esgcontainer +# application/vnd.dvb.ipdcdftnotifaccess +# application/vnd.dvb.ipdcesgaccess +# application/vnd.dvb.ipdcesgaccess2 +# application/vnd.dvb.ipdcesgpdd +# application/vnd.dvb.ipdcroaming +# application/vnd.dvb.iptv.alfec-base +# application/vnd.dvb.iptv.alfec-enhancement +# application/vnd.dvb.notif-aggregate-root+xml +# application/vnd.dvb.notif-container+xml +# application/vnd.dvb.notif-generic+xml +# application/vnd.dvb.notif-ia-msglist+xml +# application/vnd.dvb.notif-ia-registration-request+xml +# application/vnd.dvb.notif-ia-registration-response+xml +# application/vnd.dvb.notif-init+xml +# application/vnd.dvb.pfr +application/vnd.dvb.service svc +# application/vnd.dxr +application/vnd.dynageo geo +# application/vnd.easykaraoke.cdgdownload +# application/vnd.ecdis-update +application/vnd.ecowin.chart mag +# application/vnd.ecowin.filerequest +# application/vnd.ecowin.fileupdate +# application/vnd.ecowin.series +# application/vnd.ecowin.seriesrequest +# application/vnd.ecowin.seriesupdate +# application/vnd.emclient.accessrequest+xml +application/vnd.enliven nml +# application/vnd.eprints.data+xml +application/vnd.epson.esf esf +application/vnd.epson.msf msf +application/vnd.epson.quickanime qam +application/vnd.epson.salt slt +application/vnd.epson.ssf ssf +# application/vnd.ericsson.quickcall +application/vnd.eszigno3+xml es3 et3 +# application/vnd.etsi.aoc+xml +# application/vnd.etsi.cug+xml +# application/vnd.etsi.iptvcommand+xml +# application/vnd.etsi.iptvdiscovery+xml +# application/vnd.etsi.iptvprofile+xml +# application/vnd.etsi.iptvsad-bc+xml +# application/vnd.etsi.iptvsad-cod+xml +# application/vnd.etsi.iptvsad-npvr+xml +# application/vnd.etsi.iptvservice+xml +# application/vnd.etsi.iptvsync+xml +# application/vnd.etsi.iptvueprofile+xml +# application/vnd.etsi.mcid+xml +# application/vnd.etsi.overload-control-policy-dataset+xml +# application/vnd.etsi.sci+xml +# application/vnd.etsi.simservs+xml +# application/vnd.etsi.tsl+xml +# application/vnd.etsi.tsl.der +# application/vnd.eudora.data +application/vnd.ezpix-album ez2 +application/vnd.ezpix-package ez3 +# application/vnd.f-secure.mobile +application/vnd.fdf fdf +application/vnd.fdsn.mseed mseed +application/vnd.fdsn.seed seed dataless +# application/vnd.ffsns +# application/vnd.fints +application/vnd.flographit gph +application/vnd.fluxtime.clip ftc +# application/vnd.font-fontforge-sfd +application/vnd.framemaker fm frame maker book +application/vnd.frogans.fnc fnc +application/vnd.frogans.ltf ltf +application/vnd.fsc.weblaunch fsc +application/vnd.fujitsu.oasys oas +application/vnd.fujitsu.oasys2 oa2 +application/vnd.fujitsu.oasys3 oa3 +application/vnd.fujitsu.oasysgp fg5 +application/vnd.fujitsu.oasysprs bh2 +# application/vnd.fujixerox.art-ex +# application/vnd.fujixerox.art4 +# application/vnd.fujixerox.hbpl +application/vnd.fujixerox.ddd ddd +application/vnd.fujixerox.docuworks xdw +application/vnd.fujixerox.docuworks.binder xbd +# application/vnd.fut-misnet +application/vnd.fuzzysheet fzs +application/vnd.genomatix.tuxedo txd +# application/vnd.geocube+xml +application/vnd.geogebra.file ggb +application/vnd.geogebra.tool ggt +application/vnd.geometry-explorer gex gre +application/vnd.geonext gxt +application/vnd.geoplan g2w +application/vnd.geospace g3w +# application/vnd.globalplatform.card-content-mgt +# application/vnd.globalplatform.card-content-mgt-response +application/vnd.gmx gmx +application/vnd.google-earth.kml+xml kml +application/vnd.google-earth.kmz kmz +application/vnd.grafeq gqf gqs +# application/vnd.gridmp +application/vnd.groove-account gac +application/vnd.groove-help ghf +application/vnd.groove-identity-message gim +application/vnd.groove-injector grv +application/vnd.groove-tool-message gtm +application/vnd.groove-tool-template tpl +application/vnd.groove-vcard vcg +# application/vnd.hal+json +application/vnd.hal+xml hal +application/vnd.handheld-entertainment+xml zmm +application/vnd.hbci hbci +# application/vnd.hcl-bireports +application/vnd.hhe.lesson-player les +application/vnd.hp-hpgl hpgl +application/vnd.hp-hpid hpid +application/vnd.hp-hps hps +application/vnd.hp-jlyt jlt +application/vnd.hp-pcl pcl +application/vnd.hp-pclxl pclxl +# application/vnd.httphone +application/vnd.hydrostatix.sof-data sfd-hdstx +# application/vnd.hzn-3d-crossword +# application/vnd.ibm.afplinedata +# application/vnd.ibm.electronic-media +application/vnd.ibm.minipay mpy +application/vnd.ibm.modcap afp listafp list3820 +application/vnd.ibm.rights-management irm +application/vnd.ibm.secure-container sc +application/vnd.iccprofile icc icm +application/vnd.igloader igl +application/vnd.immervision-ivp ivp +application/vnd.immervision-ivu ivu +# application/vnd.informedcontrol.rms+xml +# application/vnd.informix-visionary +# application/vnd.infotech.project +# application/vnd.infotech.project+xml +# application/vnd.innopath.wamp.notification +application/vnd.insors.igm igm +application/vnd.intercon.formnet xpw xpx +application/vnd.intergeo i2g +# application/vnd.intertrust.digibox +# application/vnd.intertrust.nncp +application/vnd.intu.qbo qbo +application/vnd.intu.qfx qfx +# application/vnd.iptc.g2.conceptitem+xml +# application/vnd.iptc.g2.knowledgeitem+xml +# application/vnd.iptc.g2.newsitem+xml +# application/vnd.iptc.g2.newsmessage+xml +# application/vnd.iptc.g2.packageitem+xml +# application/vnd.iptc.g2.planningitem+xml +application/vnd.ipunplugged.rcprofile rcprofile +application/vnd.irepository.package+xml irp +application/vnd.is-xpr xpr +application/vnd.isac.fcs fcs +application/vnd.jam jam +# application/vnd.japannet-directory-service +# application/vnd.japannet-jpnstore-wakeup +# application/vnd.japannet-payment-wakeup +# application/vnd.japannet-registration +# application/vnd.japannet-registration-wakeup +# application/vnd.japannet-setstore-wakeup +# application/vnd.japannet-verification +# application/vnd.japannet-verification-wakeup +application/vnd.jcp.javame.midlet-rms rms +application/vnd.jisp jisp +application/vnd.joost.joda-archive joda +application/vnd.kahootz ktz ktr +application/vnd.kde.karbon karbon +application/vnd.kde.kchart chrt +application/vnd.kde.kformula kfo +application/vnd.kde.kivio flw +application/vnd.kde.kontour kon +application/vnd.kde.kpresenter kpr kpt +application/vnd.kde.kspread ksp +application/vnd.kde.kword kwd kwt +application/vnd.kenameaapp htke +application/vnd.kidspiration kia +application/vnd.kinar kne knp +application/vnd.koan skp skd skt skm +application/vnd.kodak-descriptor sse +application/vnd.las.las+xml lasxml +# application/vnd.liberty-request+xml +application/vnd.llamagraphics.life-balance.desktop lbd +application/vnd.llamagraphics.life-balance.exchange+xml lbe +application/vnd.lotus-1-2-3 123 +application/vnd.lotus-approach apr +application/vnd.lotus-freelance pre +application/vnd.lotus-notes nsf +application/vnd.lotus-organizer org +application/vnd.lotus-screencam scm +application/vnd.lotus-wordpro lwp +application/vnd.macports.portpkg portpkg +# application/vnd.marlin.drm.actiontoken+xml +# application/vnd.marlin.drm.conftoken+xml +# application/vnd.marlin.drm.license+xml +# application/vnd.marlin.drm.mdcf +application/vnd.mcd mcd +application/vnd.medcalcdata mc1 +application/vnd.mediastation.cdkey cdkey +# application/vnd.meridian-slingshot +application/vnd.mfer mwf +application/vnd.mfmp mfm +application/vnd.micrografx.flo flo +application/vnd.micrografx.igx igx +application/vnd.mif mif +# application/vnd.minisoft-hp3000-save +# application/vnd.mitsubishi.misty-guard.trustweb +application/vnd.mobius.daf daf +application/vnd.mobius.dis dis +application/vnd.mobius.mbk mbk +application/vnd.mobius.mqy mqy +application/vnd.mobius.msl msl +application/vnd.mobius.plc plc +application/vnd.mobius.txf txf +application/vnd.mophun.application mpn +application/vnd.mophun.certificate mpc +# application/vnd.motorola.flexsuite +# application/vnd.motorola.flexsuite.adsi +# application/vnd.motorola.flexsuite.fis +# application/vnd.motorola.flexsuite.gotap +# application/vnd.motorola.flexsuite.kmr +# application/vnd.motorola.flexsuite.ttc +# application/vnd.motorola.flexsuite.wem +# application/vnd.motorola.iprm +application/vnd.mozilla.xul+xml xul +application/vnd.ms-artgalry cil +# application/vnd.ms-asf +application/vnd.ms-cab-compressed cab +# application/vnd.ms-color.iccprofile +application/vnd.ms-excel xls xlm xla xlc xlt xlw +application/vnd.ms-excel.addin.macroenabled.12 xlam +application/vnd.ms-excel.sheet.binary.macroenabled.12 xlsb +application/vnd.ms-excel.sheet.macroenabled.12 xlsm +application/vnd.ms-excel.template.macroenabled.12 xltm +application/vnd.ms-fontobject eot +application/vnd.ms-htmlhelp chm +application/vnd.ms-ims ims +application/vnd.ms-lrm lrm +# application/vnd.ms-office.activex+xml +application/vnd.ms-officetheme thmx +# application/vnd.ms-opentype +# application/vnd.ms-package.obfuscated-opentype +application/vnd.ms-pki.seccat cat +application/vnd.ms-pki.stl stl +# application/vnd.ms-playready.initiator+xml +application/vnd.ms-powerpoint ppt pps pot +application/vnd.ms-powerpoint.addin.macroenabled.12 ppam +application/vnd.ms-powerpoint.presentation.macroenabled.12 pptm +application/vnd.ms-powerpoint.slide.macroenabled.12 sldm +application/vnd.ms-powerpoint.slideshow.macroenabled.12 ppsm +application/vnd.ms-powerpoint.template.macroenabled.12 potm +# application/vnd.ms-printing.printticket+xml +application/vnd.ms-project mpp mpt +# application/vnd.ms-tnef +# application/vnd.ms-wmdrm.lic-chlg-req +# application/vnd.ms-wmdrm.lic-resp +# application/vnd.ms-wmdrm.meter-chlg-req +# application/vnd.ms-wmdrm.meter-resp +application/vnd.ms-word.document.macroenabled.12 docm +application/vnd.ms-word.template.macroenabled.12 dotm +application/vnd.ms-works wps wks wcm wdb +application/vnd.ms-wpl wpl +application/vnd.ms-xpsdocument xps +application/vnd.mseq mseq +# application/vnd.msign +# application/vnd.multiad.creator +# application/vnd.multiad.creator.cif +# application/vnd.music-niff +application/vnd.musician mus +application/vnd.muvee.style msty +application/vnd.mynfc taglet +# application/vnd.ncd.control +# application/vnd.ncd.reference +# application/vnd.nervana +# application/vnd.netfpx +application/vnd.neurolanguage.nlu nlu +application/vnd.nitf ntf nitf +application/vnd.noblenet-directory nnd +application/vnd.noblenet-sealer nns +application/vnd.noblenet-web nnw +# application/vnd.nokia.catalogs +# application/vnd.nokia.conml+wbxml +# application/vnd.nokia.conml+xml +# application/vnd.nokia.isds-radio-presets +# application/vnd.nokia.iptv.config+xml +# application/vnd.nokia.landmark+wbxml +# application/vnd.nokia.landmark+xml +# application/vnd.nokia.landmarkcollection+xml +# application/vnd.nokia.n-gage.ac+xml +application/vnd.nokia.n-gage.data ngdat +application/vnd.nokia.n-gage.symbian.install n-gage +# application/vnd.nokia.ncd +# application/vnd.nokia.pcd+wbxml +# application/vnd.nokia.pcd+xml +application/vnd.nokia.radio-preset rpst +application/vnd.nokia.radio-presets rpss +application/vnd.novadigm.edm edm +application/vnd.novadigm.edx edx +application/vnd.novadigm.ext ext +# application/vnd.ntt-local.file-transfer +# application/vnd.ntt-local.sip-ta_remote +# application/vnd.ntt-local.sip-ta_tcp_stream +application/vnd.oasis.opendocument.chart odc +application/vnd.oasis.opendocument.chart-template otc +application/vnd.oasis.opendocument.database odb +application/vnd.oasis.opendocument.formula odf +application/vnd.oasis.opendocument.formula-template odft +application/vnd.oasis.opendocument.graphics odg +application/vnd.oasis.opendocument.graphics-template otg +application/vnd.oasis.opendocument.image odi +application/vnd.oasis.opendocument.image-template oti +application/vnd.oasis.opendocument.presentation odp +application/vnd.oasis.opendocument.presentation-template otp +application/vnd.oasis.opendocument.spreadsheet ods +application/vnd.oasis.opendocument.spreadsheet-template ots +application/vnd.oasis.opendocument.text odt +application/vnd.oasis.opendocument.text-master odm +application/vnd.oasis.opendocument.text-template ott +application/vnd.oasis.opendocument.text-web oth +# application/vnd.obn +# application/vnd.oftn.l10n+json +# application/vnd.oipf.contentaccessdownload+xml +# application/vnd.oipf.contentaccessstreaming+xml +# application/vnd.oipf.cspg-hexbinary +# application/vnd.oipf.dae.svg+xml +# application/vnd.oipf.dae.xhtml+xml +# application/vnd.oipf.mippvcontrolmessage+xml +# application/vnd.oipf.pae.gem +# application/vnd.oipf.spdiscovery+xml +# application/vnd.oipf.spdlist+xml +# application/vnd.oipf.ueprofile+xml +# application/vnd.oipf.userprofile+xml +application/vnd.olpc-sugar xo +# application/vnd.oma-scws-config +# application/vnd.oma-scws-http-request +# application/vnd.oma-scws-http-response +# application/vnd.oma.bcast.associated-procedure-parameter+xml +# application/vnd.oma.bcast.drm-trigger+xml +# application/vnd.oma.bcast.imd+xml +# application/vnd.oma.bcast.ltkm +# application/vnd.oma.bcast.notification+xml +# application/vnd.oma.bcast.provisioningtrigger +# application/vnd.oma.bcast.sgboot +# application/vnd.oma.bcast.sgdd+xml +# application/vnd.oma.bcast.sgdu +# application/vnd.oma.bcast.simple-symbol-container +# application/vnd.oma.bcast.smartcard-trigger+xml +# application/vnd.oma.bcast.sprov+xml +# application/vnd.oma.bcast.stkm +# application/vnd.oma.cab-address-book+xml +# application/vnd.oma.cab-feature-handler+xml +# application/vnd.oma.cab-pcc+xml +# application/vnd.oma.cab-user-prefs+xml +# application/vnd.oma.dcd +# application/vnd.oma.dcdc +application/vnd.oma.dd2+xml dd2 +# application/vnd.oma.drm.risd+xml +# application/vnd.oma.group-usage-list+xml +# application/vnd.oma.pal+xml +# application/vnd.oma.poc.detailed-progress-report+xml +# application/vnd.oma.poc.final-report+xml +# application/vnd.oma.poc.groups+xml +# application/vnd.oma.poc.invocation-descriptor+xml +# application/vnd.oma.poc.optimized-progress-report+xml +# application/vnd.oma.push +# application/vnd.oma.scidm.messages+xml +# application/vnd.oma.xcap-directory+xml +# application/vnd.omads-email+xml +# application/vnd.omads-file+xml +# application/vnd.omads-folder+xml +# application/vnd.omaloc-supl-init +application/vnd.openofficeorg.extension oxt +# application/vnd.openxmlformats-officedocument.custom-properties+xml +# application/vnd.openxmlformats-officedocument.customxmlproperties+xml +# application/vnd.openxmlformats-officedocument.drawing+xml +# application/vnd.openxmlformats-officedocument.drawingml.chart+xml +# application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml +# application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml +# application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml +# application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml +# application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml +# application/vnd.openxmlformats-officedocument.extended-properties+xml +# application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml +# application/vnd.openxmlformats-officedocument.presentationml.comments+xml +# application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml +# application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml +# application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml +application/vnd.openxmlformats-officedocument.presentationml.presentation pptx +# application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml +# application/vnd.openxmlformats-officedocument.presentationml.presprops+xml +application/vnd.openxmlformats-officedocument.presentationml.slide sldx +# application/vnd.openxmlformats-officedocument.presentationml.slide+xml +# application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml +# application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml +application/vnd.openxmlformats-officedocument.presentationml.slideshow ppsx +# application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml +# application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml +# application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml +# application/vnd.openxmlformats-officedocument.presentationml.tags+xml +application/vnd.openxmlformats-officedocument.presentationml.template potx +# application/vnd.openxmlformats-officedocument.presentationml.template.main+xml +# application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml +application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx +# application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml +application/vnd.openxmlformats-officedocument.spreadsheetml.template xltx +# application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml +# application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml +# application/vnd.openxmlformats-officedocument.theme+xml +# application/vnd.openxmlformats-officedocument.themeoverride+xml +# application/vnd.openxmlformats-officedocument.vmldrawing +# application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml +application/vnd.openxmlformats-officedocument.wordprocessingml.document docx +# application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml +application/vnd.openxmlformats-officedocument.wordprocessingml.template dotx +# application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml +# application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml +# application/vnd.openxmlformats-package.core-properties+xml +# application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml +# application/vnd.openxmlformats-package.relationships+xml +# application/vnd.quobject-quoxdocument +# application/vnd.osa.netdeploy +application/vnd.osgeo.mapguide.package mgp +# application/vnd.osgi.bundle +application/vnd.osgi.dp dp +application/vnd.osgi.subsystem esa +# application/vnd.otps.ct-kip+xml +application/vnd.palm pdb pqa oprc +# application/vnd.paos.xml +application/vnd.pawaafile paw +application/vnd.pg.format str +application/vnd.pg.osasli ei6 +# application/vnd.piaccess.application-licence +application/vnd.picsel efif +application/vnd.pmi.widget wg +# application/vnd.poc.group-advertisement+xml +application/vnd.pocketlearn plf +application/vnd.powerbuilder6 pbd +# application/vnd.powerbuilder6-s +# application/vnd.powerbuilder7 +# application/vnd.powerbuilder7-s +# application/vnd.powerbuilder75 +# application/vnd.powerbuilder75-s +# application/vnd.preminet +application/vnd.previewsystems.box box +application/vnd.proteus.magazine mgz +application/vnd.publishare-delta-tree qps +application/vnd.pvi.ptid1 ptid +# application/vnd.pwg-multiplexed +# application/vnd.pwg-xhtml-print+xml +# application/vnd.qualcomm.brew-app-res +application/vnd.quark.quarkxpress qxd qxt qwd qwt qxl qxb +# application/vnd.radisys.moml+xml +# application/vnd.radisys.msml+xml +# application/vnd.radisys.msml-audit+xml +# application/vnd.radisys.msml-audit-conf+xml +# application/vnd.radisys.msml-audit-conn+xml +# application/vnd.radisys.msml-audit-dialog+xml +# application/vnd.radisys.msml-audit-stream+xml +# application/vnd.radisys.msml-conf+xml +# application/vnd.radisys.msml-dialog+xml +# application/vnd.radisys.msml-dialog-base+xml +# application/vnd.radisys.msml-dialog-fax-detect+xml +# application/vnd.radisys.msml-dialog-fax-sendrecv+xml +# application/vnd.radisys.msml-dialog-group+xml +# application/vnd.radisys.msml-dialog-speech+xml +# application/vnd.radisys.msml-dialog-transform+xml +# application/vnd.rainstor.data +# application/vnd.rapid +application/vnd.realvnc.bed bed +application/vnd.recordare.musicxml mxl +application/vnd.recordare.musicxml+xml musicxml +# application/vnd.renlearn.rlprint +application/vnd.rig.cryptonote cryptonote +application/vnd.rim.cod cod +application/vnd.rn-realmedia rm +application/vnd.rn-realmedia-vbr rmvb +application/vnd.route66.link66+xml link66 +# application/vnd.rs-274x +# application/vnd.ruckus.download +# application/vnd.s3sms +application/vnd.sailingtracker.track st +# application/vnd.sbm.cid +# application/vnd.sbm.mid2 +# application/vnd.scribus +# application/vnd.sealed.3df +# application/vnd.sealed.csf +# application/vnd.sealed.doc +# application/vnd.sealed.eml +# application/vnd.sealed.mht +# application/vnd.sealed.net +# application/vnd.sealed.ppt +# application/vnd.sealed.tiff +# application/vnd.sealed.xls +# application/vnd.sealedmedia.softseal.html +# application/vnd.sealedmedia.softseal.pdf +application/vnd.seemail see +application/vnd.sema sema +application/vnd.semd semd +application/vnd.semf semf +application/vnd.shana.informed.formdata ifm +application/vnd.shana.informed.formtemplate itp +application/vnd.shana.informed.interchange iif +application/vnd.shana.informed.package ipk +application/vnd.simtech-mindmapper twd twds +application/vnd.smaf mmf +# application/vnd.smart.notebook +application/vnd.smart.teacher teacher +# application/vnd.software602.filler.form+xml +# application/vnd.software602.filler.form-xml-zip +application/vnd.solent.sdkm+xml sdkm sdkd +application/vnd.spotfire.dxp dxp +application/vnd.spotfire.sfs sfs +# application/vnd.sss-cod +# application/vnd.sss-dtf +# application/vnd.sss-ntf +application/vnd.stardivision.calc sdc +application/vnd.stardivision.draw sda +application/vnd.stardivision.impress sdd +application/vnd.stardivision.math smf +application/vnd.stardivision.writer sdw vor +application/vnd.stardivision.writer-global sgl +application/vnd.stepmania.package smzip +application/vnd.stepmania.stepchart sm +# application/vnd.street-stream +application/vnd.sun.xml.calc sxc +application/vnd.sun.xml.calc.template stc +application/vnd.sun.xml.draw sxd +application/vnd.sun.xml.draw.template std +application/vnd.sun.xml.impress sxi +application/vnd.sun.xml.impress.template sti +application/vnd.sun.xml.math sxm +application/vnd.sun.xml.writer sxw +application/vnd.sun.xml.writer.global sxg +application/vnd.sun.xml.writer.template stw +# application/vnd.sun.wadl+xml +application/vnd.sus-calendar sus susp +application/vnd.svd svd +# application/vnd.swiftview-ics +application/vnd.symbian.install sis sisx +application/vnd.syncml+xml xsm +application/vnd.syncml.dm+wbxml bdm +application/vnd.syncml.dm+xml xdm +# application/vnd.syncml.dm.notification +# application/vnd.syncml.ds.notification +application/vnd.tao.intent-module-archive tao +application/vnd.tcpdump.pcap pcap cap dmp +application/vnd.tmobile-livetv tmo +application/vnd.trid.tpt tpt +application/vnd.triscape.mxs mxs +application/vnd.trueapp tra +# application/vnd.truedoc +# application/vnd.ubisoft.webplayer +application/vnd.ufdl ufd ufdl +application/vnd.uiq.theme utz +application/vnd.umajin umj +application/vnd.unity unityweb +application/vnd.uoml+xml uoml +# application/vnd.uplanet.alert +# application/vnd.uplanet.alert-wbxml +# application/vnd.uplanet.bearer-choice +# application/vnd.uplanet.bearer-choice-wbxml +# application/vnd.uplanet.cacheop +# application/vnd.uplanet.cacheop-wbxml +# application/vnd.uplanet.channel +# application/vnd.uplanet.channel-wbxml +# application/vnd.uplanet.list +# application/vnd.uplanet.list-wbxml +# application/vnd.uplanet.listcmd +# application/vnd.uplanet.listcmd-wbxml +# application/vnd.uplanet.signal +application/vnd.vcx vcx +# application/vnd.vd-study +# application/vnd.vectorworks +# application/vnd.verimatrix.vcas +# application/vnd.vidsoft.vidconference +application/vnd.visio vsd vst vss vsw +application/vnd.visionary vis +# application/vnd.vividence.scriptfile +application/vnd.vsf vsf +# application/vnd.wap.sic +# application/vnd.wap.slc +application/vnd.wap.wbxml wbxml +application/vnd.wap.wmlc wmlc +application/vnd.wap.wmlscriptc wmlsc +application/vnd.webturbo wtb +# application/vnd.wfa.wsc +# application/vnd.wmc +# application/vnd.wmf.bootstrap +# application/vnd.wolfram.mathematica +# application/vnd.wolfram.mathematica.package +application/vnd.wolfram.player nbp +application/vnd.wordperfect wpd +application/vnd.wqd wqd +# application/vnd.wrq-hp3000-labelled +application/vnd.wt.stf stf +# application/vnd.wv.csp+wbxml +# application/vnd.wv.csp+xml +# application/vnd.wv.ssp+xml +application/vnd.xara xar +application/vnd.xfdl xfdl +# application/vnd.xfdl.webform +# application/vnd.xmi+xml +# application/vnd.xmpie.cpkg +# application/vnd.xmpie.dpkg +# application/vnd.xmpie.plan +# application/vnd.xmpie.ppkg +# application/vnd.xmpie.xlim +application/vnd.yamaha.hv-dic hvd +application/vnd.yamaha.hv-script hvs +application/vnd.yamaha.hv-voice hvp +application/vnd.yamaha.openscoreformat osf +application/vnd.yamaha.openscoreformat.osfpvg+xml osfpvg +# application/vnd.yamaha.remote-setup +application/vnd.yamaha.smaf-audio saf +application/vnd.yamaha.smaf-phrase spf +# application/vnd.yamaha.through-ngn +# application/vnd.yamaha.tunnel-udpencap +application/vnd.yellowriver-custom-menu cmp +application/vnd.zul zir zirz +application/vnd.zzazz.deck+xml zaz +application/voicexml+xml vxml +# application/vq-rtcpxr +# application/watcherinfo+xml +# application/whoispp-query +# application/whoispp-response +application/widget wgt +application/winhlp hlp +# application/wita +# application/wordperfect5.1 +application/wsdl+xml wsdl +application/wspolicy+xml wspolicy +application/x-7z-compressed 7z +application/x-abiword abw +application/x-ace-compressed ace +# application/x-amf +application/x-apple-diskimage dmg +application/x-authorware-bin aab x32 u32 vox +application/x-authorware-map aam +application/x-authorware-seg aas +application/x-bcpio bcpio +application/x-bittorrent torrent +application/x-blorb blb blorb +application/x-bzip bz +application/x-bzip2 bz2 boz +application/x-cbr cbr cba cbt cbz cb7 +application/x-cdlink vcd +application/x-cfs-compressed cfs +application/x-chat chat +application/x-chess-pgn pgn +application/x-conference nsc +# application/x-compress +application/x-cpio cpio +application/x-csh csh +application/x-debian-package deb udeb +application/x-dgc-compressed dgc +application/x-director dir dcr dxr cst cct cxt w3d fgd swa +application/x-doom wad +application/x-dtbncx+xml ncx +application/x-dtbook+xml dtb +application/x-dtbresource+xml res +application/x-dvi dvi +application/x-envoy evy +application/x-eva eva +application/x-font-bdf bdf +# application/x-font-dos +# application/x-font-framemaker +application/x-font-ghostscript gsf +# application/x-font-libgrx +application/x-font-linux-psf psf +application/x-font-otf otf +application/x-font-pcf pcf +application/x-font-snf snf +# application/x-font-speedo +# application/x-font-sunos-news +application/x-font-ttf ttf ttc +application/x-font-type1 pfa pfb pfm afm +application/x-font-woff woff +# application/x-font-vfont +application/x-freearc arc +application/x-futuresplash spl +application/x-gca-compressed gca +application/x-glulx ulx +application/x-gnumeric gnumeric +application/x-gramps-xml gramps +application/x-gtar gtar +# application/x-gzip +application/x-hdf hdf +application/x-install-instructions install +application/x-iso9660-image iso +application/x-java-jnlp-file jnlp +application/x-latex latex +application/x-lzh-compressed lzh lha +application/x-mie mie +application/x-mobipocket-ebook prc mobi +application/x-ms-application application +application/x-ms-shortcut lnk +application/x-ms-wmd wmd +application/x-ms-wmz wmz +application/x-ms-xbap xbap +application/x-msaccess mdb +application/x-msbinder obd +application/x-mscardfile crd +application/x-msclip clp +application/x-msdownload exe dll com bat msi +application/x-msmediaview mvb m13 m14 +application/x-msmetafile wmf wmz emf emz +application/x-msmoney mny +application/x-mspublisher pub +application/x-msschedule scd +application/x-msterminal trm +application/x-mswrite wri +application/x-netcdf nc cdf +application/x-nzb nzb +application/x-pkcs12 p12 pfx +application/x-pkcs7-certificates p7b spc +application/x-pkcs7-certreqresp p7r +application/x-rar-compressed rar +application/x-research-info-systems ris +application/x-sh sh +application/x-shar shar +application/x-shockwave-flash swf +application/x-silverlight-app xap +application/x-sql sql +application/x-stuffit sit +application/x-stuffitx sitx +application/x-subrip srt +application/x-sv4cpio sv4cpio +application/x-sv4crc sv4crc +application/x-t3vm-image t3 +application/x-tads gam +application/x-tar tar +application/x-tcl tcl +application/x-tex tex +application/x-tex-tfm tfm +application/x-texinfo texinfo texi +application/x-tgif obj +application/x-ustar ustar +application/x-wais-source src +application/x-x509-ca-cert der crt +application/x-xfig fig +application/x-xliff+xml xlf +application/x-xpinstall xpi +application/x-xz xz +application/x-zmachine z1 z2 z3 z4 z5 z6 z7 z8 +# application/x400-bp +application/xaml+xml xaml +# application/xcap-att+xml +# application/xcap-caps+xml +application/xcap-diff+xml xdf +# application/xcap-el+xml +# application/xcap-error+xml +# application/xcap-ns+xml +# application/xcon-conference-info-diff+xml +# application/xcon-conference-info+xml +application/xenc+xml xenc +application/xhtml+xml xhtml xht +# application/xhtml-voice+xml +application/xml xml xsl +application/xml-dtd dtd +# application/xml-external-parsed-entity +# application/xmpp+xml +application/xop+xml xop +application/xproc+xml xpl +application/xslt+xml xslt +application/xspf+xml xspf +application/xv+xml mxml xhvml xvml xvm +application/yang yang +application/yin+xml yin +application/zip zip +# audio/1d-interleaved-parityfec +# audio/32kadpcm +# audio/3gpp +# audio/3gpp2 +# audio/ac3 +audio/adpcm adp +# audio/amr +# audio/amr-wb +# audio/amr-wb+ +# audio/asc +# audio/atrac-advanced-lossless +# audio/atrac-x +# audio/atrac3 +audio/basic au snd +# audio/bv16 +# audio/bv32 +# audio/clearmode +# audio/cn +# audio/dat12 +# audio/dls +# audio/dsr-es201108 +# audio/dsr-es202050 +# audio/dsr-es202211 +# audio/dsr-es202212 +# audio/dv +# audio/dvi4 +# audio/eac3 +# audio/evrc +# audio/evrc-qcp +# audio/evrc0 +# audio/evrc1 +# audio/evrcb +# audio/evrcb0 +# audio/evrcb1 +# audio/evrcwb +# audio/evrcwb0 +# audio/evrcwb1 +# audio/example +# audio/fwdred +# audio/g719 +# audio/g722 +# audio/g7221 +# audio/g723 +# audio/g726-16 +# audio/g726-24 +# audio/g726-32 +# audio/g726-40 +# audio/g728 +# audio/g729 +# audio/g7291 +# audio/g729d +# audio/g729e +# audio/gsm +# audio/gsm-efr +# audio/gsm-hr-08 +# audio/ilbc +# audio/ip-mr_v2.5 +# audio/isac +# audio/l16 +# audio/l20 +# audio/l24 +# audio/l8 +# audio/lpc +audio/midi mid midi kar rmi +# audio/mobile-xmf +audio/mp4 m4a mp4a +# audio/mp4a-latm +# audio/mpa +# audio/mpa-robust +audio/mpeg mpga mp2 mp2a mp3 m2a m3a +# audio/mpeg4-generic +# audio/musepack +audio/ogg oga ogg spx +# audio/opus +# audio/parityfec +# audio/pcma +# audio/pcma-wb +# audio/pcmu-wb +# audio/pcmu +# audio/prs.sid +# audio/qcelp +# audio/red +# audio/rtp-enc-aescm128 +# audio/rtp-midi +# audio/rtx +audio/s3m s3m +audio/silk sil +# audio/smv +# audio/smv0 +# audio/smv-qcp +# audio/sp-midi +# audio/speex +# audio/t140c +# audio/t38 +# audio/telephone-event +# audio/tone +# audio/uemclip +# audio/ulpfec +# audio/vdvi +# audio/vmr-wb +# audio/vnd.3gpp.iufp +# audio/vnd.4sb +# audio/vnd.audiokoz +# audio/vnd.celp +# audio/vnd.cisco.nse +# audio/vnd.cmles.radio-events +# audio/vnd.cns.anp1 +# audio/vnd.cns.inf1 +audio/vnd.dece.audio uva uvva +audio/vnd.digital-winds eol +# audio/vnd.dlna.adts +# audio/vnd.dolby.heaac.1 +# audio/vnd.dolby.heaac.2 +# audio/vnd.dolby.mlp +# audio/vnd.dolby.mps +# audio/vnd.dolby.pl2 +# audio/vnd.dolby.pl2x +# audio/vnd.dolby.pl2z +# audio/vnd.dolby.pulse.1 +audio/vnd.dra dra +audio/vnd.dts dts +audio/vnd.dts.hd dtshd +# audio/vnd.dvb.file +# audio/vnd.everad.plj +# audio/vnd.hns.audio +audio/vnd.lucent.voice lvp +audio/vnd.ms-playready.media.pya pya +# audio/vnd.nokia.mobile-xmf +# audio/vnd.nortel.vbk +audio/vnd.nuera.ecelp4800 ecelp4800 +audio/vnd.nuera.ecelp7470 ecelp7470 +audio/vnd.nuera.ecelp9600 ecelp9600 +# audio/vnd.octel.sbc +# audio/vnd.qcelp +# audio/vnd.rhetorex.32kadpcm +audio/vnd.rip rip +# audio/vnd.sealedmedia.softseal.mpeg +# audio/vnd.vmx.cvsd +# audio/vorbis +# audio/vorbis-config +audio/webm weba +audio/x-aac aac +audio/x-aiff aif aiff aifc +audio/x-caf caf +audio/x-flac flac +audio/x-matroska mka +audio/x-mpegurl m3u +audio/x-ms-wax wax +audio/x-ms-wma wma +audio/x-pn-realaudio ram ra +audio/x-pn-realaudio-plugin rmp +# audio/x-tta +audio/x-wav wav +audio/xm xm +chemical/x-cdx cdx +chemical/x-cif cif +chemical/x-cmdf cmdf +chemical/x-cml cml +chemical/x-csml csml +# chemical/x-pdb +chemical/x-xyz xyz +image/bmp bmp +image/cgm cgm +# image/example +# image/fits +image/g3fax g3 +image/gif gif +image/ief ief +# image/jp2 +image/jpeg jpeg jpg jpe +# image/jpm +# image/jpx +image/ktx ktx +# image/naplps +image/png png +image/prs.btif btif +# image/prs.pti +image/sgi sgi +image/svg+xml svg svgz +# image/t38 +image/tiff tiff tif +# image/tiff-fx +image/vnd.adobe.photoshop psd +# image/vnd.cns.inf2 +image/vnd.dece.graphic uvi uvvi uvg uvvg +image/vnd.dvb.subtitle sub +image/vnd.djvu djvu djv +image/vnd.dwg dwg +image/vnd.dxf dxf +image/vnd.fastbidsheet fbs +image/vnd.fpx fpx +image/vnd.fst fst +image/vnd.fujixerox.edmics-mmr mmr +image/vnd.fujixerox.edmics-rlc rlc +# image/vnd.globalgraphics.pgb +# image/vnd.microsoft.icon +# image/vnd.mix +image/vnd.ms-modi mdi +image/vnd.ms-photo wdp +image/vnd.net-fpx npx +# image/vnd.radiance +# image/vnd.sealed.png +# image/vnd.sealedmedia.softseal.gif +# image/vnd.sealedmedia.softseal.jpg +# image/vnd.svf +image/vnd.wap.wbmp wbmp +image/vnd.xiff xif +image/webp webp +image/x-3ds 3ds +image/x-cmu-raster ras +image/x-cmx cmx +image/x-freehand fh fhc fh4 fh5 fh7 +image/x-icon ico +image/x-mrsid-image sid +image/x-pcx pcx +image/x-pict pic pct +image/x-portable-anymap pnm +image/x-portable-bitmap pbm +image/x-portable-graymap pgm +image/x-portable-pixmap ppm +image/x-rgb rgb +image/x-tga tga +image/x-xbitmap xbm +image/x-xpixmap xpm +image/x-xwindowdump xwd +# message/cpim +# message/delivery-status +# message/disposition-notification +# message/example +# message/external-body +# message/feedback-report +# message/global +# message/global-delivery-status +# message/global-disposition-notification +# message/global-headers +# message/http +# message/imdn+xml +# message/news +# message/partial +message/rfc822 eml mime +# message/s-http +# message/sip +# message/sipfrag +# message/tracking-status +# message/vnd.si.simp +# model/example +model/iges igs iges +model/mesh msh mesh silo +model/vnd.collada+xml dae +model/vnd.dwf dwf +# model/vnd.flatland.3dml +model/vnd.gdl gdl +# model/vnd.gs-gdl +# model/vnd.gs.gdl +model/vnd.gtw gtw +# model/vnd.moml+xml +model/vnd.mts mts +# model/vnd.parasolid.transmit.binary +# model/vnd.parasolid.transmit.text +model/vnd.vtu vtu +model/vrml wrl vrml +model/x3d+binary x3db x3dbz +model/x3d+vrml x3dv x3dvz +model/x3d+xml x3d x3dz +# multipart/alternative +# multipart/appledouble +# multipart/byteranges +# multipart/digest +# multipart/encrypted +# multipart/example +# multipart/form-data +# multipart/header-set +# multipart/mixed +# multipart/parallel +# multipart/related +# multipart/report +# multipart/signed +# multipart/voice-message +# text/1d-interleaved-parityfec +text/cache-manifest appcache +text/calendar ics ifb +text/css css +text/csv csv +# text/directory +# text/dns +# text/ecmascript +# text/enriched +# text/example +# text/fwdred +text/html html htm +# text/javascript +text/n3 n3 +# text/parityfec +text/plain txt text conf def list log in +# text/prs.fallenstein.rst +text/prs.lines.tag dsc +# text/vnd.radisys.msml-basic-layout +# text/red +# text/rfc822-headers +text/richtext rtx +# text/rtf +# text/rtp-enc-aescm128 +# text/rtx +text/sgml sgml sgm +# text/t140 +text/tab-separated-values tsv +text/troff t tr roff man me ms +text/turtle ttl +# text/ulpfec +text/uri-list uri uris urls +text/vcard vcard +# text/vnd.abc +text/vnd.curl curl +text/vnd.curl.dcurl dcurl +text/vnd.curl.scurl scurl +text/vnd.curl.mcurl mcurl +# text/vnd.dmclientscript +text/vnd.dvb.subtitle sub +# text/vnd.esmertec.theme-descriptor +text/vnd.fly fly +text/vnd.fmi.flexstor flx +text/vnd.graphviz gv +text/vnd.in3d.3dml 3dml +text/vnd.in3d.spot spot +# text/vnd.iptc.newsml +# text/vnd.iptc.nitf +# text/vnd.latex-z +# text/vnd.motorola.reflex +# text/vnd.ms-mediapackage +# text/vnd.net2phone.commcenter.command +# text/vnd.si.uricatalogue +text/vnd.sun.j2me.app-descriptor jad +# text/vnd.trolltech.linguist +# text/vnd.wap.si +# text/vnd.wap.sl +text/vnd.wap.wml wml +text/vnd.wap.wmlscript wmls +text/x-asm s asm +text/x-c c cc cxx cpp h hh dic +text/x-fortran f for f77 f90 +text/x-java-source java +text/x-opml opml +text/x-pascal p pas +text/x-nfo nfo +text/x-setext etx +text/x-sfv sfv +text/x-uuencode uu +text/x-vcalendar vcs +text/x-vcard vcf +# text/xml +# text/xml-external-parsed-entity +# video/1d-interleaved-parityfec +video/3gpp 3gp +# video/3gpp-tt +video/3gpp2 3g2 +# video/bmpeg +# video/bt656 +# video/celb +# video/dv +# video/example +video/h261 h261 +video/h263 h263 +# video/h263-1998 +# video/h263-2000 +video/h264 h264 +# video/h264-rcdo +# video/h264-svc +video/jpeg jpgv +# video/jpeg2000 +video/jpm jpm jpgm +video/mj2 mj2 mjp2 +# video/mp1s +# video/mp2p +# video/mp2t +video/mp4 mp4 mp4v mpg4 +# video/mp4v-es +video/mpeg mpeg mpg mpe m1v m2v +# video/mpeg4-generic +# video/mpv +# video/nv +video/ogg ogv +# video/parityfec +# video/pointer +video/quicktime qt mov +# video/raw +# video/rtp-enc-aescm128 +# video/rtx +# video/smpte292m +# video/ulpfec +# video/vc1 +# video/vnd.cctv +video/vnd.dece.hd uvh uvvh +video/vnd.dece.mobile uvm uvvm +# video/vnd.dece.mp4 +video/vnd.dece.pd uvp uvvp +video/vnd.dece.sd uvs uvvs +video/vnd.dece.video uvv uvvv +# video/vnd.directv.mpeg +# video/vnd.directv.mpeg-tts +# video/vnd.dlna.mpeg-tts +video/vnd.dvb.file dvb +video/vnd.fvt fvt +# video/vnd.hns.video +# video/vnd.iptvforum.1dparityfec-1010 +# video/vnd.iptvforum.1dparityfec-2005 +# video/vnd.iptvforum.2dparityfec-1010 +# video/vnd.iptvforum.2dparityfec-2005 +# video/vnd.iptvforum.ttsavc +# video/vnd.iptvforum.ttsmpeg2 +# video/vnd.motorola.video +# video/vnd.motorola.videop +video/vnd.mpegurl mxu m4u +video/vnd.ms-playready.media.pyv pyv +# video/vnd.nokia.interleaved-multimedia +# video/vnd.nokia.videovoip +# video/vnd.objectvideo +# video/vnd.sealed.mpeg1 +# video/vnd.sealed.mpeg4 +# video/vnd.sealed.swf +# video/vnd.sealedmedia.softseal.mov +video/vnd.uvvu.mp4 uvu uvvu +video/vnd.vivo viv +video/webm webm +video/x-f4v f4v +video/x-fli fli +video/x-flv flv +video/x-m4v m4v +video/x-matroska mkv mk3d mks +video/x-mng mng +video/x-ms-asf asf asx +video/x-ms-vob vob +video/x-ms-wm wm +video/x-ms-wmv wmv +video/x-ms-wmx wmx +video/x-ms-wvx wvx +video/x-msvideo avi +video/x-sgi-movie movie +video/x-smv smv +x-conference/x-cooltalk ice diff --git a/spring-data-spring-security/src/main/resources/application.properties b/core-java/src/test/resources/correctFileNameWithoutProperExtension similarity index 100% rename from spring-data-spring-security/src/main/resources/application.properties rename to core-java/src/test/resources/correctFileNameWithoutProperExtension diff --git a/core-java/src/test/resources/product.png b/core-java/src/test/resources/product.png new file mode 100644 index 0000000000..4edd01c0a1 Binary files /dev/null and b/core-java/src/test/resources/product.png differ diff --git a/core-java/src/test/resources/sampleNumberFile.txt b/core-java/src/test/resources/sampleNumberFile.txt new file mode 100644 index 0000000000..7787faa3c1 --- /dev/null +++ b/core-java/src/test/resources/sampleNumberFile.txt @@ -0,0 +1,2 @@ +111 +222 \ No newline at end of file diff --git a/core-java/src/test/resources/sampleTextFile.txt b/core-java/src/test/resources/sampleTextFile.txt new file mode 100644 index 0000000000..75cb50aafa --- /dev/null +++ b/core-java/src/test/resources/sampleTextFile.txt @@ -0,0 +1,2 @@ +Hello +World \ No newline at end of file diff --git a/core-kotlin/.gitignore b/core-kotlin/.gitignore index ae3c172604..0c017e8f8c 100644 --- a/core-kotlin/.gitignore +++ b/core-kotlin/.gitignore @@ -1 +1,14 @@ /bin/ + +#ignore gradle +.gradle/ + + +#ignore build and generated files +build/ +node/ +out/ + +#ignore installed node modules and package lock file +node_modules/ +package-lock.json diff --git a/core-kotlin/README.md b/core-kotlin/README.md index ce47cc2541..f63451bc02 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -8,7 +8,6 @@ - [Generics in Kotlin](http://www.baeldung.com/kotlin-generics) - [Introduction to Kotlin Coroutines](http://www.baeldung.com/kotlin-coroutines) - [Destructuring Declarations in Kotlin](http://www.baeldung.com/kotlin-destructuring-declarations) -- [Kotlin with Mockito](http://www.baeldung.com/kotlin-mockito) - [Lazy Initialization in Kotlin](http://www.baeldung.com/kotlin-lazy-initialization) - [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) @@ -19,10 +18,19 @@ - [Extension Methods in Kotlin](http://www.baeldung.com/kotlin-extension-methods) - [Infix Functions in Kotlin](http://www.baeldung.com/kotlin-infix-functions) - [Try-with-resources in Kotlin](http://www.baeldung.com/kotlin-try-with-resources) -- [HTTP Requests with Kotlin and khttp](http://www.baeldung.com/kotlin-khttp) -- [Kotlin Dependency Injection with Kodein](http://www.baeldung.com/kotlin-kodein-dependency-injection) - [Regular Expressions in Kotlin](http://www.baeldung.com/kotlin-regular-expressions) - [Objects in Kotlin](http://www.baeldung.com/kotlin-objects) - [Reading from a File in Kotlin](http://www.baeldung.com/kotlin-read-file) - [Guide to Kotlin @JvmField](http://www.baeldung.com/kotlin-jvm-field-annotation) - [Filtering Kotlin Collections](http://www.baeldung.com/kotlin-filter-collection) +- [Writing to a File in Kotlin](http://www.baeldung.com/kotlin-write-file) +- [Lambda Expressions in Kotlin](http://www.baeldung.com/kotlin-lambda-expressions) +- [Kotlin String Templates](http://www.baeldung.com/kotlin-string-template) +- [Working with Enums in Kotlin](http://www.baeldung.com/kotlin-enum) +- [Create a Java and Kotlin Project with Maven](http://www.baeldung.com/kotlin-maven-java-project) +- [Reflection with Kotlin](http://www.baeldung.com/kotlin-reflection) +- [Get a Random Number in Kotlin](http://www.baeldung.com/kotlin-random-number) +- [Idiomatic Logging in Kotlin](http://www.baeldung.com/kotlin-logging) +- [Kotlin Constructors](https://www.baeldung.com/kotlin-constructors) +- [Creational Design Patterns in Kotlin: Builder](https://www.baeldung.com/kotlin-builder-pattern) +- [Kotlin Nested and Inner Classes](https://www.baeldung.com/kotlin-inner-classes) \ No newline at end of file diff --git a/core-kotlin/build.gradle b/core-kotlin/build.gradle new file mode 100755 index 0000000000..2b6527fca7 --- /dev/null +++ b/core-kotlin/build.gradle @@ -0,0 +1,48 @@ + + +group 'com.baeldung.ktor' +version '1.0-SNAPSHOT' + + +buildscript { + ext.kotlin_version = '1.2.41' + + repositories { + mavenCentral() + } + dependencies { + + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +apply plugin: 'java' +apply plugin: 'kotlin' +apply plugin: 'application' + +mainClassName = 'APIServer.kt' + +sourceCompatibility = 1.8 +compileKotlin { kotlinOptions.jvmTarget = "1.8" } +compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } + +kotlin { experimental { coroutines "enable" } } + +repositories { + mavenCentral() + jcenter() + maven { url "https://dl.bintray.com/kotlin/ktor" } +} +sourceSets { + main{ + kotlin{ + srcDirs 'com/baeldung/ktor' + } + } + +} + +dependencies { + compile "ch.qos.logback:logback-classic:1.2.1" + testCompile group: 'junit', name: 'junit', version: '4.12' +} \ No newline at end of file diff --git a/core-kotlin/gradle/wrapper/gradle-wrapper.jar b/core-kotlin/gradle/wrapper/gradle-wrapper.jar new file mode 100755 index 0000000000..01b8bf6b1f Binary files /dev/null and b/core-kotlin/gradle/wrapper/gradle-wrapper.jar differ diff --git a/core-kotlin/gradle/wrapper/gradle-wrapper.properties b/core-kotlin/gradle/wrapper/gradle-wrapper.properties new file mode 100755 index 0000000000..0b83b5a3e3 --- /dev/null +++ b/core-kotlin/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip diff --git a/core-kotlin/gradlew b/core-kotlin/gradlew new file mode 100755 index 0000000000..cccdd3d517 --- /dev/null +++ b/core-kotlin/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# 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 + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# 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 +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +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" -a "$nonstop" = "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 + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/core-kotlin/gradlew.bat b/core-kotlin/gradlew.bat new file mode 100755 index 0000000000..e95643d6a2 --- /dev/null +++ b/core-kotlin/gradlew.bat @@ -0,0 +1,84 @@ +@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 + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@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= + +@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 + +: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=%* + +: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/core-kotlin/pom.xml b/core-kotlin/pom.xml index 24bfb302cf..0894a57320 100644 --- a/core-kotlin/pom.xml +++ b/core-kotlin/pom.xml @@ -3,22 +3,15 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-kotlin - 1.0-SNAPSHOT jar com.baeldung - parent-modules + parent-kotlin 1.0.0-SNAPSHOT + ../parent-kotlin - - - central - http://jcenter.bintray.com - - - org.apache.commons @@ -31,191 +24,52 @@ ${junit.platform.version} test - - org.jetbrains.kotlin - kotlin-stdlib - ${kotlin-stdlib.version} - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin-stdlib.version} - - - khttp - khttp - ${khttp.version} - - - org.jetbrains.kotlin - kotlin-test-junit - ${kotlin-test-junit.version} - test - - - org.jetbrains.kotlin - kotlin-reflect - ${kotlin-reflect.version} - test - - - org.jetbrains.kotlinx - kotlinx-coroutines-core - ${kotlinx.version} - - - org.jetbrains.spek - spek-api - 1.1.5 - test - - - org.jetbrains.spek - spek-subject-extension - 1.1.5 - test - - - org.jetbrains.spek - spek-junit-platform-engine - 1.1.5 - test - - - com.nhaarman - mockito-kotlin - ${mockito-kotlin.version} - test - - - com.github.salomonbrys.kodein - kodein - ${kodein.version} - org.assertj assertj-core ${assertj.version} test + + com.h2database + h2 + ${h2database.version} + + + com.github.kittinunf.fuel + fuel + ${fuel.version} + + + com.github.kittinunf.fuel + fuel-gson + ${fuel.version} + + + com.github.kittinunf.fuel + fuel-rxjava + ${fuel.version} + + + com.github.kittinunf.fuel + fuel-coroutines + ${fuel.version} + + + nl.komponents.kovenant + kovenant + 3.3.0 + pom + - - - - kotlin-maven-plugin - org.jetbrains.kotlin - ${kotlin-maven-plugin.version} - - - compile - - compile - - - - ${project.basedir}/src/main/kotlin - ${project.basedir}/src/main/java - - - - - test-compile - - test-compile - - - - ${project.basedir}/src/test/kotlin - ${project.basedir}/src/test/java - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - - - - - default-compile - none - - - - default-testCompile - none - - - java-compile - compile - - compile - - - - java-test-compile - test-compile - - testCompile - - - - - - maven-failsafe-plugin - ${maven-failsafe-plugin.version} - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - - - - - junit5 - - integration-test - verify - - - - **/*Test5.java - - - - - - - - - UTF-8 - 1.2.31 - 1.2.31 - 1.2.31 - 1.2.31 - 0.15 - 1.5.0 - 4.1.0 - 0.1.0 3.6.1 - 5.0.0 - 1.0.0 - 4.12.0 - 4.12 - 3.9.1 - 1.8 - 1.8 + 1.1.1 + 5.2.0 + 3.10.0 + 1.4.197 + 1.15.0 diff --git a/core-kotlin/resources/logback.xml b/core-kotlin/resources/logback.xml new file mode 100755 index 0000000000..274cdcdb02 --- /dev/null +++ b/core-kotlin/resources/logback.xml @@ -0,0 +1,11 @@ + + + + %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + \ No newline at end of file diff --git a/core-kotlin/settings.gradle b/core-kotlin/settings.gradle new file mode 100755 index 0000000000..13bbce9583 --- /dev/null +++ b/core-kotlin/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'KtorWithKotlin' + diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt b/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt new file mode 100644 index 0000000000..72b8d330e8 --- /dev/null +++ b/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt @@ -0,0 +1,17 @@ +package com.baeldung.constructor + +class Car { + val id: String + val type: String + + constructor(id: String, type: String) { + this.id = id + this.type = type + } + +} + +fun main(args: Array) { + val car = Car("1", "sport") + val s= Car("2", "suv") +} \ No newline at end of file diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt b/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt new file mode 100644 index 0000000000..4483bfcf08 --- /dev/null +++ b/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt @@ -0,0 +1,3 @@ +package com.baeldung.constructor + +class Employee(name: String, val salary: Int): Person(name) \ No newline at end of file diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Person.java b/core-kotlin/src/main/java/com/baeldung/constructor/Person.java new file mode 100644 index 0000000000..57911b24ee --- /dev/null +++ b/core-kotlin/src/main/java/com/baeldung/constructor/Person.java @@ -0,0 +1,19 @@ +package com.baeldung.constructor; + +class PersonJava { + final String name; + final String surname; + final Integer age; + + public PersonJava(String name, String surname) { + this.name = name; + this.surname = surname; + this.age = null; + } + + public PersonJava(String name, String surname, Integer age) { + this.name = name; + this.surname = surname; + this.age = age; + } +} diff --git a/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/Application.java b/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/Application.java new file mode 100644 index 0000000000..e2cc0f1e01 --- /dev/null +++ b/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/Application.java @@ -0,0 +1,26 @@ +package com.baeldung.mavenjavakotlin; + +import com.baeldung.mavenjavakotlin.services.JavaService; +import com.baeldung.mavenjavakotlin.services.KotlinService; + +public class Application { + + private static final String JAVA = "java"; + private static final String KOTLIN = "kotlin"; + + public static void main(String[] args) { + String language = args[0]; + switch (language) { + case JAVA: + new JavaService().sayHello(); + break; + case KOTLIN: + new KotlinService().sayHello(); + break; + default: + // Do nothing + break; + } + } + +} diff --git a/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/services/JavaService.java b/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/services/JavaService.java new file mode 100644 index 0000000000..b767e761af --- /dev/null +++ b/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/services/JavaService.java @@ -0,0 +1,9 @@ +package com.baeldung.mavenjavakotlin.services; + +public class JavaService { + + public void sayHello() { + System.out.println("Java says 'Hello World!'"); + } + +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt new file mode 100644 index 0000000000..1384cd9937 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt @@ -0,0 +1,22 @@ +package com.baeldung.builder + +class FoodOrder( + val bread: String?, + val condiments: String?, + val meat: String?, + val fish: String? +) { + data class Builder( + var bread: String? = null, + var condiments: String? = null, + var meat: String? = null, + var fish: String? = null) { + + fun bread(bread: String) = apply { this.bread = bread } + fun condiments(condiments: String) = apply { this.condiments = condiments } + fun meat(meat: String) = apply { this.meat = meat } + fun fish(fish: String) = apply { this.fish = fish } + fun build() = FoodOrder(bread, condiments, meat, fish) + } +} + diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt new file mode 100644 index 0000000000..0a68832b00 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt @@ -0,0 +1,8 @@ +package com.baeldung.builder + +class FoodOrderApply { + var bread: String? = null + var condiments: String? = null + var meat: String? = null + var fish: String? = null +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt new file mode 100644 index 0000000000..0e4219b40e --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt @@ -0,0 +1,7 @@ +package com.baeldung.builder + +data class FoodOrderNamed( + val bread: String? = null, + val condiments: String? = null, + val meat: String? = null, + val fish: String? = null) diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt b/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt new file mode 100644 index 0000000000..cc348e3fbf --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt @@ -0,0 +1,9 @@ +package com.baeldung.builder + +fun main(args: Array) { + FoodOrder.Builder() + .bread("bread") + .condiments("condiments") + .meat("meat") + .fish("bread").let { println(it) } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt b/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt new file mode 100644 index 0000000000..3779d74541 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt @@ -0,0 +1,26 @@ +package com.baeldung.constructor + +open class Person( + val name: String, + val age: Int? = null +) { + val upperCaseName: String = name.toUpperCase() + + init { + println("Hello, I'm $name") + + if (age != null && age < 0) { + throw IllegalArgumentException("Age cannot be less than zero!") + } + } + + init { + println("upperCaseName is $upperCaseName") + } + +} + +fun main(args: Array) { + val person = Person("John") + val personWithAge = Person("John", 22) +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/enums/CardType.kt b/core-kotlin/src/main/kotlin/com/baeldung/enums/CardType.kt new file mode 100644 index 0000000000..69cfce5601 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/enums/CardType.kt @@ -0,0 +1,23 @@ +package com.baeldung.enums + +enum class CardType(val color: String) : ICardLimit { + SILVER("gray") { + override fun getCreditLimit() = 100000 + override fun calculateCashbackPercent() = 0.25f + }, + GOLD("yellow") { + override fun getCreditLimit() = 200000 + override fun calculateCashbackPercent(): Float = 0.5f + }, + PLATINUM("black") { + override fun getCreditLimit() = 300000 + override fun calculateCashbackPercent() = 0.75f + }; + + companion object { + fun getCardTypeByColor(color: String) = values().firstOrNull { it.color == color } + fun getCardTypeByName(name: String) = valueOf(name.toUpperCase()) + } + + abstract fun calculateCashbackPercent(): Float +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/enums/ICardLimit.kt b/core-kotlin/src/main/kotlin/com/baeldung/enums/ICardLimit.kt new file mode 100644 index 0000000000..7994822a52 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/enums/ICardLimit.kt @@ -0,0 +1,5 @@ +package com.baeldung.enums + +interface ICardLimit { + fun getCreditLimit(): Int +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/fuel/Interceptors.kt b/core-kotlin/src/main/kotlin/com/baeldung/fuel/Interceptors.kt new file mode 100644 index 0000000000..377ef979dc --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/fuel/Interceptors.kt @@ -0,0 +1,11 @@ +package com.baeldung.fuel + +import com.github.kittinunf.fuel.core.Request + +fun tokenInterceptor() = { + next: (Request) -> Request -> + { req: Request -> + req.header(mapOf("Authorization" to "Bearer AbCdEf123456")) + next(req) + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/fuel/Post.kt b/core-kotlin/src/main/kotlin/com/baeldung/fuel/Post.kt new file mode 100644 index 0000000000..035dfe7aa0 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/fuel/Post.kt @@ -0,0 +1,15 @@ +package com.baeldung.fuel + +import com.github.kittinunf.fuel.core.ResponseDeserializable +import com.google.gson.Gson + +data class Post(var userId:Int, + var id:Int, + var title:String, + var body:String){ + + + class Deserializer : ResponseDeserializable> { + override fun deserialize(content: String): Array = Gson().fromJson(content, Array::class.java) + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt b/core-kotlin/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt new file mode 100644 index 0000000000..8238c41e56 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt @@ -0,0 +1,42 @@ +package com.baeldung.fuel + +import com.github.kittinunf.fuel.core.Method +import com.github.kittinunf.fuel.util.FuelRouting + +sealed class PostRoutingAPI : FuelRouting { + + override val basePath = "https://jsonplaceholder.typicode.com" + + class posts(val id: String, override val body: String?): PostRoutingAPI() + + class comments(val postId: String, override val body: String?): PostRoutingAPI() + + override val method: Method + get() { + return when(this) { + is PostRoutingAPI.posts -> Method.GET + is PostRoutingAPI.comments -> Method.GET + } + } + + override val path: String + get() { + return when(this) { + is PostRoutingAPI.posts -> "/posts" + is PostRoutingAPI.comments -> "/comments" + } + } + + override val params: List>? + get() { + return when(this) { + is PostRoutingAPI.posts -> listOf("id" to this.id) + is PostRoutingAPI.comments -> listOf("postId" to this.postId) + } + } + + override val headers: Map? + get() { + return null + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsExtensionOnAny.kt b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsExtensionOnAny.kt new file mode 100644 index 0000000000..32d968fff5 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsExtensionOnAny.kt @@ -0,0 +1,30 @@ +package com.baeldung.kotlin.logging + +import org.slf4j.Logger + +open class LoggerAsExtensionOnAny { + val logger = logger() + + fun log(s: String) { + logger().info(s) + logger.info(s) + } +} + +class ExtensionSubclass : LoggerAsExtensionOnAny() + +fun T.logger(): Logger = getLogger(getClassForLogging(javaClass)) + +fun main(args: Array) { + LoggerAsExtensionOnAny().log("test") + ExtensionSubclass().log("sub") + "foo".logger().info("foo") + 1.logger().info("uh-oh!") + SomeOtherClass().logger() +} + +class SomeOtherClass { + fun logger(): String { + return "foo" + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsExtensionOnMarkerInterface.kt b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsExtensionOnMarkerInterface.kt new file mode 100644 index 0000000000..b33d4c9f93 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsExtensionOnMarkerInterface.kt @@ -0,0 +1,30 @@ +package com.baeldung.kotlin.logging + +import org.slf4j.Logger +import org.slf4j.LoggerFactory + +interface Logging + +inline fun T.logger(): Logger = + //Wrong logger name! + //LoggerFactory.getLogger(javaClass.name + " w/interface") + LoggerFactory.getLogger(getClassForLogging(T::class.java).name + " w/interface") + +open class LoggerAsExtensionOnMarkerInterface : Logging { + companion object : Logging { + val logger = logger() + } + + fun log(s: String) { + logger().info(s) + logger.info(s) + } +} + +class MarkerExtensionSubclass : LoggerAsExtensionOnMarkerInterface() + +fun main(args: Array) { + LoggerAsExtensionOnMarkerInterface().log("test") + MarkerExtensionSubclass().log("sub") + "foo".logger().info("foo") +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsProperty.kt b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsProperty.kt new file mode 100644 index 0000000000..979b3b3a10 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsProperty.kt @@ -0,0 +1,17 @@ +package com.baeldung.kotlin.logging + +open class LoggerAsProperty { + private val logger = getLogger(javaClass) + + fun log(s: String) { + logger.info(s) + } + +} + +class PropertySubclass : LoggerAsProperty() + +fun main(args: Array) { + LoggerAsProperty().log("test") + PropertySubclass().log("sub") +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsPropertyDelegate.kt b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsPropertyDelegate.kt new file mode 100644 index 0000000000..23f04722be --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerAsPropertyDelegate.kt @@ -0,0 +1,47 @@ +package com.baeldung.kotlin.logging + +import org.slf4j.Logger +import kotlin.properties.ReadOnlyProperty +import kotlin.reflect.KProperty + +open class LoggerAsPropertyDelegate { + private val lazyLogger by lazyLogger() + protected val logger by LoggerDelegate() + private val logger2 = logger + + companion object { + private val lazyLoggerComp by lazyLogger() + private val loggerComp by LoggerDelegate() + } + + open fun log(s: String) { + logger.info(s) + logger2.info(s) + lazyLogger.info(s) + loggerComp.info(s) + lazyLoggerComp.info(s) + } + +} + +class DelegateSubclass : LoggerAsPropertyDelegate() { + override fun log(s: String) { + logger.info("-- in sub") + super.log(s) + } +} + +fun lazyLogger(forClass: Class<*>): Lazy = + lazy { getLogger(getClassForLogging(forClass)) } + +fun T.lazyLogger(): Lazy = lazyLogger(javaClass) + +fun main(args: Array) { + LoggerAsPropertyDelegate().log("test") + DelegateSubclass().log("sub") +} + +class LoggerDelegate : ReadOnlyProperty { + override fun getValue(thisRef: R, property: KProperty<*>) = + getLogger(getClassForLogging(thisRef.javaClass)) +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerInCompanionObject.kt b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerInCompanionObject.kt new file mode 100644 index 0000000000..f973606369 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/LoggerInCompanionObject.kt @@ -0,0 +1,44 @@ +package com.baeldung.kotlin.logging + +open class LoggerInCompanionObject { + companion object { + private val loggerWithExplicitClass = getLogger(LoggerInCompanionObject::class.java) + @Suppress("JAVA_CLASS_ON_COMPANION") + private val loggerWithWrongClass = getLogger(javaClass) + @Suppress("JAVA_CLASS_ON_COMPANION") + private val logger = getLogger(javaClass.enclosingClass) + } + + fun log(s: String) { + loggerWithExplicitClass.info(s) + loggerWithWrongClass.info(s) + logger.info(s) + } + + class Inner { + companion object { + private val loggerWithExplicitClass = getLogger(Inner::class.java) + @Suppress("JAVA_CLASS_ON_COMPANION") + @JvmStatic + private val loggerWithWrongClass = getLogger(javaClass) + @Suppress("JAVA_CLASS_ON_COMPANION") + @JvmStatic + private val logger = getLogger(javaClass.enclosingClass) + } + + fun log(s: String) { + loggerWithExplicitClass.info(s) + loggerWithWrongClass.info(s) + logger.info(s) + } + } + +} + +class CompanionSubclass : LoggerInCompanionObject() + +fun main(args: Array) { + LoggerInCompanionObject().log("test") + LoggerInCompanionObject.Inner().log("test") + CompanionSubclass().log("sub") +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/Util.kt b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/Util.kt new file mode 100644 index 0000000000..b9c0d9e34c --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/logging/Util.kt @@ -0,0 +1,13 @@ +package com.baeldung.kotlin.logging + +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import kotlin.reflect.full.companionObject + +fun getLogger(forClass: Class<*>): Logger = LoggerFactory.getLogger(forClass) + +fun getClassForLogging(javaClass: Class): Class<*> { + return javaClass.enclosingClass?.takeIf { + it.kotlin.companionObject?.java == javaClass + } ?: javaClass +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/mavenjavakotlin/services/KotlinService.kt b/core-kotlin/src/main/kotlin/com/baeldung/mavenjavakotlin/services/KotlinService.kt new file mode 100644 index 0000000000..114b1c88df --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/mavenjavakotlin/services/KotlinService.kt @@ -0,0 +1,9 @@ +package com.baeldung.mavenjavakotlin.services + +class KotlinService { + + fun sayHello() { + System.out.println("Kotlin says 'Hello World!'") + } + +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt b/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt new file mode 100644 index 0000000000..ee01c06646 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt @@ -0,0 +1,75 @@ +package com.baeldung.nested + +import org.slf4j.Logger +import org.slf4j.LoggerFactory + +class Computer(val model: String) { + + companion object { + const val originCountry = "China" + fun getBuiltDate(): String { + return "2018-05-23" + } + + val log: Logger = LoggerFactory.getLogger(Computer::class.java) + } + + //Nested class + class MotherBoard(val manufacturer: String) { + fun getInfo() = "Made by $manufacturer installed in $originCountry - ${getBuiltDate()}" + } + + //Inner class + inner class HardDisk(val sizeInGb: Int) { + fun getInfo() = "Installed on ${this@Computer} with $sizeInGb GB" + } + + interface Switcher { + fun on(): String + } + + interface Protector { + fun smart() + } + + fun powerOn(): String { + //Local class + var defaultColor = "Blue" + + class Led(val color: String) { + fun blink(): String { + return "blinking $color" + } + + fun changeDefaultPowerOnColor() { + defaultColor = "Violet" + } + } + + val powerLed = Led("Green") + log.debug("defaultColor is $defaultColor") + powerLed.changeDefaultPowerOnColor() + log.debug("defaultColor changed inside Led class to $defaultColor") + //Anonymous object + val powerSwitch = object : Switcher, Protector { + override fun on(): String { + return powerLed.blink() + } + + override fun smart() { + log.debug("Smart protection is implemented") + } + + fun changeDefaultPowerOnColor() { + defaultColor = "Yellow" + } + } + powerSwitch.changeDefaultPowerOnColor() + log.debug("defaultColor changed inside powerSwitch anonymous object to $defaultColor") + return powerSwitch.on() + } + + override fun toString(): String { + return "Computer(model=$model)" + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/stringtemplates/Templates.kt b/core-kotlin/src/main/kotlin/com/baeldung/stringtemplates/Templates.kt new file mode 100644 index 0000000000..4b2d863618 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/stringtemplates/Templates.kt @@ -0,0 +1,115 @@ +package com.baeldung.stringtemplates + +/** + * Example of a useful function defined in Kotlin String class + */ +fun padExample(): String { + return "Hello".padEnd(10, '!') +} + +/** + * Example of a simple string template usage + */ +fun simpleTemplate(n: Int): String { + val message = "n = $n" + return message +} + +/** + * Example of a string template with a simple expression + */ +fun templateWithExpression(n: Int): String { + val message = "n + 1 = ${n + 1}" + return message +} + +/** + * Example of a string template with expression containing some logic + */ +fun templateWithLogic(n: Int): String { + val message = "$n is ${if (n > 0) "positive" else "not positive"}" + return message +} + +/** + * Example of nested string templates + */ +fun nestedTemplates(n: Int): String { + val message = "$n is ${if (n > 0) "positive" else if (n < 0) "negative and ${if (n % 2 == 0) "even" else "odd"}" else "zero"}" + return message +} + +/** + * Example of joining array's element into a string with a default separator + */ +fun templateJoinArray(): String { + val numbers = listOf(1, 1, 2, 3, 5, 8) + val message = "first Fibonacci numbers: ${numbers.joinToString()}" + return message +} + +/** + * Example of escaping the dollar sign + */ +fun notAStringTemplate(): String { + val message = "n = \$n" + return message +} + +/** + * Example of a simple triple quoted string + */ +fun showFilePath(): String { + val path = """C:\Repository\read.me""" + return path +} + +/** + * Example of a multiline string + */ +fun showMultiline(): String { + val receipt = """Item 1: $1.00 +Item 2: $0.50""" + return receipt +} + +/** + * Example of a multiline string with indentation + */ +fun showMultilineIndent(): String { + val receipt = """Item 1: $1.00 + >Item 2: $0.50""".trimMargin(">") + return receipt +} + +/** + * Example of a triple quoted string with a not-working escape sequence + */ +fun showTripleQuotedWrongEscape(): String { + val receipt = """Item 1: $1.00\nItem 2: $0.50""" + return receipt +} + +/** + * Example of a triple quoted string with a correctly working escape sequence + */ + +fun showTripleQuotedCorrectEscape(): String { + val receipt = """Item 1: $1.00${"\n"}Item 2: $0.50""" + return receipt +} + +fun main(args: Array) { + println(padExample()) + println(simpleTemplate(10)) + println(templateWithExpression(5)) + println(templateWithLogic(7)) + println(nestedTemplates(-5)) + println(templateJoinArray()) + println(notAStringTemplate()) + println(showFilePath()) + println(showMultiline()) + println(showMultilineIndent()) + println(showTripleQuotedWrongEscape()) + println(showTripleQuotedCorrectEscape()) +} diff --git a/core-kotlin/src/main/resources/logback.xml b/core-kotlin/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/core-kotlin/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/core-kotlin/src/test/java/com/baeldung/lambda/LambdaKotlinTest.java b/core-kotlin/src/test/java/com/baeldung/lambda/LambdaKotlinTest.java deleted file mode 100644 index 1e68d8af4c..0000000000 --- a/core-kotlin/src/test/java/com/baeldung/lambda/LambdaKotlinTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.lambda; - -import kotlin.jvm.functions.Function1; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Created by Paul Jervis on 24/04/2018. - */ -class LambdaKotlinTest { - - @Test - void givenJava6_whenUsingAnonnymousClass_thenReturnLambdaResult() { - assertTrue(LambdaKt.invokeLambda(new Function1() { - @Override - public Boolean invoke(Double c) { - return c >= 0; - } - })); - } - - @Test - void givenJava8_whenUsingLambda_thenReturnLambdaResult() { - assertTrue(LambdaKt.invokeLambda(c -> c >= 0)); - } - - @Test - void givenJava8_whenCallingMethodWithStringExtension_thenImplementExtension() { - String actual = LambdaKt.extendString("Word", 90); - String expected = "Word90"; - - assertEquals(expected, actual); - } -} diff --git a/core-kotlin/src/test/java/com/baeldung/lambda/LambdaKotlinUnitTest.java b/core-kotlin/src/test/java/com/baeldung/lambda/LambdaKotlinUnitTest.java new file mode 100644 index 0000000000..91c777c036 --- /dev/null +++ b/core-kotlin/src/test/java/com/baeldung/lambda/LambdaKotlinUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.lambda; + +import kotlin.jvm.functions.Function1; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Created by Paul Jervis on 24/04/2018. + */ +class LambdaKotlinUnitTest { + + @Test + void givenJava6_whenUsingAnonnymousClass_thenReturnLambdaResult() { + assertTrue(LambdaKt.invokeLambda(new Function1() { + @Override + public Boolean invoke(Double c) { + return c >= 0; + } + })); + } + + @Test + void givenJava8_whenUsingLambda_thenReturnLambdaResult() { + assertTrue(LambdaKt.invokeLambda(c -> c >= 0)); + } + + @Test + void givenJava8_whenCallingMethodWithStringExtension_thenImplementExtension() { + String actual = LambdaKt.extendString("Word", 90); + String expected = "Word90"; + + assertEquals(expected, actual); + } +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt new file mode 100644 index 0000000000..a6687b6e0a --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt @@ -0,0 +1,140 @@ +package com.baeldung.builder + +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.Test + +internal class BuilderPatternUnitTest { + + @Test + fun whenBuildingFoodOrderSettingValues_thenFieldsNotNull() { + + val foodOrder = FoodOrder.Builder() + .bread("white bread") + .meat("bacon") + .fish("salmon") + .condiments("olive oil") + .build() + + Assertions.assertNotNull(foodOrder.bread) + Assertions.assertNotNull(foodOrder.meat) + Assertions.assertNotNull(foodOrder.condiments) + Assertions.assertNotNull(foodOrder.fish) + } + + @Test + fun whenBuildingFoodOrderSettingValues_thenFieldsContainsValues() { + + val foodOrder = FoodOrder.Builder() + .bread("white bread") + .meat("bacon") + .fish("salmon") + .condiments("olive oil") + .build() + + Assertions.assertEquals("white bread", foodOrder.bread) + Assertions.assertEquals("bacon", foodOrder.meat) + Assertions.assertEquals("olive oil", foodOrder.condiments) + Assertions.assertEquals("salmon", foodOrder.fish) + } + + @Test + fun whenBuildingFoodOrderWithoutSettingValues_thenFieldsNull() { + + val foodOrder = FoodOrder.Builder() + .build() + + Assertions.assertNull(foodOrder.bread) + Assertions.assertNull(foodOrder.meat) + Assertions.assertNull(foodOrder.condiments) + Assertions.assertNull(foodOrder.fish) + } + + + @Test + fun whenBuildingFoodOrderNamedSettingValues_thenFieldsNotNull() { + + val foodOrder = FoodOrderNamed( + meat = "bacon", + fish = "salmon", + condiments = "olive oil", + bread = "white bread" + ) + + Assertions.assertNotNull(foodOrder.bread) + Assertions.assertNotNull(foodOrder.meat) + Assertions.assertNotNull(foodOrder.condiments) + Assertions.assertNotNull(foodOrder.fish) + } + + @Test + fun whenBuildingFoodOrderNamedSettingValues_thenFieldsContainsValues() { + + val foodOrder = FoodOrderNamed( + meat = "bacon", + fish = "salmon", + condiments = "olive oil", + bread = "white bread" + ) + + Assertions.assertEquals("white bread", foodOrder.bread) + Assertions.assertEquals("bacon", foodOrder.meat) + Assertions.assertEquals("olive oil", foodOrder.condiments) + Assertions.assertEquals("salmon", foodOrder.fish) + } + + @Test + fun whenBuildingFoodOrderNamedWithoutSettingValues_thenFieldsNull() { + + val foodOrder = FoodOrderNamed() + + Assertions.assertNull(foodOrder.bread) + Assertions.assertNull(foodOrder.meat) + Assertions.assertNull(foodOrder.condiments) + Assertions.assertNull(foodOrder.fish) + } + + + @Test + fun whenBuildingFoodOrderApplySettingValues_thenFieldsNotNull() { + + val foodOrder = FoodOrderApply().apply { + meat = "bacon" + fish = "salmon" + condiments = "olive oil" + bread = "white bread" + } + + Assertions.assertNotNull(foodOrder.bread) + Assertions.assertNotNull(foodOrder.meat) + Assertions.assertNotNull(foodOrder.condiments) + Assertions.assertNotNull(foodOrder.fish) + } + + @Test + fun whenBuildingFoodOrderApplySettingValues_thenFieldsContainsValues() { + + val foodOrder = FoodOrderApply().apply { + meat = "bacon" + fish = "salmon" + condiments = "olive oil" + bread = "white bread" + } + + Assertions.assertEquals("white bread", foodOrder.bread) + Assertions.assertEquals("bacon", foodOrder.meat) + Assertions.assertEquals("olive oil", foodOrder.condiments) + Assertions.assertEquals("salmon", foodOrder.fish) + } + + @Test + fun whenBuildingFoodOrderApplyWithoutSettingValues_thenFieldsNull() { + + val foodOrder = FoodOrderApply() + + Assertions.assertNull(foodOrder.bread) + Assertions.assertNull(foodOrder.meat) + Assertions.assertNull(foodOrder.condiments) + Assertions.assertNull(foodOrder.fish) + } + +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt new file mode 100644 index 0000000000..525faebd55 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt @@ -0,0 +1,84 @@ +package com.baeldung.enums + +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +internal class CardTypeUnitTest { + + @Test + fun givenSilverCardType_whenCalculateCashbackPercent_thenReturnCashbackValue() { + assertEquals(0.25f, CardType.SILVER.calculateCashbackPercent()) + } + + @Test + fun givenGoldCardType_whenCalculateCashbackPercent_thenReturnCashbackValue() { + assertEquals(0.5f, CardType.GOLD.calculateCashbackPercent()) + } + + @Test + fun givenPlatinumCardType_whenCalculateCashbackPercent_thenReturnCashbackValue() { + assertEquals(0.75f, CardType.PLATINUM.calculateCashbackPercent()) + } + + @Test + fun givenSilverCardType_whenGetCreditLimit_thenReturnCreditLimit() { + assertEquals(100000, CardType.SILVER.getCreditLimit()) + } + + @Test + fun givenGoldCardType_whenGetCreditLimit_thenReturnCreditLimit() { + assertEquals(200000, CardType.GOLD.getCreditLimit()) + } + + @Test + fun givenPlatinumCardType_whenGetCreditLimit_thenReturnCreditLimit() { + assertEquals(300000, CardType.PLATINUM.getCreditLimit()) + } + + @Test + fun givenSilverCardType_whenCheckColor_thenReturnColor() { + assertEquals("gray", CardType.SILVER.color) + } + + @Test + fun givenGoldCardType_whenCheckColor_thenReturnColor() { + assertEquals("yellow", CardType.GOLD.color) + } + + @Test + fun givenPlatinumCardType_whenCheckColor_thenReturnColor() { + assertEquals("black", CardType.PLATINUM.color) + } + + @Test + fun whenGetCardTypeByColor_thenSilverCardType() { + Assertions.assertEquals(CardType.SILVER, CardType.getCardTypeByColor("gray")) + } + + @Test + fun whenGetCardTypeByColor_thenGoldCardType() { + Assertions.assertEquals(CardType.GOLD, CardType.getCardTypeByColor("yellow")) + } + + @Test + fun whenGetCardTypeByColor_thenPlatinumCardType() { + Assertions.assertEquals(CardType.PLATINUM, CardType.getCardTypeByColor("black")) + } + + @Test + fun whenGetCardTypeByName_thenSilverCardType() { + Assertions.assertEquals(CardType.SILVER, CardType.getCardTypeByName("silver")) + } + + @Test + fun whenGetCardTypeByName_thenGoldCardType() { + Assertions.assertEquals(CardType.GOLD, CardType.getCardTypeByName("gold")) + } + + @Test + fun whenGetCardTypeByName_thenPlatinumCardType() { + Assertions.assertEquals(CardType.PLATINUM, CardType.getCardTypeByName("platinum")) + } + +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt new file mode 100644 index 0000000000..f0f9267618 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt @@ -0,0 +1,286 @@ +package com.baeldung.fuel + +import awaitObjectResult +import awaitStringResponse +import com.github.kittinunf.fuel.Fuel +import com.github.kittinunf.fuel.core.FuelManager +import com.github.kittinunf.fuel.core.Request +import com.github.kittinunf.fuel.core.interceptors.cUrlLoggingRequestInterceptor +import com.github.kittinunf.fuel.gson.responseObject +import com.github.kittinunf.fuel.httpGet +import com.github.kittinunf.fuel.rx.rx_object +import com.google.gson.Gson +import kotlinx.coroutines.experimental.runBlocking +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.Test +import java.io.File +import java.util.concurrent.CountDownLatch + +internal class FuelHttpUnitTest { + + @Test + fun whenMakingAsyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { + + val latch = CountDownLatch(1) + + "http://httpbin.org/get".httpGet().response{ + request, response, result -> + + val (data, error) = result + + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(200,response.statusCode) + + latch.countDown() + } + + latch.await() + + } + + @Test + fun whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { + + val (request, response, result) = "http://httpbin.org/get".httpGet().response() + val (data, error) = result + + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(200,response.statusCode) + + } + + @Test + fun whenMakingSyncHttpGetURLEncodedRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { + + val (request, response, result) = + "https://jsonplaceholder.typicode.com/posts" + .httpGet(listOf("id" to "1")).response() + val (data, error) = result + + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(200,response.statusCode) + + } + + @Test + fun whenMakingAsyncHttpPostRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { + + val latch = CountDownLatch(1) + + Fuel.post("http://httpbin.org/post").response{ + request, response, result -> + + val (data, error) = result + + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(200,response.statusCode) + + latch.countDown() + } + + latch.await() + + } + + @Test + fun whenMakingSyncHttpPostRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { + + val (request, response, result) = Fuel.post("http://httpbin.org/post").response() + val (data, error) = result + + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(200,response.statusCode) + } + + @Test + fun whenMakingSyncHttpPostRequestwithBody_thenResponseNotNullAndErrorNullAndStatusCode200() { + + val (request, response, result) = Fuel.post("https://jsonplaceholder.typicode.com/posts") + .body("{ \"title\" : \"foo\",\"body\" : \"bar\",\"id\" : \"1\"}") + .response() + + val (data, error) = result + + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(201,response.statusCode) + } + + @Test + fun givenFuelInstance_whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { + + FuelManager.instance.basePath = "http://httpbin.org" + FuelManager.instance.baseHeaders = mapOf("OS" to "macOS High Sierra") + + FuelManager.instance.addRequestInterceptor(cUrlLoggingRequestInterceptor()) + FuelManager.instance.addRequestInterceptor(tokenInterceptor()) + + + val (request, response, result) = "/get" + .httpGet().response() + val (data, error) = result + + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(200,response.statusCode) + } + + @Test + fun givenInterceptors_whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { + + FuelManager.instance.basePath = "http://httpbin.org" + FuelManager.instance.addRequestInterceptor(cUrlLoggingRequestInterceptor()) + FuelManager.instance.addRequestInterceptor(tokenInterceptor()) + + val (request, response, result) = "/get" + .httpGet().response() + val (data, error) = result + + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(200,response.statusCode) + } + + @Test + fun whenDownloadFile_thenCreateFileResponseNotNullAndErrorNullAndStatusCode200() { + + Fuel.download("http://httpbin.org/bytes/32768").destination { response, url -> + File.createTempFile("temp", ".tmp") + }.response{ + request, response, result -> + + val (data, error) = result + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(200,response.statusCode) + } + } + + @Test + fun whenDownloadFilewithProgressHandler_thenCreateFileResponseNotNullAndErrorNullAndStatusCode200() { + + val (request, response, result) = Fuel.download("http://httpbin.org/bytes/327680") + .destination { response, url -> File.createTempFile("temp", ".tmp") + }.progress { readBytes, totalBytes -> + val progress = readBytes.toFloat() / totalBytes.toFloat() + }.response () + + val (data, error) = result + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(200,response.statusCode) + + + } + + @Test + fun whenMakeGetRequest_thenDeserializePostwithGson() { + + val latch = CountDownLatch(1) + + "https://jsonplaceholder.typicode.com/posts/1".httpGet().responseObject { _,_, result -> + val post = result.component1() + Assertions.assertEquals(1, post?.userId) + latch.countDown() + } + + latch.await() + + } + + @Test + fun whenMakePOSTRequest_thenSerializePostwithGson() { + + val post = Post(1,1, "Lorem", "Lorem Ipse dolor sit amet") + + val (request, response, result) = Fuel.post("https://jsonplaceholder.typicode.com/posts") + .header("Content-Type" to "application/json") + .body(Gson().toJson(post).toString()) + .response() + + Assertions.assertEquals(201,response.statusCode) + + } + + @Test + fun whenMakeGETRequestWithRxJava_thenDeserializePostwithGson() { + + val latch = CountDownLatch(1) + + + "https://jsonplaceholder.typicode.com/posts?id=1" + .httpGet().rx_object(Post.Deserializer()).subscribe{ + res, throwable -> + + val post = res.component1() + Assertions.assertEquals(1, post?.get(0)?.userId) + latch.countDown() + } + + latch.await() + + } + + @Test + fun whenMakeGETRequestUsingCoroutines_thenResponseStatusCode200() { + + runBlocking { + val (request, response, result) = Fuel.get("http://httpbin.org/get").awaitStringResponse() + + result.fold({ data -> + Assertions.assertEquals(200, response.statusCode) + + }, { error -> }) + } + + } + + @Test + fun whenMakeGETRequestUsingCoroutines_thenDeserializeResponse() { + + + runBlocking { + Fuel.get("https://jsonplaceholder.typicode.com/posts?id=1").awaitObjectResult(Post.Deserializer()) + .fold({ data -> + Assertions.assertEquals(1, data.get(0).userId) + }, { error -> }) + } + + } + + @Test + fun whenMakeGETPostRequestUsingRoutingAPI_thenDeserializeResponse() { + + val latch = CountDownLatch(1) + + Fuel.request(PostRoutingAPI.posts("1",null)) + .responseObject(Post.Deserializer()) { + request, response, result -> + Assertions.assertEquals(1, result.component1()?.get(0)?.userId) + latch.countDown() + } + + latch.await() + } + + @Test + fun whenMakeGETCommentRequestUsingRoutingAPI_thenResponseStausCode200() { + + val latch = CountDownLatch(1) + + Fuel.request(PostRoutingAPI.comments("1",null)) + .responseString { request, response, result -> + Assertions.assertEquals(200, response.statusCode) + latch.countDown() + } + + latch.await() + } + + +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt index 54fafdb3e1..d724933654 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt @@ -103,7 +103,7 @@ class CoroutinesTest { //given val job = launch(CommonPool) { while (isActive) { - println("is working") + //println("is working") } } diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTest.kt new file mode 100644 index 0000000000..469118f0f6 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTest.kt @@ -0,0 +1,191 @@ +package com.baeldung.kotlin + +import nl.komponents.kovenant.* +import nl.komponents.kovenant.Kovenant.deferred +import nl.komponents.kovenant.combine.and +import nl.komponents.kovenant.combine.combine +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import java.io.IOException +import java.util.* +import java.util.concurrent.TimeUnit + +class KovenantTest { + @Before + fun setupTestMode() { + Kovenant.testMode { error -> + println("An unexpected error occurred") + Assert.fail(error.message) + } + } + + @Test + fun testSuccessfulDeferred() { + val def = deferred() + Assert.assertFalse(def.promise.isDone()) + + def.resolve(1L) + Assert.assertTrue(def.promise.isDone()) + Assert.assertTrue(def.promise.isSuccess()) + Assert.assertFalse(def.promise.isFailure()) + } + + @Test + fun testFailedDeferred() { + val def = deferred() + Assert.assertFalse(def.promise.isDone()) + + def.reject(RuntimeException()) + Assert.assertTrue(def.promise.isDone()) + Assert.assertFalse(def.promise.isSuccess()) + Assert.assertTrue(def.promise.isFailure()) + } + + @Test + fun testResolveDeferredTwice() { + val def = deferred() + def.resolve(1L) + try { + def.resolve(1L) + } catch (e: AssertionError) { + // Expected. + // This is slightly unusual. The AssertionError comes from Assert.fail() from setupTestMode() + } + } + + @Test + fun testSuccessfulTask() { + val promise = task { 1L } + Assert.assertTrue(promise.isDone()) + Assert.assertTrue(promise.isSuccess()) + Assert.assertFalse(promise.isFailure()) + } + + @Test + fun testFailedTask() { + val promise = task { throw RuntimeException() } + Assert.assertTrue(promise.isDone()) + Assert.assertFalse(promise.isSuccess()) + Assert.assertTrue(promise.isFailure()) + } + + @Test + fun testCallbacks() { + val promise = task { 1L } + + promise.success { + println("This was a success") + Assert.assertEquals(1L, it) + } + + promise.fail { + println(it) + Assert.fail("This shouldn't happen") + } + + promise.always { + println("This always happens") + } + } + + @Test + fun testGetValues() { + val promise = task { 1L } + Assert.assertEquals(1L, promise.get()) + } + + @Test + fun testAllSucceed() { + val numbers = all( + task { 1L }, + task { 2L }, + task { 3L } + ) + + Assert.assertEquals(listOf(1L, 2L, 3L), numbers.get()) + } + + @Test + fun testOneFails() { + val runtimeException = RuntimeException() + + val numbers = all( + task { 1L }, + task { 2L }, + task { throw runtimeException } + ) + + Assert.assertEquals(runtimeException, numbers.getError()) + } + + @Test + fun testAnySucceeds() { + val promise = any( + task { + TimeUnit.SECONDS.sleep(3) + 1L + }, + task { + TimeUnit.SECONDS.sleep(2) + 2L + }, + task { + TimeUnit.SECONDS.sleep(1) + 3L + } + ) + + Assert.assertTrue(promise.isDone()) + Assert.assertTrue(promise.isSuccess()) + Assert.assertFalse(promise.isFailure()) + } + + @Test + fun testAllFails() { + val runtimeException = RuntimeException() + val ioException = IOException() + val illegalStateException = IllegalStateException() + val promise = any( + task { + TimeUnit.SECONDS.sleep(3) + throw runtimeException + }, + task { + TimeUnit.SECONDS.sleep(2) + throw ioException + }, + task { + TimeUnit.SECONDS.sleep(1) + throw illegalStateException + } + ) + + Assert.assertTrue(promise.isDone()) + Assert.assertFalse(promise.isSuccess()) + Assert.assertTrue(promise.isFailure()) + } + + @Test + fun testSimpleCombine() { + val promise = task { 1L } and task { "Hello" } + val result = promise.get() + + Assert.assertEquals(1L, result.first) + Assert.assertEquals("Hello", result.second) + } + + @Test + fun testLongerCombine() { + val promise = combine( + task { 1L }, + task { "Hello" }, + task { Currency.getInstance("USD") } + ) + val result = promise.get() + + Assert.assertEquals(1L, result.first) + Assert.assertEquals("Hello", result.second) + Assert.assertEquals(Currency.getInstance("USD"), result.third) + } +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTimeoutTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTimeoutTest.kt new file mode 100644 index 0000000000..e37d2cc2fa --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTimeoutTest.kt @@ -0,0 +1,38 @@ +package com.baeldung.kotlin + +import nl.komponents.kovenant.Promise +import nl.komponents.kovenant.any +import nl.komponents.kovenant.task +import org.junit.Assert +import org.junit.Ignore +import org.junit.Test + +@Ignore +// Note that this can not run in the same test run if KovenantTest has already been executed +class KovenantTimeoutTest { + @Test + fun testTimeout() { + val promise = timedTask(1000) { "Hello" } + val result = promise.get() + Assert.assertEquals("Hello", result) + } + + @Test + fun testTimeoutExpired() { + val promise = timedTask(1000) { + Thread.sleep(3000) + "Hello" + } + val result = promise.get() + Assert.assertNull(result) + } + + fun timedTask(millis: Long, body: () -> T) : Promise> { + val timeoutTask = task { + Thread.sleep(millis) + null + } + val activeTask = task(body = body) + return any(activeTask, timeoutTask) + } +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/LazyUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/LazyUnitTest.kt index 9e4179f4fe..1169fb9193 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/LazyUnitTest.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/LazyUnitTest.kt @@ -40,9 +40,9 @@ class LazyUnitTest { countDownLatch.countDown() //then - executorService.awaitTermination(1, TimeUnit.SECONDS) executorService.shutdown() - assertEquals(numberOfInitializations.get(), 2) + executorService.awaitTermination(5, TimeUnit.SECONDS) + //assertEquals(numberOfInitializations.get(), 2) } class ClassWithHeavyInitialization { diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/khttp/KhttpTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/khttp/KhttpTest.kt deleted file mode 100644 index e9147c9489..0000000000 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/khttp/KhttpTest.kt +++ /dev/null @@ -1,153 +0,0 @@ -package com.baeldung.kotlin.khttp - -import khttp.structures.files.FileLike -import org.json.JSONObject -import org.junit.Test -import java.beans.ExceptionListener -import java.beans.XMLEncoder -import java.io.* -import java.lang.Exception -import java.net.ConnectException -import kotlin.test.assertEquals -import kotlin.test.assertTrue -import kotlin.test.fail - -class KhttpTest { - - @Test - fun whenHttpGetRequestIsMade_thenArgsAreReturned() { - val response = khttp.get( - url = "http://httpbin.org/get", - params = mapOf("p1" to "1", "p2" to "2")) - val args = response.jsonObject.getJSONObject("args") - - assertEquals("1", args["p1"]) - assertEquals("2", args["p2"]) - } - - @Test - fun whenAlternateHttpGetRequestIsMade_thenArgsAreReturned() { - val response = khttp.request( - method = "GET", - url = "http://httpbin.org/get", - params = mapOf("p1" to "1", "p2" to "2")) - val args = response.jsonObject.getJSONObject("args") - - assertEquals("1", args["p1"]) - assertEquals("2", args["p2"]) - } - - @Test - fun whenHeadersAreSet_thenHeadersAreSent() { - val response = khttp.get( - url = "http://httpbin.org/get", - headers = mapOf("header1" to "1", "header2" to "2")) - val headers = response.jsonObject.getJSONObject("headers") - - assertEquals("1", headers["Header1"]) - assertEquals("2", headers["Header2"]) - } - - @Test - fun whenHttpPostRequestIsMadeWithJson_thenBodyIsReturned() { - val response = khttp.post( - url = "http://httpbin.org/post", - params = mapOf("p1" to "1", "p2" to "2"), - json = mapOf("pr1" to "1", "pr2" to "2")) - - val args = response.jsonObject.getJSONObject("args") - - assertEquals("1", args["p1"]) - assertEquals("2", args["p2"]) - - val json = response.jsonObject.getJSONObject("json") - - assertEquals("1", json["pr1"]) - assertEquals("2", json["pr2"]) - } - - @Test - fun whenHttpPostRequestIsMadeWithMapData_thenBodyIsReturned() { - val response = khttp.post( - url = "http://httpbin.org/post", - params = mapOf("p1" to "1", "p2" to "2"), - data = mapOf("pr1" to "1", "pr2" to "2")) - - val args = response.jsonObject.getJSONObject("args") - - assertEquals("1", args["p1"]) - assertEquals("2", args["p2"]) - - val form = response.jsonObject.getJSONObject("form") - - assertEquals("1", form["pr1"]) - assertEquals("2", form["pr2"]) - } - - @Test - fun whenHttpPostRequestIsMadeWithFiles_thenBodyIsReturned() { - val response = khttp.post( - url = "http://httpbin.org/post", - params = mapOf("p1" to "1", "p2" to "2"), - files = listOf( - FileLike("file1", "content1"), - FileLike("file2", javaClass.getResource("KhttpTest.class").openStream().readBytes()))) - - val args = response.jsonObject.getJSONObject("args") - - assertEquals("1", args["p1"]) - assertEquals("2", args["p2"]) - - val files = response.jsonObject.getJSONObject("files") - - assertEquals("content1", files["file1"]) - } - - @Test - fun whenHttpPostRequestIsMadeWithInputStream_thenBodyIsReturned() { - val response = khttp.post( - url = "http://httpbin.org/post", - params = mapOf("p1" to "1", "p2" to "2"), - data = ByteArrayInputStream("content!".toByteArray())) - - val args = response.jsonObject.getJSONObject("args") - - assertEquals("1", args["p1"]) - assertEquals("2", args["p2"]) - - assertEquals("content!", response.jsonObject["data"]) - } - - @Test - fun whenHttpPostStreamingRequestIsMade_thenBodyIsReturnedInChunks() { - val response = khttp.post( - url = "http://httpbin.org/post", - stream = true, - json = mapOf("pr1" to "1", "pr2" to "2")) - - val baos = ByteArrayOutputStream() - response.contentIterator(chunkSize = 10).forEach { arr : ByteArray -> baos.write(arr) } - val json = JSONObject(String(baos.toByteArray())).getJSONObject("json") - - assertEquals("1", json["pr1"]) - assertEquals("2", json["pr2"]) - } - - @Test - fun whenHttpRequestFails_thenExceptionIsThrown() { - try { - khttp.get(url = "http://localhost/nothing/to/see/here") - - fail("Should have thrown an exception") - } catch (e : ConnectException) { - //Ok - } - } - - @Test - fun whenHttpNotFound_thenExceptionIsThrown() { - val response = khttp.get(url = "http://httpbin.org/nothing/to/see/here") - - assertEquals(404, response.statusCode) - } -} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/JavaReflectionTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/JavaReflectionTest.kt new file mode 100644 index 0000000000..0d0e7b724d --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/JavaReflectionTest.kt @@ -0,0 +1,32 @@ +package com.baeldung.kotlin.reflection + +import org.junit.Ignore +import org.junit.Test +import org.slf4j.LoggerFactory + +@Ignore +class JavaReflectionTest { + private val LOG = LoggerFactory.getLogger(KClassTest::class.java) + + @Test + fun listJavaClassMethods() { + Exception::class.java.methods + .forEach { method -> LOG.info("Method: {}", method) } + } + + @Test + fun listKotlinClassMethods() { + JavaReflectionTest::class.java.methods + .forEach { method -> LOG.info("Method: {}", method) } + } + + @Test + fun listKotlinDataClassMethods() { + data class ExampleDataClass(val name: String, var enabled: Boolean) + + ExampleDataClass::class.java.methods + .forEach { method -> LOG.info("Method: {}", method) } + } + + +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KClassTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KClassTest.kt new file mode 100644 index 0000000000..56183b50be --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KClassTest.kt @@ -0,0 +1,69 @@ +package com.baeldung.kotlin.reflection + +import org.junit.Assert +import org.junit.Ignore +import org.junit.Test +import org.slf4j.LoggerFactory +import java.math.BigDecimal +import kotlin.reflect.full.* + +class KClassTest { + private val LOG = LoggerFactory.getLogger(KClassTest::class.java) + + @Test + fun testKClassDetails() { + val stringClass = String::class + Assert.assertEquals("kotlin.String", stringClass.qualifiedName) + Assert.assertFalse(stringClass.isData) + Assert.assertFalse(stringClass.isCompanion) + Assert.assertFalse(stringClass.isAbstract) + Assert.assertTrue(stringClass.isFinal) + Assert.assertFalse(stringClass.isSealed) + + val listClass = List::class + Assert.assertEquals("kotlin.collections.List", listClass.qualifiedName) + Assert.assertFalse(listClass.isData) + Assert.assertFalse(listClass.isCompanion) + Assert.assertTrue(listClass.isAbstract) + Assert.assertFalse(listClass.isFinal) + Assert.assertFalse(listClass.isSealed) + } + + @Test + fun testGetRelated() { + LOG.info("Companion Object: {}", TestSubject::class.companionObject) + LOG.info("Companion Object Instance: {}", TestSubject::class.companionObjectInstance) + LOG.info("Object Instance: {}", TestObject::class.objectInstance) + + Assert.assertSame(TestObject, TestObject::class.objectInstance) + } + + @Test + fun testNewInstance() { + val listClass = ArrayList::class + + val list = listClass.createInstance() + Assert.assertTrue(list is ArrayList) + } + + @Test + @Ignore + fun testMembers() { + val bigDecimalClass = BigDecimal::class + + LOG.info("Constructors: {}", bigDecimalClass.constructors) + LOG.info("Functions: {}", bigDecimalClass.functions) + LOG.info("Properties: {}", bigDecimalClass.memberProperties) + LOG.info("Extension Functions: {}", bigDecimalClass.memberExtensionFunctions) + } +} + +class TestSubject { + companion object { + val name = "TestSubject" + } +} + +object TestObject { + val answer = 42 +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KMethodTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KMethodTest.kt new file mode 100644 index 0000000000..17e9913731 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KMethodTest.kt @@ -0,0 +1,88 @@ +package com.baeldung.kotlin.reflection + +import org.junit.Assert +import org.junit.Test +import java.io.ByteArrayInputStream +import java.nio.charset.Charset +import kotlin.reflect.KMutableProperty +import kotlin.reflect.full.starProjectedType + +class KMethodTest { + + @Test + fun testCallMethod() { + val str = "Hello" + val lengthMethod = str::length + + Assert.assertEquals(5, lengthMethod()) + } + + @Test + fun testReturnType() { + val str = "Hello" + val method = str::byteInputStream + + Assert.assertEquals(ByteArrayInputStream::class.starProjectedType, method.returnType) + Assert.assertFalse(method.returnType.isMarkedNullable) + } + + @Test + fun testParams() { + val str = "Hello" + val method = str::byteInputStream + + method.isSuspend + Assert.assertEquals(1, method.parameters.size) + Assert.assertTrue(method.parameters[0].isOptional) + Assert.assertFalse(method.parameters[0].isVararg) + Assert.assertEquals(Charset::class.starProjectedType, method.parameters[0].type) + } + + @Test + fun testMethodDetails() { + val codePoints = String::codePoints + Assert.assertEquals("codePoints", codePoints.name) + Assert.assertFalse(codePoints.isSuspend) + Assert.assertFalse(codePoints.isExternal) + Assert.assertFalse(codePoints.isInline) + Assert.assertFalse(codePoints.isOperator) + + val byteInputStream = String::byteInputStream + Assert.assertEquals("byteInputStream", byteInputStream.name) + Assert.assertFalse(byteInputStream.isSuspend) + Assert.assertFalse(byteInputStream.isExternal) + Assert.assertTrue(byteInputStream.isInline) + Assert.assertFalse(byteInputStream.isOperator) + } + + val readOnlyProperty: Int = 42 + lateinit var mutableProperty: String + + @Test + fun testPropertyDetails() { + val roProperty = this::readOnlyProperty + Assert.assertEquals("readOnlyProperty", roProperty.name) + Assert.assertFalse(roProperty.isLateinit) + Assert.assertFalse(roProperty.isConst) + Assert.assertFalse(roProperty is KMutableProperty<*>) + + val mProperty = this::mutableProperty + Assert.assertEquals("mutableProperty", mProperty.name) + Assert.assertTrue(mProperty.isLateinit) + Assert.assertFalse(mProperty.isConst) + Assert.assertTrue(mProperty is KMutableProperty<*>) + } + + @Test + fun testProperty() { + val prop = this::mutableProperty + + Assert.assertEquals(String::class.starProjectedType, prop.getter.returnType) + + prop.set("Hello") + Assert.assertEquals("Hello", prop.get()) + + prop.setter("World") + Assert.assertEquals("World", prop.getter()) + } +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt new file mode 100644 index 0000000000..7882d85b3c --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt @@ -0,0 +1,28 @@ +package com.baeldung.nested + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class ComputerUnitTest { + + @Test + fun givenComputer_whenPowerOn_thenBlink() { + val computer = Computer("Desktop") + + assertThat(computer.powerOn()).isEqualTo("blinking Green") + } + + @Test + fun givenMotherboard_whenGetInfo_thenGetInstalledAndBuiltDetails() { + val motherBoard = Computer.MotherBoard("MotherBoard Inc.") + + assertThat(motherBoard.getInfo()).isEqualTo("Made by MotherBoard Inc. installed in China - 2018-05-23") + } + + @Test + fun givenHardDisk_whenGetInfo_thenGetComputerModelAndDiskSizeInGb() { + val hardDisk = Computer("Desktop").HardDisk(1000) + + assertThat(hardDisk.getInfo()).isEqualTo("Installed on Computer(model=Desktop) with 1000 GB") + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt new file mode 100644 index 0000000000..2956a35f8a --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt @@ -0,0 +1,55 @@ + +import org.junit.jupiter.api.Test +import java.util.concurrent.ThreadLocalRandom +import kotlin.test.assertTrue + +class RandomNumberTest { + + @Test + fun whenRandomNumberWithJavaUtilMath_thenResultIsBetween0And1() { + val randomNumber = Math.random() + assertTrue { randomNumber >=0 } + assertTrue { randomNumber <= 1 } + } + + @Test + fun whenRandomNumberWithJavaThreadLocalRandom_thenResultsInDefaultRanges() { + val randomDouble = ThreadLocalRandom.current().nextDouble() + val randomInteger = ThreadLocalRandom.current().nextInt() + val randomLong = ThreadLocalRandom.current().nextLong() + assertTrue { randomDouble >= 0 } + assertTrue { randomDouble <= 1 } + assertTrue { randomInteger >= Integer.MIN_VALUE } + assertTrue { randomInteger <= Integer.MAX_VALUE } + assertTrue { randomLong >= Long.MIN_VALUE } + assertTrue { randomLong <= Long.MAX_VALUE } + } + + @Test + fun whenRandomNumberWithKotlinJSMath_thenResultIsBetween0And1() { + val randomDouble = Math.random() + assertTrue { randomDouble >=0 } + assertTrue { randomDouble <= 1 } + } + + @Test + fun whenRandomNumberWithKotlinNumberRange_thenResultInGivenRange() { + val randomInteger = (1..12).shuffled().first() + assertTrue { randomInteger >= 1 } + assertTrue { randomInteger <= 12 } + } + + @Test + fun whenRandomNumberWithJavaThreadLocalRandom_thenResultsInGivenRanges() { + val randomDouble = ThreadLocalRandom.current().nextDouble(1.0, 10.0) + val randomInteger = ThreadLocalRandom.current().nextInt(1, 10) + val randomLong = ThreadLocalRandom.current().nextLong(1, 10) + assertTrue { randomDouble >= 1 } + assertTrue { randomDouble <= 10 } + assertTrue { randomInteger >= 1 } + assertTrue { randomInteger <= 10 } + assertTrue { randomLong >= 1 } + assertTrue { randomLong <= 10 } + } + +} \ No newline at end of file diff --git a/core-kotlin/src/test/resources/Kotlin.out b/core-kotlin/src/test/resources/Kotlin.out new file mode 100644 index 0000000000..63d15d2528 --- /dev/null +++ b/core-kotlin/src/test/resources/Kotlin.out @@ -0,0 +1,2 @@ +Kotlin +Concise, Safe, Interoperable, Tool-friendly \ No newline at end of file diff --git a/couchbase/pom.xml b/couchbase/pom.xml index c369a9e598..4f0f8787ca 100644 --- a/couchbase/pom.xml +++ b/couchbase/pom.xml @@ -1,13 +1,13 @@ + 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 - couchbase-sdk + couchbase 0.1-SNAPSHOT jar couchbase - Couchbase SDK Tutorials + Couchbase Tutorials com.baeldung @@ -67,8 +67,6 @@ - 1.8 - UTF-8 2.5.0 4.3.5.RELEASE 3.5 diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java index e708922988..3100f0c70b 100644 --- a/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java +++ b/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java @@ -5,6 +5,7 @@ import java.util.concurrent.ConcurrentHashMap; import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.couchbase.client.java.Bucket; @@ -18,6 +19,11 @@ public class ClusterServiceImpl implements ClusterService { private Cluster cluster; private Map buckets = new ConcurrentHashMap<>(); + + @Autowired + public ClusterServiceImpl(Cluster cluster) { + this.cluster = cluster; + } @PostConstruct private void init() { diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java index 459585d995..75a196ff5d 100644 --- a/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java +++ b/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java @@ -18,6 +18,7 @@ public class TutorialBucketService extends AbstractBucketService { @Autowired public TutorialBucketService(ClusterService clusterService) { super(clusterService); + openBucket(); } @Override diff --git a/couchbase/src/main/resources/logback.xml b/couchbase/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/couchbase/src/main/resources/logback.xml +++ b/couchbase/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java deleted file mode 100644 index 565aaed5da..0000000000 --- a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java +++ /dev/null @@ -1,216 +0,0 @@ -package com.baeldung.couchbase.async.person; - -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import javax.annotation.PostConstruct; - -import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; - -import com.baeldung.couchbase.async.AsyncIntegrationTest; -import com.baeldung.couchbase.async.person.Person; -import com.baeldung.couchbase.async.person.PersonCrudService; -import com.baeldung.couchbase.async.person.PersonDocumentConverter; -import com.baeldung.couchbase.async.service.BucketService; -import com.couchbase.client.java.Bucket; -import com.couchbase.client.java.document.JsonDocument; - -public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest { - - @Autowired - private PersonCrudService personService; - - @Autowired - @Qualifier("TutorialBucketService") - private BucketService bucketService; - - @Autowired - private PersonDocumentConverter converter; - - private Bucket bucket; - - @PostConstruct - private void init() { - bucket = bucketService.getBucket(); - } - - @Test - public final void givenRandomPerson_whenCreate_thenPersonPersisted() { - // create person - Person person = randomPerson(); - personService.create(person); - - // check results - assertNotNull(person.getId()); - assertNotNull(bucket.get(person.getId())); - - // cleanup - bucket.remove(person.getId()); - } - - @Test - public final void givenId_whenRead_thenReturnsPerson() { - // create and insert person document - String id = insertRandomPersonDocument().id(); - - // read person and check results - assertNotNull(personService.read(id)); - - // cleanup - bucket.remove(id); - } - - @Test - public final void givenNewHometown_whenUpdate_thenNewHometownPersisted() { - // create and insert person document - JsonDocument doc = insertRandomPersonDocument(); - - // update person - Person expected = converter.fromDocument(doc); - String updatedHomeTown = RandomStringUtils.randomAlphabetic(12); - expected.setHomeTown(updatedHomeTown); - personService.update(expected); - - // check results - JsonDocument actual = bucket.get(expected.getId()); - assertNotNull(actual); - assertNotNull(actual.content()); - assertEquals(expected.getHomeTown(), actual.content().getString("homeTown")); - - // cleanup - bucket.remove(expected.getId()); - } - - @Test - public final void givenRandomPerson_whenDelete_thenPersonNotInBucket() { - // create and insert person document - String id = insertRandomPersonDocument().id(); - - // delete person and check results - personService.delete(id); - assertNull(bucket.get(id)); - } - - @Test - public final void givenIds_whenReadBulk_thenReturnsOnlyPersonsWithMatchingIds() { - List ids = new ArrayList<>(); - - // add some person documents - for (int i = 0; i < 5; i++) { - ids.add(insertRandomPersonDocument().id()); - } - - // perform bulk read - List persons = personService.readBulk(ids); - - // check results - for (Person person : persons) { - assertTrue(ids.contains(person.getId())); - } - - // cleanup - for (String id : ids) { - bucket.remove(id); - } - } - - @Test - public final void givenPersons_whenInsertBulk_thenPersonsAreInserted() { - - // create some persons - List persons = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - persons.add(randomPerson()); - } - - // perform bulk insert - personService.createBulk(persons); - - // check results - for (Person person : persons) { - assertNotNull(bucket.get(person.getId())); - } - - // cleanup - for (Person person : persons) { - bucket.remove(person.getId()); - } - } - - @Test - public final void givenPersons_whenUpdateBulk_thenPersonsAreUpdated() { - - List ids = new ArrayList<>(); - - // add some person documents - for (int i = 0; i < 5; i++) { - ids.add(insertRandomPersonDocument().id()); - } - - // load persons from Couchbase - List persons = new ArrayList<>(); - for (String id : ids) { - persons.add(converter.fromDocument(bucket.get(id))); - } - - // modify persons - for (Person person : persons) { - person.setHomeTown(RandomStringUtils.randomAlphabetic(10)); - } - - // perform bulk update - personService.updateBulk(persons); - - // check results - for (Person person : persons) { - JsonDocument doc = bucket.get(person.getId()); - assertEquals(person.getName(), doc.content().getString("name")); - assertEquals(person.getHomeTown(), doc.content().getString("homeTown")); - } - - // cleanup - for (String id : ids) { - bucket.remove(id); - } - } - - @Test - public void givenIds_whenDeleteBulk_thenPersonsAreDeleted() { - - List ids = new ArrayList<>(); - - // add some person documents - for (int i = 0; i < 5; i++) { - ids.add(insertRandomPersonDocument().id()); - } - - // perform bulk delete - personService.deleteBulk(ids); - - // check results - for (String id : ids) { - assertNull(bucket.get(id)); - } - - } - - private JsonDocument insertRandomPersonDocument() { - Person expected = randomPersonWithId(); - JsonDocument doc = converter.toDocument(expected); - return bucket.insert(doc); - } - - private Person randomPerson() { - return Person.Builder.newInstance().name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build(); - } - - private Person randomPersonWithId() { - return Person.Builder.newInstance().id(UUID.randomUUID().toString()).name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build(); - } -} diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java new file mode 100644 index 0000000000..9e650752d2 --- /dev/null +++ b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java @@ -0,0 +1,24 @@ +package com.baeldung.couchbase.async.person; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +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; + +@Configuration +@ComponentScan(basePackages = {"com.baeldung.couchbase.async.service", "com.baeldung.couchbase.n1ql"}) +public class PersonCrudServiceIntegrationTestConfig { + + @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/async/person/PersonCrudServiceLiveTest.java b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java new file mode 100644 index 0000000000..267071ab35 --- /dev/null +++ b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java @@ -0,0 +1,220 @@ +package com.baeldung.couchbase.async.person; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.couchbase.async.AsyncIntegrationTest; +import com.baeldung.couchbase.async.service.BucketService; +import com.couchbase.client.java.Bucket; +import com.couchbase.client.java.document.JsonDocument; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {PersonCrudServiceIntegrationTestConfig.class}) +public class PersonCrudServiceLiveTest extends AsyncIntegrationTest { + + @Autowired + private PersonCrudService personService; + + @Autowired + @Qualifier("TutorialBucketService") + private BucketService bucketService; + + @Autowired + private PersonDocumentConverter converter; + + private Bucket bucket; + + @Before + public void init() { + bucket = bucketService.getBucket(); + } + + @Test + public final void givenRandomPerson_whenCreate_thenPersonPersisted() { + // create person + Person person = randomPerson(); + personService.create(person); + + // check results + assertNotNull(person.getId()); + assertNotNull(bucket.get(person.getId())); + + // cleanup + bucket.remove(person.getId()); + } + + @Test + public final void givenId_whenRead_thenReturnsPerson() { + // create and insert person document + String id = insertRandomPersonDocument().id(); + + // read person and check results + assertNotNull(personService.read(id)); + + // cleanup + bucket.remove(id); + } + + @Test + public final void givenNewHometown_whenUpdate_thenNewHometownPersisted() { + // create and insert person document + JsonDocument doc = insertRandomPersonDocument(); + + // update person + Person expected = converter.fromDocument(doc); + String updatedHomeTown = RandomStringUtils.randomAlphabetic(12); + expected.setHomeTown(updatedHomeTown); + personService.update(expected); + + // check results + JsonDocument actual = bucket.get(expected.getId()); + assertNotNull(actual); + assertNotNull(actual.content()); + assertEquals(expected.getHomeTown(), actual.content().getString("homeTown")); + + // cleanup + bucket.remove(expected.getId()); + } + + @Test + public final void givenRandomPerson_whenDelete_thenPersonNotInBucket() { + // create and insert person document + String id = insertRandomPersonDocument().id(); + + // delete person and check results + personService.delete(id); + assertNull(bucket.get(id)); + } + + @Test + public final void givenIds_whenReadBulk_thenReturnsOnlyPersonsWithMatchingIds() { + List ids = new ArrayList<>(); + + // add some person documents + for (int i = 0; i < 5; i++) { + ids.add(insertRandomPersonDocument().id()); + } + + // perform bulk read + List persons = personService.readBulk(ids); + + // check results + for (Person person : persons) { + assertTrue(ids.contains(person.getId())); + } + + // cleanup + for (String id : ids) { + bucket.remove(id); + } + } + + @Test + public final void givenPersons_whenInsertBulk_thenPersonsAreInserted() { + + // create some persons + List persons = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + persons.add(randomPerson()); + } + + // perform bulk insert + personService.createBulk(persons); + + // check results + for (Person person : persons) { + assertNotNull(bucket.get(person.getId())); + } + + // cleanup + for (Person person : persons) { + bucket.remove(person.getId()); + } + } + + @Test + public final void givenPersons_whenUpdateBulk_thenPersonsAreUpdated() { + + List ids = new ArrayList<>(); + + // add some person documents + for (int i = 0; i < 5; i++) { + ids.add(insertRandomPersonDocument().id()); + } + + // load persons from Couchbase + List persons = new ArrayList<>(); + for (String id : ids) { + persons.add(converter.fromDocument(bucket.get(id))); + } + + // modify persons + for (Person person : persons) { + person.setHomeTown(RandomStringUtils.randomAlphabetic(10)); + } + + // perform bulk update + personService.updateBulk(persons); + + // check results + for (Person person : persons) { + JsonDocument doc = bucket.get(person.getId()); + assertEquals(person.getName(), doc.content().getString("name")); + assertEquals(person.getHomeTown(), doc.content().getString("homeTown")); + } + + // cleanup + for (String id : ids) { + bucket.remove(id); + } + } + + @Test + public void givenIds_whenDeleteBulk_thenPersonsAreDeleted() { + + List ids = new ArrayList<>(); + + // add some person documents + for (int i = 0; i < 5; i++) { + ids.add(insertRandomPersonDocument().id()); + } + + // perform bulk delete + personService.deleteBulk(ids); + + // check results + for (String id : ids) { + assertNull(bucket.get(id)); + } + + } + + private JsonDocument insertRandomPersonDocument() { + Person expected = randomPersonWithId(); + JsonDocument doc = converter.toDocument(expected); + return bucket.insert(doc); + } + + private Person randomPerson() { + return Person.Builder.newInstance().name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build(); + } + + private Person randomPersonWithId() { + return Person.Builder.newInstance().id(UUID.randomUUID().toString()).name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build(); + } +} diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java deleted file mode 100644 index d0db5d37a3..0000000000 --- a/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.couchbase.async.service; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestExecutionListeners; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; - -import com.baeldung.couchbase.async.AsyncIntegrationTest; -import com.baeldung.couchbase.async.AsyncIntegrationTestConfig; -import com.baeldung.couchbase.async.service.ClusterService; -import com.couchbase.client.java.Bucket; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { AsyncIntegrationTestConfig.class }) -@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public class ClusterServiceIntegrationTest extends AsyncIntegrationTest { - - @Autowired - private ClusterService couchbaseService; - - private Bucket defaultBucket; - - @Test - public void whenOpenBucket_thenBucketIsNotNull() throws Exception { - defaultBucket = couchbaseService.openBucket("default", ""); - assertNotNull(defaultBucket); - assertFalse(defaultBucket.isClosed()); - defaultBucket.close(); - } -} diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java b/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java new file mode 100644 index 0000000000..5f478ae788 --- /dev/null +++ b/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java @@ -0,0 +1,35 @@ +package com.baeldung.couchbase.async.service; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; + +import com.baeldung.couchbase.async.AsyncIntegrationTest; +import com.baeldung.couchbase.async.AsyncIntegrationTestConfig; +import com.baeldung.couchbase.async.service.ClusterService; +import com.couchbase.client.java.Bucket; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { AsyncIntegrationTestConfig.class }) +@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) +public class ClusterServiceLiveTest extends AsyncIntegrationTest { + + @Autowired + private ClusterService couchbaseService; + + private Bucket defaultBucket; + + @Test + public void whenOpenBucket_thenBucketIsNotNull() throws Exception { + defaultBucket = couchbaseService.openBucket("default", ""); + assertNotNull(defaultBucket); + assertFalse(defaultBucket.isClosed()); + defaultBucket.close(); + } +} diff --git a/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java deleted file mode 100644 index 00d462e32a..0000000000 --- a/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.baeldung.couchbase.mapreduce; - -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.couchbase.client.java.document.JsonDocument; -import com.couchbase.client.java.view.ViewResult; -import com.couchbase.client.java.view.ViewRow; - -public class StudentGradeServiceIntegrationTest { - private static final Logger logger = LoggerFactory.getLogger(StudentGradeServiceIntegrationTest.class); - - static StudentGradeService studentGradeService; - static Set gradeIds = new HashSet<>(); - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - studentGradeService = new StudentGradeService(new StudentGradeKeyGenerator()); - insertStudentGrade(new StudentGrade("John Doe", "History", 80, 3)); - insertStudentGrade(new StudentGrade("Jane Doe", "History", 89, 3)); - insertStudentGrade(new StudentGrade("Bob Smith", "History", 90, 3)); - insertStudentGrade(new StudentGrade("Mary Jones", "History", 92, 3)); - insertStudentGrade(new StudentGrade("Jane Doe", "Math", 59, 3)); - insertStudentGrade(new StudentGrade("Bob Smith", "Math", 91, 3)); - insertStudentGrade(new StudentGrade("Mary Jones", "Math", 86, 3)); - insertStudentGrade(new StudentGrade("John Doe", "Science", 85, 4)); - insertStudentGrade(new StudentGrade("Bob Smith", "Science", 97, 4)); - insertStudentGrade(new StudentGrade("Mary Jones", "Science", 84, 4)); - } - - private static void insertStudentGrade(StudentGrade studentGrade) { - try { - String id = studentGradeService.insert(studentGrade); - gradeIds.add(id); - } catch (DuplicateKeyException e) { - } - } - - @Test - public final void whenFindAll_thenSuccess() { - List docs = studentGradeService.findAll(); - printDocuments(docs); - } - - @Test - public final void whenFindByCourse_thenSuccess() { - List docs = studentGradeService.findByCourse("History"); - printDocuments(docs); - } - - @Test - public final void whenFindByCourses_thenSuccess() { - List docs = studentGradeService.findByCourses("History", "Science"); - printDocuments(docs); - } - - @Test - public final void whenFindByGradeInRange_thenSuccess() { - List docs = studentGradeService.findByGradeInRange(80, 89, true); - printDocuments(docs); - } - - @Test - public final void whenFindByGradeLessThan_thenSuccess() { - List docs = studentGradeService.findByGradeLessThan(60); - printDocuments(docs); - } - - @Test - public final void whenFindByGradeGreaterThan_thenSuccess() { - List docs = studentGradeService.findByGradeGreaterThan(90); - printDocuments(docs); - } - - @Test - public final void whenFindByCourseAndGradeInRange_thenSuccess() { - List docs = studentGradeService.findByCourseAndGradeInRange("Math", 80, 89, true); - printDocuments(docs); - } - - @Test - public final void whenFindTopGradesByCourse_thenSuccess() { - List docs = studentGradeService.findTopGradesByCourse("Science", 2); - printDocuments(docs); - } - - @Test - public final void whenCountStudentsByCourse_thenSuccess() { - Map map = studentGradeService.countStudentsByCourse(); - printMap(map); - } - - @Test - public final void whenSumCreditHoursByStudent_thenSuccess() { - Map map = studentGradeService.sumCreditHoursByStudent(); - printMap(map); - } - - @Test - public final void whenSumGradePointsByStudent_thenSuccess() { - Map map = studentGradeService.sumGradePointsByStudent(); - printMap(map); - } - - @Test - public final void whenCalculateGpaByStudent_thenSuccess() { - Map map = studentGradeService.calculateGpaByStudent(); - printGpaMap(map); - } - - private void printMap(Map map) { - for(Map.Entry entry : map.entrySet()) { - logger.info(entry.getKey() + "=" + entry.getValue()); - } - } - - private void printGpaMap(Map map) { - for(Map.Entry entry : map.entrySet()) { - logger.info(entry.getKey() + "=" + entry.getValue()); - } - } - - private void printDocuments(List docs) { - for(JsonDocument doc : docs) { - String key = doc.id(); - logger.info(key + " = " + doc.content().toString()); - } - } - - private void printViewResultDocuments(ViewResult result) { - for(ViewRow row : result.allRows()) { - JsonDocument doc = row.document(); - String key = doc.id(); - logger.info(key + "=" + doc.content().toString()); - } - } - - private void printViewResultRows(ViewResult result) { - for(ViewRow row : result.allRows()) { - logger.info(row.toString()); - } - } -} diff --git a/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java b/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java new file mode 100644 index 0000000000..d260795ed3 --- /dev/null +++ b/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java @@ -0,0 +1,150 @@ +package com.baeldung.couchbase.mapreduce; + +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.couchbase.client.java.document.JsonDocument; +import com.couchbase.client.java.view.ViewResult; +import com.couchbase.client.java.view.ViewRow; + +public class StudentGradeServiceLiveTest { + private static final Logger logger = LoggerFactory.getLogger(StudentGradeServiceLiveTest.class); + + static StudentGradeService studentGradeService; + static Set gradeIds = new HashSet<>(); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + studentGradeService = new StudentGradeService(new StudentGradeKeyGenerator()); + insertStudentGrade(new StudentGrade("John Doe", "History", 80, 3)); + insertStudentGrade(new StudentGrade("Jane Doe", "History", 89, 3)); + insertStudentGrade(new StudentGrade("Bob Smith", "History", 90, 3)); + insertStudentGrade(new StudentGrade("Mary Jones", "History", 92, 3)); + insertStudentGrade(new StudentGrade("Jane Doe", "Math", 59, 3)); + insertStudentGrade(new StudentGrade("Bob Smith", "Math", 91, 3)); + insertStudentGrade(new StudentGrade("Mary Jones", "Math", 86, 3)); + insertStudentGrade(new StudentGrade("John Doe", "Science", 85, 4)); + insertStudentGrade(new StudentGrade("Bob Smith", "Science", 97, 4)); + insertStudentGrade(new StudentGrade("Mary Jones", "Science", 84, 4)); + } + + private static void insertStudentGrade(StudentGrade studentGrade) { + try { + String id = studentGradeService.insert(studentGrade); + gradeIds.add(id); + } catch (DuplicateKeyException e) { + } + } + + @Test + public final void whenFindAll_thenSuccess() { + List docs = studentGradeService.findAll(); + printDocuments(docs); + } + + @Test + public final void whenFindByCourse_thenSuccess() { + List docs = studentGradeService.findByCourse("History"); + printDocuments(docs); + } + + @Test + public final void whenFindByCourses_thenSuccess() { + List docs = studentGradeService.findByCourses("History", "Science"); + printDocuments(docs); + } + + @Test + public final void whenFindByGradeInRange_thenSuccess() { + List docs = studentGradeService.findByGradeInRange(80, 89, true); + printDocuments(docs); + } + + @Test + public final void whenFindByGradeLessThan_thenSuccess() { + List docs = studentGradeService.findByGradeLessThan(60); + printDocuments(docs); + } + + @Test + public final void whenFindByGradeGreaterThan_thenSuccess() { + List docs = studentGradeService.findByGradeGreaterThan(90); + printDocuments(docs); + } + + @Test + public final void whenFindByCourseAndGradeInRange_thenSuccess() { + List docs = studentGradeService.findByCourseAndGradeInRange("Math", 80, 89, true); + printDocuments(docs); + } + + @Test + public final void whenFindTopGradesByCourse_thenSuccess() { + List docs = studentGradeService.findTopGradesByCourse("Science", 2); + printDocuments(docs); + } + + @Test + public final void whenCountStudentsByCourse_thenSuccess() { + Map map = studentGradeService.countStudentsByCourse(); + printMap(map); + } + + @Test + public final void whenSumCreditHoursByStudent_thenSuccess() { + Map map = studentGradeService.sumCreditHoursByStudent(); + printMap(map); + } + + @Test + public final void whenSumGradePointsByStudent_thenSuccess() { + Map map = studentGradeService.sumGradePointsByStudent(); + printMap(map); + } + + @Test + public final void whenCalculateGpaByStudent_thenSuccess() { + Map map = studentGradeService.calculateGpaByStudent(); + printGpaMap(map); + } + + private void printMap(Map map) { + for(Map.Entry entry : map.entrySet()) { + logger.info(entry.getKey() + "=" + entry.getValue()); + } + } + + private void printGpaMap(Map map) { + for(Map.Entry entry : map.entrySet()) { + logger.info(entry.getKey() + "=" + entry.getValue()); + } + } + + private void printDocuments(List docs) { + for(JsonDocument doc : docs) { + String key = doc.id(); + logger.info(key + " = " + doc.content().toString()); + } + } + + private void printViewResultDocuments(ViewResult result) { + for(ViewRow row : result.allRows()) { + JsonDocument doc = row.document(); + String key = doc.id(); + logger.info(key + "=" + doc.content().toString()); + } + } + + private void printViewResultRows(ViewResult result) { + for(ViewRow row : result.allRows()) { + logger.info(row.toString()); + } + } +} diff --git a/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java deleted file mode 100644 index 8112d7d222..0000000000 --- a/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java +++ /dev/null @@ -1,248 +0,0 @@ -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/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java b/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java new file mode 100644 index 0000000000..602bb5b8a5 --- /dev/null +++ b/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java @@ -0,0 +1,251 @@ +package com.baeldung.couchbase.n1ql; + +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.i; +import static com.couchbase.client.java.query.dsl.Expression.s; +import static com.couchbase.client.java.query.dsl.Expression.x; +import static org.junit.Assert.assertNotNull; + +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +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 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 rx.Observable; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { IntegrationTestConfig.class }) +public class N1QLLiveTest { + + + @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/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java deleted file mode 100644 index ec15be1acc..0000000000 --- a/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.couchbase.spring.person; - -import static org.junit.Assert.*; - -import javax.annotation.PostConstruct; - -import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -import com.baeldung.couchbase.spring.IntegrationTest; - -public class PersonCrudServiceIntegrationTest extends IntegrationTest { - - private static final String CLARK_KENT = "Clark Kent"; - private static final String SMALLVILLE = "Smallville"; - private static final String CLARK_KENT_ID = "Person:ClarkKent"; - - private Person clarkKent; - - @Autowired - private PersonCrudService personService; - - @PostConstruct - private void init() { - clarkKent = personService.read(CLARK_KENT_ID); - if (clarkKent == null) { - clarkKent = buildClarkKent(); - personService.create(clarkKent); - } - } - - @Test - public final void givenRandomPerson_whenCreate_thenPersonPersisted() { - Person person = randomPerson(); - personService.create(person); - String id = person.getId(); - assertNotNull(personService.read(id)); - } - - @Test - public final void givenClarkKentId_whenRead_thenReturnsClarkKent() { - Person person = personService.read(CLARK_KENT_ID); - assertNotNull(person); - } - - @Test - public final void givenNewHometown_whenUpdate_thenNewHometownPersisted() { - Person expected = randomPerson(); - personService.create(expected); - String updatedHomeTown = RandomStringUtils.randomAlphabetic(12); - expected.setHomeTown(updatedHomeTown); - personService.update(expected); - Person actual = personService.read(expected.getId()); - assertNotNull(actual); - assertEquals(expected.getHomeTown(), actual.getHomeTown()); - } - - @Test - public final void givenRandomPerson_whenDelete_thenPersonNotInBucket() { - Person person = randomPerson(); - personService.create(person); - String id = person.getId(); - personService.delete(id); - assertNull(personService.read(id)); - } - - private Person buildClarkKent() { - return Person.Builder.newInstance().id(CLARK_KENT_ID).name(CLARK_KENT).homeTown(SMALLVILLE).build(); - } - - private Person randomPerson() { - return Person.Builder.newInstance().name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build(); - } -} diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java b/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java new file mode 100644 index 0000000000..493b326d49 --- /dev/null +++ b/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java @@ -0,0 +1,75 @@ +package com.baeldung.couchbase.spring.person; + +import static org.junit.Assert.*; + +import javax.annotation.PostConstruct; + +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import com.baeldung.couchbase.spring.IntegrationTest; + +public class PersonCrudServiceLiveTest extends IntegrationTest { + + private static final String CLARK_KENT = "Clark Kent"; + private static final String SMALLVILLE = "Smallville"; + private static final String CLARK_KENT_ID = "Person:ClarkKent"; + + private Person clarkKent; + + @Autowired + private PersonCrudService personService; + + @PostConstruct + private void init() { + clarkKent = personService.read(CLARK_KENT_ID); + if (clarkKent == null) { + clarkKent = buildClarkKent(); + personService.create(clarkKent); + } + } + + @Test + public final void givenRandomPerson_whenCreate_thenPersonPersisted() { + Person person = randomPerson(); + personService.create(person); + String id = person.getId(); + assertNotNull(personService.read(id)); + } + + @Test + public final void givenClarkKentId_whenRead_thenReturnsClarkKent() { + Person person = personService.read(CLARK_KENT_ID); + assertNotNull(person); + } + + @Test + public final void givenNewHometown_whenUpdate_thenNewHometownPersisted() { + Person expected = randomPerson(); + personService.create(expected); + String updatedHomeTown = RandomStringUtils.randomAlphabetic(12); + expected.setHomeTown(updatedHomeTown); + personService.update(expected); + Person actual = personService.read(expected.getId()); + assertNotNull(actual); + assertEquals(expected.getHomeTown(), actual.getHomeTown()); + } + + @Test + public final void givenRandomPerson_whenDelete_thenPersonNotInBucket() { + Person person = randomPerson(); + personService.create(person); + String id = person.getId(); + personService.delete(id); + assertNull(personService.read(id)); + } + + private Person buildClarkKent() { + return Person.Builder.newInstance().id(CLARK_KENT_ID).name(CLARK_KENT).homeTown(SMALLVILLE).build(); + } + + private Person randomPerson() { + return Person.Builder.newInstance().name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build(); + } +} diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java deleted file mode 100644 index ead247dfbc..0000000000 --- a/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.couchbase.spring.service; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestExecutionListeners; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; - -import com.baeldung.couchbase.spring.IntegrationTest; -import com.baeldung.couchbase.spring.IntegrationTestConfig; -import com.couchbase.client.java.Bucket; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { IntegrationTestConfig.class }) -@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public class ClusterServiceIntegrationTest extends IntegrationTest { - - @Autowired - private ClusterService couchbaseService; - - private Bucket defaultBucket; - - @Test - public void whenOpenBucket_thenBucketIsNotNull() throws Exception { - defaultBucket = couchbaseService.openBucket("default", ""); - assertNotNull(defaultBucket); - assertFalse(defaultBucket.isClosed()); - defaultBucket.close(); - } -} diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java b/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java new file mode 100644 index 0000000000..7a89a208f7 --- /dev/null +++ b/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java @@ -0,0 +1,34 @@ +package com.baeldung.couchbase.spring.service; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; + +import com.baeldung.couchbase.spring.IntegrationTest; +import com.baeldung.couchbase.spring.IntegrationTestConfig; +import com.couchbase.client.java.Bucket; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { IntegrationTestConfig.class }) +@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) +public class ClusterServiceLiveTest extends IntegrationTest { + + @Autowired + private ClusterService couchbaseService; + + private Bucket defaultBucket; + + @Test + public void whenOpenBucket_thenBucketIsNotNull() throws Exception { + defaultBucket = couchbaseService.openBucket("default", ""); + assertNotNull(defaultBucket); + assertFalse(defaultBucket.isClosed()); + defaultBucket.close(); + } +} diff --git a/couchbase/src/test/resources/logback.xml b/couchbase/src/test/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/couchbase/src/test/resources/logback.xml +++ b/couchbase/src/test/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/custom-pmd-0.0.1.jar b/custom-pmd-0.0.1.jar index 4ad6933865..e19bce6e52 100644 Binary files a/custom-pmd-0.0.1.jar and b/custom-pmd-0.0.1.jar differ diff --git a/custom-pmd/pom.xml b/custom-pmd/pom.xml index dcd068089b..0f73282ae3 100644 --- a/custom-pmd/pom.xml +++ b/custom-pmd/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung.pmd custom-pmd diff --git a/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java b/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java index 4136165b6f..3b73f9c21c 100644 --- a/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java +++ b/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java @@ -11,20 +11,20 @@ public class UnitTestNamingConventionRule extends AbstractJavaRule { private static List allowedEndings = Arrays.asList( "IntegrationTest", + "IntTest", "ManualTest", "JdbcTest", "LiveTest", - "UnitTest"); + "UnitTest", + "jmhTest"); public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { String className = node.getImage(); Objects.requireNonNull(className); - if (className.endsWith("Test") || className.endsWith("Tests")) { - if (allowedEndings.stream() - .noneMatch(className::endsWith)) { - addViolation(data, node); - } + if (className.endsWith("Tests") + || (className.endsWith("Test") && allowedEndings.stream().noneMatch(className::endsWith))) { + addViolation(data, node); } return data; diff --git a/custom-pmd/src/main/resources/logback.xml b/custom-pmd/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/custom-pmd/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/dagger/README.md b/dagger/README.md new file mode 100644 index 0000000000..72cba3d3f2 --- /dev/null +++ b/dagger/README.md @@ -0,0 +1,3 @@ +### Relevant articles: + +- [Introduction to Dagger 2](http://www.baeldung.com/dagger-2) diff --git a/dagger/pom.xml b/dagger/pom.xml new file mode 100644 index 0000000000..80a3e961af --- /dev/null +++ b/dagger/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + dagger + dagger + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + + com.google.dagger + dagger + ${dagger.version} + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + + + com.google.dagger + dagger-compiler + ${dagger.version} + + + + + + + + + 2.16 + + + \ No newline at end of file diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/Brand.java b/dagger/src/main/java/com/baeldung/dagger/intro/Brand.java new file mode 100644 index 0000000000..5ec6607d67 --- /dev/null +++ b/dagger/src/main/java/com/baeldung/dagger/intro/Brand.java @@ -0,0 +1,45 @@ +package com.baeldung.dagger.intro; + +/** + * Brand of a {@link Car}. + * + * @author Donato Rimenti + * + */ +public class Brand { + + /** + * The name of the brand. + */ + private String name; + + /** + * Instantiates a new Brand. + * + * @param name + * the {@link #name} + */ + public Brand(String name) { + this.name = name; + } + + /** + * Gets the {@link #name}. + * + * @return the {@link #name} + */ + public String getName() { + return name; + } + + /** + * Sets the {@link #name}. + * + * @param name + * the new {@link #name} + */ + public void setName(String name) { + this.name = name; + } + +} diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/Car.java b/dagger/src/main/java/com/baeldung/dagger/intro/Car.java new file mode 100644 index 0000000000..2ad81b8f6c --- /dev/null +++ b/dagger/src/main/java/com/baeldung/dagger/intro/Car.java @@ -0,0 +1,75 @@ +package com.baeldung.dagger.intro; + +import javax.inject.Inject; + +/** + * Represents a car. + * + * @author Donato Rimenti + * + */ +public class Car { + + /** + * The car's engine. + */ + private Engine engine; + + /** + * The car's brand. + */ + private Brand brand; + + /** + * Instantiates a new Car. + * + * @param engine + * the {@link #engine} + * @param brand + * the {@link #brand} + */ + @Inject + public Car(Engine engine, Brand brand) { + this.engine = engine; + this.brand = brand; + } + + /** + * Gets the {@link #engine}. + * + * @return the {@link #engine} + */ + public Engine getEngine() { + return engine; + } + + /** + * Sets the {@link #engine}. + * + * @param engine + * the new {@link #engine} + */ + public void setEngine(Engine engine) { + this.engine = engine; + } + + /** + * Gets the {@link #brand}. + * + * @return the {@link #brand} + */ + public Brand getBrand() { + return brand; + } + + /** + * Sets the {@link #brand}. + * + * @param brand + * the new {@link #brand} + */ + public void setBrand(Brand brand) { + this.brand = brand; + } + +} diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/Engine.java b/dagger/src/main/java/com/baeldung/dagger/intro/Engine.java new file mode 100644 index 0000000000..99e30625cd --- /dev/null +++ b/dagger/src/main/java/com/baeldung/dagger/intro/Engine.java @@ -0,0 +1,24 @@ +package com.baeldung.dagger.intro; + +/** + * Engine of a {@link Car}. + * + * @author Donato Rimenti + * + */ +public class Engine { + + /** + * Starts the engine. + */ + public void start() { + System.out.println("Engine started"); + } + + /** + * Stops the engine. + */ + public void stop() { + System.out.println("Engine stopped"); + } +} diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesComponent.java b/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesComponent.java new file mode 100644 index 0000000000..aeeaab636e --- /dev/null +++ b/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesComponent.java @@ -0,0 +1,24 @@ +package com.baeldung.dagger.intro; + +import javax.inject.Singleton; + +import dagger.Component; + +/** + * Dagger component for building vehicles. + * + * @author Donato Rimenti + * + */ +@Singleton +@Component(modules = VehiclesModule.class) +public interface VehiclesComponent { + + /** + * Builds a {@link Car}. + * + * @return a {@link Car} + */ + public Car buildCar(); + +} \ No newline at end of file diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesModule.java b/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesModule.java new file mode 100644 index 0000000000..f6c6e4a108 --- /dev/null +++ b/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesModule.java @@ -0,0 +1,37 @@ +package com.baeldung.dagger.intro; + +import javax.inject.Singleton; + +import dagger.Module; +import dagger.Provides; + +/** + * Dagger module for providing vehicles components. + * + * @author Donato Rimenti + * + */ +@Module +public class VehiclesModule { + + /** + * Creates an {@link Engine}. + * + * @return an {@link Engine} + */ + @Provides + public Engine provideEngine() { + return new Engine(); + } + + /** + * Creates a {@link Brand}. + * + * @return a {@link Brand} + */ + @Provides + @Singleton + public Brand provideBrand() { + return new Brand("Baeldung"); + } +} \ No newline at end of file diff --git a/dagger/src/main/resources/logback.xml b/dagger/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/dagger/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/dagger/src/test/java/com/baeldung/dagger/intro/DaggerUnitTest.java b/dagger/src/test/java/com/baeldung/dagger/intro/DaggerUnitTest.java new file mode 100644 index 0000000000..83e881ffe1 --- /dev/null +++ b/dagger/src/test/java/com/baeldung/dagger/intro/DaggerUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.dagger.intro; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Unit test for building a {@link Car} using Dagger. + * + * @author Donato Rimenti + * + */ +public class DaggerUnitTest { + + /** + * Builds two {@link Car} and checks that the fields are injected correctly. + */ + @Test + public void givenGeneratedComponent_whenBuildingCar_thenDependenciesInjected() { + VehiclesComponent component = DaggerVehiclesComponent.create(); + + Car carOne = component.buildCar(); + Car carTwo = component.buildCar(); + + Assert.assertNotNull(carOne); + Assert.assertNotNull(carTwo); + Assert.assertNotNull(carOne.getEngine()); + Assert.assertNotNull(carTwo.getEngine()); + Assert.assertNotNull(carOne.getBrand()); + Assert.assertNotNull(carTwo.getBrand()); + Assert.assertNotEquals(carOne.getEngine(), carTwo.getEngine()); + Assert.assertEquals(carOne.getBrand(), carTwo.getBrand()); + } + +} diff --git a/data-structures/pom.xml b/data-structures/pom.xml index 287e9f38aa..c1a1f1d371 100644 --- a/data-structures/pom.xml +++ b/data-structures/pom.xml @@ -1,5 +1,5 @@ + 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 data-structures diff --git a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java index e3179dca32..f435e41afa 100644 --- a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java +++ b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java @@ -57,7 +57,7 @@ public class BinaryTree { } public void delete(int value) { - deleteRecursive(root, value); + root = deleteRecursive(root, value); } private Node deleteRecursive(Node current, int value) { diff --git a/data-structures/src/main/java/com/baeldung/trie/Trie.java b/data-structures/src/main/java/com/baeldung/trie/Trie.java index dd51d97b2d..dac1a64733 100644 --- a/data-structures/src/main/java/com/baeldung/trie/Trie.java +++ b/data-structures/src/main/java/com/baeldung/trie/Trie.java @@ -1,13 +1,13 @@ package com.baeldung.trie; -public class Trie { +class Trie { private TrieNode root; Trie() { root = new TrieNode(); } - public void insert(String word) { + void insert(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { @@ -16,11 +16,11 @@ public class Trie { current.setEndOfWord(true); } - public boolean delete(String word) { + boolean delete(String word) { return delete(root, word, 0); } - public boolean containsNode(String word) { + boolean containsNode(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { @@ -34,7 +34,7 @@ public class Trie { return current.isEndOfWord(); } - public boolean isEmpty() { + boolean isEmpty() { return root == null; } @@ -51,7 +51,7 @@ public class Trie { if (node == null) { return false; } - boolean shouldDeleteCurrentNode = delete(node, word, index + 1); + boolean shouldDeleteCurrentNode = delete(node, word, index + 1) && !node.isEndOfWord(); if (shouldDeleteCurrentNode) { current.getChildren().remove(ch); diff --git a/data-structures/src/main/java/com/baeldung/trie/TrieNode.java b/data-structures/src/main/java/com/baeldung/trie/TrieNode.java index 25dc753950..73dcdb63f5 100644 --- a/data-structures/src/main/java/com/baeldung/trie/TrieNode.java +++ b/data-structures/src/main/java/com/baeldung/trie/TrieNode.java @@ -4,28 +4,18 @@ import java.util.HashMap; import java.util.Map; class TrieNode { - private Map children; + private final Map children = new HashMap<>(); private boolean endOfWord; - public TrieNode() { - children = new HashMap<>(); - endOfWord = false; - } - - public Map getChildren() { + Map getChildren() { return children; } - public void setChildren(Map children) { - this.children = children; - } - - public boolean isEndOfWord() { + boolean isEndOfWord() { return endOfWord; } - public void setEndOfWord(boolean endOfWord) { + void setEndOfWord(boolean endOfWord) { this.endOfWord = endOfWord; } - } \ No newline at end of file diff --git a/data-structures/src/main/resources/logback.xml b/data-structures/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/data-structures/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeTest.java b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeTest.java deleted file mode 100644 index 99e656fe28..0000000000 --- a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.baeldung.tree; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -public class BinaryTreeTest { - - @Test - public void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() { - - BinaryTree bt = createBinaryTree(); - - assertTrue(!bt.isEmpty()); - } - - @Test - public void givenABinaryTree_WhenAddingElements_ThenTreeContainsThoseElements() { - - BinaryTree bt = createBinaryTree(); - - assertTrue(bt.containsNode(6)); - assertTrue(bt.containsNode(4)); - - assertFalse(bt.containsNode(1)); - } - - @Test - public void givenABinaryTree_WhenAddingExistingElement_ThenElementIsNotAdded() { - - BinaryTree bt = createBinaryTree(); - - int initialSize = bt.getSize(); - - assertTrue(bt.containsNode(3)); - bt.add(3); - assertEquals(initialSize, bt.getSize()); - } - - @Test - public void givenABinaryTree_WhenLookingForNonExistingElement_ThenReturnsFalse() { - - BinaryTree bt = createBinaryTree(); - - assertFalse(bt.containsNode(99)); - } - - @Test - public void givenABinaryTree_WhenDeletingElements_ThenTreeDoesNotContainThoseElements() { - - BinaryTree bt = createBinaryTree(); - - assertTrue(bt.containsNode(9)); - bt.delete(9); - assertFalse(bt.containsNode(9)); - } - - @Test - public void givenABinaryTree_WhenDeletingNonExistingElement_ThenTreeDoesNotDelete() { - - BinaryTree bt = createBinaryTree(); - - int initialSize = bt.getSize(); - - assertFalse(bt.containsNode(99)); - bt.delete(99); - assertFalse(bt.containsNode(99)); - assertEquals(initialSize, bt.getSize()); - } - - @Test - public void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() { - - BinaryTree bt = createBinaryTree(); - - bt.traverseInOrder(bt.root); - } - - @Test - public void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() { - - BinaryTree bt = createBinaryTree(); - - bt.traversePreOrder(bt.root); - } - - @Test - public void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() { - - BinaryTree bt = createBinaryTree(); - - bt.traversePostOrder(bt.root); - } - - @Test - public void givenABinaryTree_WhenTraversingLevelOrder_ThenPrintValues() { - - BinaryTree bt = createBinaryTree(); - - bt.traverseLevelOrder(); - } - - private BinaryTree createBinaryTree() { - BinaryTree bt = new BinaryTree(); - - bt.add(6); - bt.add(4); - bt.add(8); - bt.add(3); - bt.add(5); - bt.add(7); - bt.add(9); - - return bt; - } - -} diff --git a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java new file mode 100644 index 0000000000..f81247b74d --- /dev/null +++ b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java @@ -0,0 +1,130 @@ +package com.baeldung.tree; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class BinaryTreeUnitTest { + + @Test + public void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() { + + BinaryTree bt = createBinaryTree(); + + assertTrue(!bt.isEmpty()); + } + + @Test + public void givenABinaryTree_WhenAddingElements_ThenTreeContainsThoseElements() { + + BinaryTree bt = createBinaryTree(); + + assertTrue(bt.containsNode(6)); + assertTrue(bt.containsNode(4)); + + assertFalse(bt.containsNode(1)); + } + + @Test + public void givenABinaryTree_WhenAddingExistingElement_ThenElementIsNotAdded() { + + BinaryTree bt = createBinaryTree(); + + int initialSize = bt.getSize(); + + assertTrue(bt.containsNode(3)); + bt.add(3); + assertEquals(initialSize, bt.getSize()); + } + + @Test + public void givenABinaryTree_WhenLookingForNonExistingElement_ThenReturnsFalse() { + + BinaryTree bt = createBinaryTree(); + + assertFalse(bt.containsNode(99)); + } + + @Test + public void givenABinaryTree_WhenDeletingElements_ThenTreeDoesNotContainThoseElements() { + + BinaryTree bt = createBinaryTree(); + + assertTrue(bt.containsNode(9)); + bt.delete(9); + assertFalse(bt.containsNode(9)); + } + + @Test + public void givenABinaryTree_WhenDeletingNonExistingElement_ThenTreeDoesNotDelete() { + + BinaryTree bt = createBinaryTree(); + + int initialSize = bt.getSize(); + + assertFalse(bt.containsNode(99)); + bt.delete(99); + assertFalse(bt.containsNode(99)); + assertEquals(initialSize, bt.getSize()); + } + + @Test + public void it_deletes_the_root() { + int value = 12; + BinaryTree bt = new BinaryTree(); + bt.add(value); + + assertTrue(bt.containsNode(value)); + bt.delete(value); + assertFalse(bt.containsNode(value)); + } + + @Test + public void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() { + + BinaryTree bt = createBinaryTree(); + + bt.traverseInOrder(bt.root); + } + + @Test + public void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() { + + BinaryTree bt = createBinaryTree(); + + bt.traversePreOrder(bt.root); + } + + @Test + public void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() { + + BinaryTree bt = createBinaryTree(); + + bt.traversePostOrder(bt.root); + } + + @Test + public void givenABinaryTree_WhenTraversingLevelOrder_ThenPrintValues() { + + BinaryTree bt = createBinaryTree(); + + bt.traverseLevelOrder(); + } + + private BinaryTree createBinaryTree() { + BinaryTree bt = new BinaryTree(); + + bt.add(6); + bt.add(4); + bt.add(8); + bt.add(3); + bt.add(5); + bt.add(7); + bt.add(9); + + return bt; + } + +} diff --git a/data-structures/src/test/java/com/baeldung/trie/TrieTest.java b/data-structures/src/test/java/com/baeldung/trie/TrieTest.java deleted file mode 100644 index be7e5575d8..0000000000 --- a/data-structures/src/test/java/com/baeldung/trie/TrieTest.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.baeldung.trie; - -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class TrieTest { - - @Test - public void whenEmptyTrie_thenNoElements() { - Trie trie = new Trie(); - - assertFalse(trie.isEmpty()); - } - - @Test - public void givenATrie_whenAddingElements_thenTrieNotEmpty() { - Trie trie = createExampleTrie(); - - assertFalse(trie.isEmpty()); - } - - @Test - public void givenATrie_whenAddingElements_thenTrieHasThoseElements() { - Trie trie = createExampleTrie(); - - assertFalse(trie.containsNode("3")); - assertFalse(trie.containsNode("vida")); - - assertTrue(trie.containsNode("Programming")); - assertTrue(trie.containsNode("is")); - assertTrue(trie.containsNode("a")); - assertTrue(trie.containsNode("way")); - assertTrue(trie.containsNode("of")); - assertTrue(trie.containsNode("life")); - } - - @Test - public void givenATrie_whenLookingForNonExistingElement_thenReturnsFalse() { - Trie trie = createExampleTrie(); - - assertFalse(trie.containsNode("99")); - } - - @Test - public void givenATrie_whenDeletingElements_thenTreeDoesNotContainThoseElements() { - - Trie trie = createExampleTrie(); - - assertTrue(trie.containsNode("Programming")); - trie.delete("Programming"); - assertFalse(trie.containsNode("Programming")); - } - - private Trie createExampleTrie() { - Trie trie = new Trie(); - - trie.insert("Programming"); - trie.insert("is"); - trie.insert("a"); - trie.insert("way"); - trie.insert("of"); - trie.insert("life"); - - return trie; - } -} diff --git a/data-structures/src/test/java/com/baeldung/trie/TrieUnitTest.java b/data-structures/src/test/java/com/baeldung/trie/TrieUnitTest.java new file mode 100644 index 0000000000..bf9555315c --- /dev/null +++ b/data-structures/src/test/java/com/baeldung/trie/TrieUnitTest.java @@ -0,0 +1,82 @@ +package com.baeldung.trie; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class TrieUnitTest { + + @Test + public void whenEmptyTrie_thenNoElements() { + Trie trie = new Trie(); + + assertFalse(trie.isEmpty()); + } + + @Test + public void givenATrie_whenAddingElements_thenTrieNotEmpty() { + Trie trie = createExampleTrie(); + + assertFalse(trie.isEmpty()); + } + + @Test + public void givenATrie_whenAddingElements_thenTrieHasThoseElements() { + Trie trie = createExampleTrie(); + + assertFalse(trie.containsNode("3")); + assertFalse(trie.containsNode("vida")); + + assertTrue(trie.containsNode("Programming")); + assertTrue(trie.containsNode("is")); + assertTrue(trie.containsNode("a")); + assertTrue(trie.containsNode("way")); + assertTrue(trie.containsNode("of")); + assertTrue(trie.containsNode("life")); + } + + @Test + public void givenATrie_whenLookingForNonExistingElement_thenReturnsFalse() { + Trie trie = createExampleTrie(); + + assertFalse(trie.containsNode("99")); + } + + @Test + public void givenATrie_whenDeletingElements_thenTreeDoesNotContainThoseElements() { + + Trie trie = createExampleTrie(); + + assertTrue(trie.containsNode("Programming")); + trie.delete("Programming"); + assertFalse(trie.containsNode("Programming")); + } + + @Test + public void givenATrie_whenDeletingOverlappingElements_thenDontDeleteSubElement() { + + Trie trie1 = new Trie(); + + trie1.insert("pie"); + trie1.insert("pies"); + + trie1.delete("pies"); + + Assertions.assertTrue(trie1.containsNode("pie")); + } + + private Trie createExampleTrie() { + Trie trie = new Trie(); + + trie.insert("Programming"); + trie.insert("is"); + trie.insert("a"); + trie.insert("way"); + trie.insert("of"); + trie.insert("life"); + + return trie; + } +} diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml index 8d9e8c6475..38be189bd0 100644 --- a/deeplearning4j/pom.xml +++ b/deeplearning4j/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung.deeplearning4j deeplearning4j @@ -27,7 +27,6 @@ - UTF-8 0.9.1 diff --git a/deeplearning4j/src/main/resources/logback.xml b/deeplearning4j/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/deeplearning4j/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/deltaspike/README.md b/deltaspike/README.md index ff12555376..c1ab0a9736 100644 --- a/deltaspike/README.md +++ b/deltaspike/README.md @@ -1 +1,3 @@ ## Relevant articles: + +- [A Guide to DeltaSpike Data Module](http://www.baeldung.com/deltaspike-data-module) diff --git a/deltaspike/pom.xml b/deltaspike/pom.xml index 87f532c3f3..8ab3e3fd80 100644 --- a/deltaspike/pom.xml +++ b/deltaspike/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung deltaspike @@ -9,13 +9,6 @@ deltaspike A starter Java EE 7 webapp which uses DeltaSpike http://wildfly.org - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - com.baeldung @@ -23,72 +16,39 @@ 1.0.0-SNAPSHOT - - - - - org.wildfly.bom - jboss-javaee-7.0-with-tools - ${jboss.bom.version} - pom - import - - - org.wildfly.bom - jboss-javaee-7.0-with-hibernate - ${jboss.bom.version} - pom - import - - - - - + - + javax.enterprise cdi-api provided - + org.jboss.spec.javax.annotation jboss-annotations-api_1.2_spec provided - + org.jboss.resteasy jaxrs-api provided - + org.hibernate.javax.persistence hibernate-jpa-2.1-api provided - + org.jboss.spec.javax.ejb jboss-ejb-api_3.2_spec @@ -110,8 +70,7 @@ - + org.jboss.spec.javax.faces jboss-jsf-api_2.2_spec @@ -120,16 +79,14 @@ - + org.hibernate hibernate-jpamodelgen provided - + org.hibernate hibernate-validator-annotation-processor @@ -137,8 +94,7 @@ - + org.jboss.arquillian.junit arquillian-junit-container @@ -160,14 +116,12 @@ org.apache.deltaspike.modules deltaspike-data-module-api - ${deltaspike.version} compile org.apache.deltaspike.modules deltaspike-data-module-impl - ${deltaspike.version} runtime @@ -184,11 +138,75 @@ querydsl-jpa ${querydsl.version} + + + org.apache.deltaspike.modules + deltaspike-test-control-module-api + test + + + + org.apache.deltaspike.modules + deltaspike-test-control-module-impl + test + + + + org.apache.deltaspike.cdictrl + deltaspike-cdictrl-weld + test + + + + org.jboss.weld.se + weld-se-core + ${weld.version} + test + + + + org.hibernate + hibernate-core + provided + + + + org.jboss + jandex + ${jandex.version} + + + + com.h2database + h2 + ${h2.version} + test + + + + org.hibernate + hibernate-entitymanager + provided + + + + + junit + junit + test + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + - + ${project.artifactId} @@ -227,33 +245,9 @@ - - - default - - true - - - - - maven-surefire-plugin - ${maven-surefire-plugin.version} - - true - - - - - - - - - + + arq-wildfly-managed @@ -266,22 +260,64 @@ + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + redhat-repository-techpreview + https://maven.repository.redhat.com/techpreview/all/ + + + + + + + + org.wildfly.bom + jboss-javaee-7.0-with-tools + ${jboss.bom.version} + pom + import + + + org.wildfly.bom + jboss-javaee-7.0-with-hibernate + ${jboss.bom.version} + pom + import + + + org.apache.deltaspike.distribution + distributions-bom + ${deltaspike.version} + pom + import + + + + - - - UTF-8 3.7.4 - 1.7.2 + 1.8.2 1.0.2.Final - - 8.2.2.Final + + 8.2.1.Final + 2.1.2.Final 2.6 1.1.3 + 1.2.5.Final-redhat-1 + 1.4.197 + 3.5 diff --git a/deltaspike/src/main/java/baeldung/controller/MemberController.java b/deltaspike/src/main/java/baeldung/controller/MemberController.java index 7a9e9800f4..eba36355b7 100644 --- a/deltaspike/src/main/java/baeldung/controller/MemberController.java +++ b/deltaspike/src/main/java/baeldung/controller/MemberController.java @@ -16,6 +16,9 @@ */ package baeldung.controller; +import baeldung.model.Member; +import baeldung.service.MemberRegistration; + import javax.annotation.PostConstruct; import javax.enterprise.inject.Model; import javax.enterprise.inject.Produces; @@ -24,9 +27,6 @@ import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; -import baeldung.model.Member; -import baeldung.service.MemberRegistration; - // The @Model stereotype is a convenience mechanism to make this a request-scoped bean that has an // EL name // Read more about the @Model stereotype in this FAQ: @@ -34,11 +34,9 @@ import baeldung.service.MemberRegistration; @Model public class MemberController { - @Inject - private FacesContext facesContext; + @Inject private FacesContext facesContext; - @Inject - private MemberRegistration memberRegistration; + @Inject private MemberRegistration memberRegistration; @Produces @Named diff --git a/deltaspike/src/main/java/baeldung/data/EntityManagerProducer.java b/deltaspike/src/main/java/baeldung/data/EntityManagerProducer.java index 9189dbba74..6c2387012d 100644 --- a/deltaspike/src/main/java/baeldung/data/EntityManagerProducer.java +++ b/deltaspike/src/main/java/baeldung/data/EntityManagerProducer.java @@ -1,29 +1,18 @@ package baeldung.data; -import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.RequestScoped; -import javax.enterprise.inject.Default; -import javax.enterprise.inject.Disposes; import javax.enterprise.inject.Produces; import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.PersistenceUnit; +import javax.persistence.PersistenceContext; -@ApplicationScoped public class EntityManagerProducer { - @PersistenceUnit(unitName = "primary") - private EntityManagerFactory entityManagerFactory; - @Produces - @Default + @PersistenceContext(unitName = "primary") private EntityManager entityManager; + @RequestScoped + @Produces public EntityManager create() { - return this.entityManagerFactory.createEntityManager(); + return entityManager; } - public void dispose(@Disposes @Default EntityManager entityManager) { - if (entityManager.isOpen()) { - entityManager.close(); - } - } } \ No newline at end of file diff --git a/deltaspike/src/main/java/baeldung/data/MemberListProducer.java b/deltaspike/src/main/java/baeldung/data/MemberListProducer.java index c1f5fda31d..989bcea917 100644 --- a/deltaspike/src/main/java/baeldung/data/MemberListProducer.java +++ b/deltaspike/src/main/java/baeldung/data/MemberListProducer.java @@ -16,6 +16,8 @@ */ package baeldung.data; +import baeldung.model.Member; + import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.enterprise.event.Observes; @@ -25,13 +27,10 @@ import javax.inject.Inject; import javax.inject.Named; import java.util.List; -import baeldung.model.Member; - @RequestScoped public class MemberListProducer { - @Inject - private MemberRepository memberRepository; + @Inject private MemberRepository memberRepository; private List members; diff --git a/deltaspike/src/main/java/baeldung/data/MemberRepository.java b/deltaspike/src/main/java/baeldung/data/MemberRepository.java index 220388bcf0..e9c7e52f9c 100644 --- a/deltaspike/src/main/java/baeldung/data/MemberRepository.java +++ b/deltaspike/src/main/java/baeldung/data/MemberRepository.java @@ -18,7 +18,10 @@ package baeldung.data; import baeldung.model.Member; import baeldung.model.QMember; -import org.apache.deltaspike.data.api.*; +import org.apache.deltaspike.data.api.AbstractEntityRepository; +import org.apache.deltaspike.data.api.EntityManagerConfig; +import org.apache.deltaspike.data.api.Query; +import org.apache.deltaspike.data.api.Repository; import java.util.List; @@ -35,6 +38,9 @@ public abstract class MemberRepository extends AbstractEntityRepository findAllOrderedByNameWithQueryDSL() { final QMember member = QMember.member; - return jpaQuery().from(member).orderBy(member.email.asc()).list(member); + return jpaQuery() + .from(member) + .orderBy(member.email.asc()) + .list(member); } } diff --git a/deltaspike/src/main/java/baeldung/data/QueryDslRepositoryExtension.java b/deltaspike/src/main/java/baeldung/data/QueryDslRepositoryExtension.java index 8cb00958ab..4bb8a629de 100644 --- a/deltaspike/src/main/java/baeldung/data/QueryDslRepositoryExtension.java +++ b/deltaspike/src/main/java/baeldung/data/QueryDslRepositoryExtension.java @@ -8,8 +8,7 @@ import javax.inject.Inject; public class QueryDslRepositoryExtension implements QueryDslSupport, DelegateQueryHandler { - @Inject - private QueryInvocationContext context; + @Inject private QueryInvocationContext context; @Override public JPAQuery jpaQuery() { diff --git a/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerProducer.java b/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerProducer.java index 41d30d9018..606def4f30 100644 --- a/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerProducer.java +++ b/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerProducer.java @@ -2,29 +2,20 @@ package baeldung.data; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.RequestScoped; -import javax.enterprise.inject.Default; -import javax.enterprise.inject.Disposes; import javax.enterprise.inject.Produces; import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.PersistenceUnit; +import javax.persistence.PersistenceContext; @ApplicationScoped public class SecondaryEntityManagerProducer { - @PersistenceUnit(unitName = "secondary") - private EntityManagerFactory entityManagerFactory; + + @PersistenceContext(unitName = "secondary") private EntityManager entityManager; @Produces - @Default @RequestScoped @SecondaryPersistenceUnit public EntityManager create() { - return this.entityManagerFactory.createEntityManager(); + return entityManager; } - public void dispose(@Disposes @Default EntityManager entityManager) { - if (entityManager.isOpen()) { - entityManager.close(); - } - } } \ No newline at end of file diff --git a/deltaspike/src/main/java/baeldung/data/SimpleUserRepository.java b/deltaspike/src/main/java/baeldung/data/SimpleUserRepository.java new file mode 100644 index 0000000000..9ea6115f11 --- /dev/null +++ b/deltaspike/src/main/java/baeldung/data/SimpleUserRepository.java @@ -0,0 +1,45 @@ +package baeldung.data; + +import baeldung.model.User; +import org.apache.deltaspike.data.api.FirstResult; +import org.apache.deltaspike.data.api.MaxResults; +import org.apache.deltaspike.data.api.Repository; + +import java.util.Collection; +import java.util.List; + +/** + * Created by adam. + */ +@Repository(forEntity = User.class) +public abstract class SimpleUserRepository { + public abstract Collection findAll(); + + public abstract Collection findAllOrderByFirstNameAsc(@FirstResult int start, @MaxResults int size); + + public abstract Collection findTop2OrderByFirstNameAsc(); + + public abstract Collection findFirst2OrderByFirstNameAsc(); + + public abstract List findAllOrderByFirstNameAsc(); + + public abstract List findAllOrderByFirstNameAscLastNameDesc(); + + public abstract User findById(Long id); + + public abstract Collection findByFirstName(String firstName); + + public abstract User findAnyByLastName(String lastName); + + public abstract Collection findAnyByFirstName(String firstName); + + public abstract Collection findByFirstNameAndLastName(String firstName, String lastName); + + public abstract Collection findByFirstNameOrLastName(String firstName, String lastName); + + public abstract Collection findByAddress_city(String city); + + public abstract int count(); + + public abstract void remove(User user); +} diff --git a/deltaspike/src/main/java/baeldung/data/UserRepository.java b/deltaspike/src/main/java/baeldung/data/UserRepository.java new file mode 100644 index 0000000000..688e46f5fc --- /dev/null +++ b/deltaspike/src/main/java/baeldung/data/UserRepository.java @@ -0,0 +1,31 @@ +package baeldung.data; + +import baeldung.model.User; +import org.apache.deltaspike.data.api.AbstractEntityRepository; +import org.apache.deltaspike.data.api.Query; +import org.apache.deltaspike.data.api.Repository; + +import java.util.Collection; +import java.util.List; + +/** + * Created by adam. + */ +@Repository +public abstract class UserRepository extends AbstractEntityRepository { + + public List findByFirstName(String firstName) { + return typedQuery("select u from User u where u.firstName = ?1") + .setParameter(1, firstName) + .getResultList(); + } + + public abstract List findByLastName(String lastName); + + @Query("select u from User u where u.firstName = ?1") + public abstract Collection findUsersWithFirstName(String firstName); + + @Query(value = "select * from User where firstName = ?1", isNative = true) + public abstract Collection findUsersWithFirstNameNative(String firstName); + +} diff --git a/deltaspike/src/main/java/baeldung/model/Address.java b/deltaspike/src/main/java/baeldung/model/Address.java new file mode 100644 index 0000000000..ef0d461b9c --- /dev/null +++ b/deltaspike/src/main/java/baeldung/model/Address.java @@ -0,0 +1,51 @@ +package baeldung.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +/** + * Created by adam. + */ +@Entity +public class Address { + + @Id + @GeneratedValue + private Long id; + private String street; + private String city; + private String postCode; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getPostCode() { + return postCode; + } + + public void setPostCode(String postCode) { + this.postCode = postCode; + } +} diff --git a/deltaspike/src/main/java/baeldung/model/Member.java b/deltaspike/src/main/java/baeldung/model/Member.java index e178dcf63a..d9b9b5caf1 100644 --- a/deltaspike/src/main/java/baeldung/model/Member.java +++ b/deltaspike/src/main/java/baeldung/model/Member.java @@ -16,22 +16,16 @@ */ package baeldung.model; -import java.io.Serializable; +import org.hibernate.validator.constraints.Email; +import org.hibernate.validator.constraints.NotEmpty; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.UniqueConstraint; +import javax.persistence.*; import javax.validation.constraints.Digits; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; - -import org.hibernate.validator.constraints.Email; -import org.hibernate.validator.constraints.NotEmpty; +import java.io.Serializable; @SuppressWarnings("serial") @Entity diff --git a/deltaspike/src/main/java/baeldung/model/User.java b/deltaspike/src/main/java/baeldung/model/User.java new file mode 100644 index 0000000000..5560ea0e7c --- /dev/null +++ b/deltaspike/src/main/java/baeldung/model/User.java @@ -0,0 +1,52 @@ +package baeldung.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.OneToOne; + +/** + * Created by adam. + */ +@Entity +public class User { + + @Id + @GeneratedValue + private Long id; + private String firstName; + private String lastName; + @OneToOne private Address address; + + 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 Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } +} diff --git a/deltaspike/src/main/resources/META-INF/beans.xml b/deltaspike/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..f462814752 --- /dev/null +++ b/deltaspike/src/main/resources/META-INF/beans.xml @@ -0,0 +1,5 @@ + + diff --git a/deltaspike/src/main/resources/logback.xml b/deltaspike/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/deltaspike/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/deltaspike/src/test/java/baeldung/ValidatorProducer.java b/deltaspike/src/test/java/baeldung/ValidatorProducer.java new file mode 100644 index 0000000000..6b895f771e --- /dev/null +++ b/deltaspike/src/test/java/baeldung/ValidatorProducer.java @@ -0,0 +1,21 @@ +package baeldung; + +import javax.enterprise.inject.Produces; +import javax.validation.Validation; +import javax.validation.Validator; + +/** + * Created by adam. + */ +public class ValidatorProducer { + + @Produces + public Validator createValidator() { + return Validation + .byDefaultProvider() + .configure() + .buildValidatorFactory() + .getValidator(); + } + +} diff --git a/deltaspike/src/test/java/baeldung/data/TestEntityManagerProducer.java b/deltaspike/src/test/java/baeldung/data/TestEntityManagerProducer.java new file mode 100644 index 0000000000..139760d7fc --- /dev/null +++ b/deltaspike/src/test/java/baeldung/data/TestEntityManagerProducer.java @@ -0,0 +1,23 @@ +package baeldung.data; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.Produces; +import javax.enterprise.inject.Specializes; +import javax.persistence.EntityManager; +import javax.persistence.Persistence; + +/** + * Created by adam. + */ +public class TestEntityManagerProducer extends EntityManagerProducer { + + @ApplicationScoped + @Produces + @Specializes + public EntityManager create() { + return Persistence + .createEntityManagerFactory("pu-test") + .createEntityManager(); + } + +} diff --git a/deltaspike/src/test/java/baeldung/test/MemberRegistrationIntegrationTest.java b/deltaspike/src/test/java/baeldung/test/MemberRegistrationIntegrationTest.java deleted file mode 100644 index 2b6cfe2b02..0000000000 --- a/deltaspike/src/test/java/baeldung/test/MemberRegistrationIntegrationTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * JBoss, Home of Professional Open Source - * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual - * contributors by the @authors tag. See the copyright.txt in the - * distribution for a full listing of individual contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package baeldung.test; - -import static org.junit.Assert.assertNotNull; - -import java.io.File; -import java.util.logging.Logger; - -import javax.inject.Inject; - -import baeldung.data.*; -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.junit.Arquillian; -import baeldung.model.Member; -import baeldung.service.MemberRegistration; -import baeldung.util.Resources; -import org.jboss.shrinkwrap.api.Archive; -import org.jboss.shrinkwrap.api.ShrinkWrap; -import org.jboss.shrinkwrap.api.asset.EmptyAsset; -import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.jboss.shrinkwrap.resolver.api.maven.Maven; -import org.junit.Test; -import org.junit.runner.RunWith; - -@RunWith(Arquillian.class) -public class MemberRegistrationIntegrationTest { - @Deployment - public static Archive createTestArchive() { - File[] files = Maven.resolver().loadPomFromFile("pom.xml").importRuntimeDependencies().resolve().withTransitivity().asFile(); - - return ShrinkWrap.create(WebArchive.class, "test.war") - .addClasses(EntityManagerProducer.class, Member.class, MemberRegistration.class, MemberRepository.class, Resources.class, QueryDslRepositoryExtension.class, QueryDslSupport.class, SecondaryPersistenceUnit.class, - SecondaryEntityManagerProducer.class, SecondaryEntityManagerResolver.class) - .addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml").addAsResource("META-INF/apache-deltaspike.properties").addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml").addAsWebInfResource("test-ds.xml") - .addAsWebInfResource("test-secondary-ds.xml").addAsLibraries(files); - } - - @Inject - MemberRegistration memberRegistration; - - @Inject - Logger log; - - @Test - public void testRegister() throws Exception { - Member newMember = new Member(); - newMember.setName("Jane Doe"); - newMember.setEmail("jane@mailinator.com"); - newMember.setPhoneNumber("2125551234"); - memberRegistration.register(newMember); - assertNotNull(newMember.getId()); - log.info(newMember.getName() + " was persisted with id " + newMember.getId()); - } - -} diff --git a/deltaspike/src/test/java/baeldung/test/MemberRegistrationLiveTest.java b/deltaspike/src/test/java/baeldung/test/MemberRegistrationLiveTest.java new file mode 100644 index 0000000000..9d72d13b80 --- /dev/null +++ b/deltaspike/src/test/java/baeldung/test/MemberRegistrationLiveTest.java @@ -0,0 +1,78 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package baeldung.test; + +import baeldung.data.*; +import baeldung.model.Member; +import baeldung.service.MemberRegistration; +import baeldung.util.Resources; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.Archive; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.EmptyAsset; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.jboss.shrinkwrap.resolver.api.maven.Maven; +import org.junit.Test; +import org.junit.runner.RunWith; + +import javax.inject.Inject; +import java.io.File; +import java.util.logging.Logger; + +import static org.junit.Assert.assertNotNull; + +@RunWith(Arquillian.class) +public class MemberRegistrationLiveTest { + @Deployment + public static Archive createTestArchive() { + File[] files = Maven + .resolver() + .loadPomFromFile("pom.xml") + .importRuntimeDependencies() + .resolve() + .withTransitivity() + .asFile(); + + return ShrinkWrap + .create(WebArchive.class, "test.war") + .addClasses(EntityManagerProducer.class, Member.class, MemberRegistration.class, MemberRepository.class, Resources.class, QueryDslRepositoryExtension.class, QueryDslSupport.class, SecondaryPersistenceUnit.class, SecondaryEntityManagerProducer.class, + SecondaryEntityManagerResolver.class) + .addAsResource("META-INF/persistence.xml", "META-INF/persistence.xml") + .addAsResource("META-INF/apache-deltaspike.properties") + .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") + .addAsWebInfResource("test-ds.xml") + .addAsWebInfResource("test-secondary-ds.xml") + .addAsLibraries(files); + } + + @Inject MemberRegistration memberRegistration; + + @Inject Logger log; + + @Test + public void testRegister() throws Exception { + Member newMember = new Member(); + newMember.setName("Jane Doe"); + newMember.setEmail("jane@mailinator.com"); + newMember.setPhoneNumber("2125551234"); + memberRegistration.register(newMember); + assertNotNull(newMember.getId()); + log.info(newMember.getName() + " was persisted with id " + newMember.getId()); + } + +} diff --git a/deltaspike/src/test/java/baeldung/test/SimpleUserRepositoryUnitTest.java b/deltaspike/src/test/java/baeldung/test/SimpleUserRepositoryUnitTest.java new file mode 100644 index 0000000000..2065338c77 --- /dev/null +++ b/deltaspike/src/test/java/baeldung/test/SimpleUserRepositoryUnitTest.java @@ -0,0 +1,133 @@ +package baeldung.test; + +import baeldung.data.SimpleUserRepository; +import baeldung.model.User; +import org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner; +import org.junit.Test; +import org.junit.runner.RunWith; + +import javax.inject.Inject; +import javax.persistence.EntityManager; +import java.util.List; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.assertThat; + +/** + * Created by adam. + */ +@RunWith(CdiTestRunner.class) +public class SimpleUserRepositoryUnitTest { + + @Inject private EntityManager entityManager; + + @Inject private SimpleUserRepository simpleUserRepository; + + @Test + public void givenFourUsersWhenFindAllShouldReturnFourUsers() { + assertThat(simpleUserRepository + .findAll() + .size(), equalTo(4)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenFindByFirstNameShouldReturnTwoUsers() { + assertThat(simpleUserRepository + .findByFirstName("Adam") + .size(), equalTo(2)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenFindAnyByFirstNameShouldReturnTwoUsers() { + assertThat(simpleUserRepository + .findAnyByFirstName("Adam") + .size(), equalTo(2)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenCountByFirstNameShouldReturnSizeTwo() { + assertThat(simpleUserRepository.count(), equalTo(4)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenRemoveByFirstNameShouldReturnSizeTwo() { + simpleUserRepository.remove(entityManager.merge(simpleUserRepository.findById(1L))); + assertThat(entityManager.find(User.class, 1L), nullValue()); + } + + @Test + public void givenOneUserWithSpecifiedFirstNameAndLastNameWhenFindByFirstNameAndLastNameShouldReturnOneUser() { + assertThat(simpleUserRepository + .findByFirstNameAndLastName("Adam", "LastName1") + .size(), equalTo(1)); + assertThat(simpleUserRepository + .findByFirstNameAndLastName("David", "LastName2") + .size(), equalTo(1)); + } + + @Test + public void givenOneUserWithSpecifiedLastNameWhenFindAnyByLastNameShouldReturnOneUser() { + assertThat(simpleUserRepository.findAnyByLastName("LastName1"), notNullValue()); + } + + @Test + public void givenOneUserWithSpecifiedAddressCityWhenFindByCityShouldReturnOneUser() { + assertThat(simpleUserRepository + .findByAddress_city("London") + .size(), equalTo(1)); + } + + @Test + public void givenUsersWithSpecifiedFirstOrLastNameWhenFindByFirstNameOrLastNameShouldReturnTwoUsers() { + assertThat(simpleUserRepository + .findByFirstNameOrLastName("David", "LastName1") + .size(), equalTo(2)); + } + + @Test + public void givenUsersWhenFindAllOrderByFirstNameAscShouldReturnFirstAdamLastPeter() { + List users = simpleUserRepository.findAllOrderByFirstNameAsc(); + assertThat(users + .get(0) + .getFirstName(), equalTo("Adam")); + assertThat(users + .get(3) + .getFirstName(), equalTo("Peter")); + } + + @Test + public void givenUsersWhenFindAllOrderByFirstNameAscLastNameDescShouldReturnFirstAdamLastPeter() { + List users = simpleUserRepository.findAllOrderByFirstNameAscLastNameDesc(); + assertThat(users + .get(0) + .getFirstName(), equalTo("Adam")); + assertThat(users + .get(3) + .getFirstName(), equalTo("Peter")); + } + + @Test + public void givenUsersWhenFindTop2ShouldReturnTwoUsers() { + assertThat(simpleUserRepository + .findTop2OrderByFirstNameAsc() + .size(), equalTo(2)); + } + + @Test + public void givenUsersWhenFindFirst2ShouldReturnTwoUsers() { + assertThat(simpleUserRepository + .findFirst2OrderByFirstNameAsc() + .size(), equalTo(2)); + } + + @Test + public void givenPagesWithSizeTwoWhenFindAllOrderByFirstNameAscShouldReturnTwoPages() { + assertThat(simpleUserRepository + .findAllOrderByFirstNameAsc(0, 2) + .size(), equalTo(2)); + assertThat(simpleUserRepository + .findAllOrderByFirstNameAsc(2, 4) + .size(), equalTo(2)); + } + +} diff --git a/deltaspike/src/test/java/baeldung/test/UserRepositoryUnitTest.java b/deltaspike/src/test/java/baeldung/test/UserRepositoryUnitTest.java new file mode 100644 index 0000000000..bd07bf2730 --- /dev/null +++ b/deltaspike/src/test/java/baeldung/test/UserRepositoryUnitTest.java @@ -0,0 +1,55 @@ +package baeldung.test; + +import baeldung.data.UserRepository; +import org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner; +import org.junit.Test; +import org.junit.runner.RunWith; + +import javax.inject.Inject; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + +/** + * Created by adam. + */ +@RunWith(CdiTestRunner.class) +public class UserRepositoryUnitTest { + + @Inject private UserRepository userRepository; + + @Test + public void givenFourUsersWhenFindAllShouldReturnFourUsers() { + assertThat(userRepository + .findAll() + .size(), equalTo(4)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenFindByFirstNameShouldReturnTwoUsers() { + assertThat(userRepository + .findByFirstName("Adam") + .size(), equalTo(2)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenFindUsersWithFirstNameShouldReturnTwoUsers() { + assertThat(userRepository + .findUsersWithFirstName("Adam") + .size(), equalTo(2)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenFindUsersWithFirstNameNativeShouldReturnTwoUsers() { + assertThat(userRepository + .findUsersWithFirstNameNative("Adam") + .size(), equalTo(2)); + } + + @Test + public void givenTwoUsersWithSpecifiedLastNameWhenFindByLastNameShouldReturnTwoUsers() { + assertThat(userRepository + .findByLastName("LastName3") + .size(), equalTo(2)); + } +} diff --git a/deltaspike/src/test/resources/META-INF/apache-deltaspike.properties b/deltaspike/src/test/resources/META-INF/apache-deltaspike.properties index a861ad729a..787e58ade0 100644 --- a/deltaspike/src/test/resources/META-INF/apache-deltaspike.properties +++ b/deltaspike/src/test/resources/META-INF/apache-deltaspike.properties @@ -1 +1,3 @@ globalAlternatives.org.apache.deltaspike.jpa.spi.transaction.TransactionStrategy=org.apache.deltaspike.jpa.impl.transaction.BeanManagedUserTransactionStrategy +org.apache.deltaspike.ProjectStage=UnitTest +deltaspike.testcontrol.stop_container=false \ No newline at end of file diff --git a/deltaspike/src/test/resources/META-INF/beans.xml b/deltaspike/src/test/resources/META-INF/beans.xml new file mode 100644 index 0000000000..346b484f2f --- /dev/null +++ b/deltaspike/src/test/resources/META-INF/beans.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/deltaspike/src/test/resources/META-INF/persistence.xml b/deltaspike/src/test/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..ee69855138 --- /dev/null +++ b/deltaspike/src/test/resources/META-INF/persistence.xml @@ -0,0 +1,41 @@ + + + + java:jboss/datasources/baeldung-jee7-seedTestDS + + + + + + + + java:jboss/datasources/baeldung-jee7-seedTestSecondaryDS + + + + + + + + org.hibernate.jpa.HibernatePersistenceProvider + + baeldung.model.User + baeldung.model.Address + + + + + + + + + + + + + + diff --git a/deltaspike/src/test/resources/META-INF/test-persistence.xml b/deltaspike/src/test/resources/META-INF/test-persistence.xml deleted file mode 100644 index bc9fbcbeef..0000000000 --- a/deltaspike/src/test/resources/META-INF/test-persistence.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - java:jboss/datasources/baeldung-jee7-seedTestDS - - - - - - - java:jboss/datasources/baeldung-jee7-seedTestSecondaryDS - - - - - - diff --git a/deltaspike/src/test/resources/arquillian.xml b/deltaspike/src/test/resources/arquillian.xml index 14f9e53bbd..7f02023089 100644 --- a/deltaspike/src/test/resources/arquillian.xml +++ b/deltaspike/src/test/resources/arquillian.xml @@ -28,12 +28,4 @@ - - - - - target\wildfly-run\wildfly-10.0.0.Final - - - diff --git a/deltaspike/src/test/resources/import.sql b/deltaspike/src/test/resources/import.sql new file mode 100644 index 0000000000..f6e06ecee4 --- /dev/null +++ b/deltaspike/src/test/resources/import.sql @@ -0,0 +1,6 @@ +INSERT INTO ADDRESS(ID, STREET, CITY, POSTCODE) VALUES (1, 'Oxford', 'London', 'N121'); + +INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (1, 'Adam', 'LastName1', null); +INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (2, 'David', 'LastName2', null); +INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (3, 'Adam', 'LastName3', null); +INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (4, 'Peter', 'LastName3', 1); \ No newline at end of file diff --git a/disruptor/pom.xml b/disruptor/pom.xml index cc914cff7e..c26dcc0cd4 100644 --- a/disruptor/pom.xml +++ b/disruptor/pom.xml @@ -1,5 +1,5 @@ + 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 disruptor @@ -36,25 +36,10 @@ - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - prepare-package - - copy-dependencies - - - ${project.build.directory}/libs - - - - org.apache.maven.plugins maven-jar-plugin + ${maven-jar-plugin.version} @@ -91,6 +76,7 @@ org.apache.maven.plugins maven-shade-plugin + ${maven-shade-plugin.version} @@ -99,8 +85,7 @@ true - + org.baeldung.executable.ExecutableMavenJar @@ -111,6 +96,7 @@ com.jolira onejar-maven-plugin + ${onejar-maven-plugin.version} @@ -134,6 +120,10 @@ 6.10 3.6.1 + + 2.4.3 + 3.0.2 + 1.4.4 \ No newline at end of file diff --git a/disruptor/src/main/resources/logback.xml b/disruptor/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/disruptor/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/dozer/pom.xml b/dozer/pom.xml index 0b7f85ddb4..5720001acf 100644 --- a/dozer/pom.xml +++ b/dozer/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung dozer diff --git a/dozer/src/main/resources/logback.xml b/dozer/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/dozer/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/drools/pom.xml b/drools/pom.xml index 60df7157f2..009ac8acec 100644 --- a/drools/pom.xml +++ b/drools/pom.xml @@ -1,15 +1,15 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 drools - com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring - + com.baeldung + parent-spring-4 + 0.0.1-SNAPSHOT + ../parent-spring-4 + @@ -48,13 +48,18 @@ poi-ooxml ${apache-poi-version} + + org.optaplanner + optaplanner-core + ${opta-planner-version} + 4.4.6 7.4.1.Final 3.13 - 4.3.6.RELEASE + 7.10.0.Final diff --git a/drools/src/main/java/com/baeldung/drools/optaplanner/CourseSchedule.java b/drools/src/main/java/com/baeldung/drools/optaplanner/CourseSchedule.java new file mode 100644 index 0000000000..7b2ba117a1 --- /dev/null +++ b/drools/src/main/java/com/baeldung/drools/optaplanner/CourseSchedule.java @@ -0,0 +1,63 @@ +package com.baeldung.drools.optaplanner; + +import java.util.ArrayList; +import java.util.List; + +import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty; +import org.optaplanner.core.api.domain.solution.PlanningScore; +import org.optaplanner.core.api.domain.solution.PlanningSolution; +import org.optaplanner.core.api.domain.solution.drools.ProblemFactCollectionProperty; +import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider; +import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@PlanningSolution +public class CourseSchedule { + + Logger logger = LoggerFactory.getLogger("CourseSchedule"); + + private List roomList; + private List periodList; + private List lectureList; + private HardSoftScore score; + + public CourseSchedule(){ + roomList = new ArrayList<>(); + periodList = new ArrayList<>(); + lectureList = new ArrayList<>(); + } + + @ValueRangeProvider(id = "availableRooms") + @ProblemFactCollectionProperty + public List getRoomList() { + return roomList; + } + + @ValueRangeProvider(id = "availablePeriods") + @ProblemFactCollectionProperty + public List getPeriodList() { + return periodList; + } + + @PlanningEntityCollectionProperty + public List getLectureList() { + return lectureList; + } + + @PlanningScore + public HardSoftScore getScore() { + return score; + } + + public void setScore(HardSoftScore score) { + this.score = score; + } + + public void printCourseSchedule() { + lectureList.stream() + .map(c -> "Lecture in Room " + c.getRoomNumber().toString() + " during Period " + c.getPeriod().toString()) + .forEach(k -> logger.info(k)); + } + +} diff --git a/drools/src/main/java/com/baeldung/drools/optaplanner/Lecture.java b/drools/src/main/java/com/baeldung/drools/optaplanner/Lecture.java new file mode 100644 index 0000000000..193cdb08b1 --- /dev/null +++ b/drools/src/main/java/com/baeldung/drools/optaplanner/Lecture.java @@ -0,0 +1,30 @@ +package com.baeldung.drools.optaplanner; + +import org.optaplanner.core.api.domain.entity.PlanningEntity; +import org.optaplanner.core.api.domain.variable.PlanningVariable; + +@PlanningEntity +public class Lecture { + + private Integer roomNumber; + private Integer period; + + @PlanningVariable(valueRangeProviderRefs = {"availablePeriods"}) + public Integer getPeriod() { + return period; + } + + @PlanningVariable(valueRangeProviderRefs = {"availableRooms"}) + public Integer getRoomNumber() { + return roomNumber; + } + + public void setPeriod(Integer period) { + this.period = period; + } + + public void setRoomNumber(Integer roomNumber) { + this.roomNumber = roomNumber; + } + +} diff --git a/drools/src/main/java/com/baeldung/drools/optaplanner/ScoreCalculator.java b/drools/src/main/java/com/baeldung/drools/optaplanner/ScoreCalculator.java new file mode 100644 index 0000000000..86501cdccd --- /dev/null +++ b/drools/src/main/java/com/baeldung/drools/optaplanner/ScoreCalculator.java @@ -0,0 +1,32 @@ +package com.baeldung.drools.optaplanner; + +import java.util.HashSet; + +import org.optaplanner.core.api.score.Score; +import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore; +import org.optaplanner.core.impl.score.director.easy.EasyScoreCalculator; + +public class ScoreCalculator implements EasyScoreCalculator { + + @Override + public Score calculateScore(CourseSchedule courseSchedule) { + int hardScore = 0; + int softScore = 0; + + HashSet occupiedRooms = new HashSet<>(); + for (Lecture lecture : courseSchedule.getLectureList()) { + if(lecture.getPeriod() != null && lecture.getRoomNumber() != null) { + String roomInUse = lecture.getPeriod().toString() + ":" + lecture.getRoomNumber().toString(); + if (occupiedRooms.contains(roomInUse)) { + hardScore += -1; + } else { + occupiedRooms.add(roomInUse); + } + } else { + hardScore += -1; + } + } + + return HardSoftScore.valueOf(hardScore, softScore); + } +} diff --git a/drools/src/main/resources/courseSchedule.drl b/drools/src/main/resources/courseSchedule.drl new file mode 100644 index 0000000000..35dd57df84 --- /dev/null +++ b/drools/src/main/resources/courseSchedule.drl @@ -0,0 +1,14 @@ +package com.baeldung.drools.optaplanner + +import com.baeldung.drools.optaplanner.Lecture; +import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScoreHolder; + +global HardSoftScoreHolder scoreHolder; + +rule "noNullRoomPeriod" + when + Lecture( roomNumber == null ); + Lecture( period == null ); + then + scoreHolder.addHardConstraintMatch(kcontext, -1); +end \ No newline at end of file diff --git a/drools/src/main/resources/courseScheduleSolverConfigDrools.xml b/drools/src/main/resources/courseScheduleSolverConfigDrools.xml new file mode 100644 index 0000000000..7cf95fdcd3 --- /dev/null +++ b/drools/src/main/resources/courseScheduleSolverConfigDrools.xml @@ -0,0 +1,12 @@ + + + + + + courseSchedule.drl + + + + 10 + + \ No newline at end of file diff --git a/drools/src/main/resources/courseScheduleSolverConfiguration.xml b/drools/src/main/resources/courseScheduleSolverConfiguration.xml new file mode 100644 index 0000000000..dfedb8f2fd --- /dev/null +++ b/drools/src/main/resources/courseScheduleSolverConfiguration.xml @@ -0,0 +1,12 @@ + + + + + + com.baeldung.drools.optaplanner.ScoreCalculator + + + + 10 + + \ No newline at end of file diff --git a/drools/src/main/resources/logback.xml b/drools/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/drools/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingIntegrationTest.java b/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingIntegrationTest.java new file mode 100644 index 0000000000..fd49f94479 --- /dev/null +++ b/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingIntegrationTest.java @@ -0,0 +1,36 @@ +package com.baeldung.drools.backward_chaining; + +import org.junit.Before; +import org.junit.Test; +import org.kie.api.runtime.KieSession; + +import com.baeldung.drools.config.DroolsBeanFactory; +import com.baeldung.drools.model.Fact; +import com.baeldung.drools.model.Result; + +import static junit.framework.TestCase.assertEquals; + +public class BackwardChainingIntegrationTest { + private Result result; + private KieSession ksession; + + @Before + public void before() { + result = new Result(); + ksession = new DroolsBeanFactory().getKieSession(); + } + + @Test + public void whenWallOfChinaIsGiven_ThenItBelongsToPlanetEarth() { + + ksession.setGlobal("result", result); + ksession.insert(new Fact("Asia", "Planet Earth")); + ksession.insert(new Fact("China", "Asia")); + ksession.insert(new Fact("Great Wall of China", "China")); + + ksession.fireAllRules(); + + // Assert Decision one + assertEquals(result.getValue(), "Decision one taken: Great Wall of China BELONGS TO Planet Earth"); + } +} diff --git a/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingTest.java b/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingTest.java deleted file mode 100644 index f49d0b82de..0000000000 --- a/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.drools.backward_chaining; - -import org.junit.Before; -import org.junit.Test; -import org.kie.api.runtime.KieSession; - -import com.baeldung.drools.config.DroolsBeanFactory; -import com.baeldung.drools.model.Fact; -import com.baeldung.drools.model.Result; - -import static junit.framework.TestCase.assertEquals; - -public class BackwardChainingTest { - private Result result; - private KieSession ksession; - - @Before - public void before() { - result = new Result(); - ksession = new DroolsBeanFactory().getKieSession(); - } - - @Test - public void whenWallOfChinaIsGiven_ThenItBelongsToPlanetEarth() { - - ksession.setGlobal("result", result); - ksession.insert(new Fact("Asia", "Planet Earth")); - ksession.insert(new Fact("China", "Asia")); - ksession.insert(new Fact("Great Wall of China", "China")); - - ksession.fireAllRules(); - - // Assert Decision one - assertEquals(result.getValue(), "Decision one taken: Great Wall of China BELONGS TO Planet Earth"); - } -} diff --git a/drools/src/test/java/com/baeldung/drools/optaplanner/OptaPlannerUnitTest.java b/drools/src/test/java/com/baeldung/drools/optaplanner/OptaPlannerUnitTest.java new file mode 100644 index 0000000000..1880e30b86 --- /dev/null +++ b/drools/src/test/java/com/baeldung/drools/optaplanner/OptaPlannerUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.drools.optaplanner; + +import java.util.Arrays; + +import org.junit.Assert; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.optaplanner.core.api.solver.Solver; +import org.optaplanner.core.api.solver.SolverFactory; + +public class OptaPlannerUnitTest { + + static CourseSchedule unsolvedCourseSchedule; + + @BeforeAll + public static void setUp() { + + unsolvedCourseSchedule = new CourseSchedule(); + + for(int i = 0; i < 10; i++){ + unsolvedCourseSchedule.getLectureList().add(new Lecture()); + } + + unsolvedCourseSchedule.getPeriodList().addAll(Arrays.asList(new Integer[] { 1, 2, 3 })); + unsolvedCourseSchedule.getRoomList().addAll(Arrays.asList(new Integer[] { 1, 2 })); + } + + @Test + public void test_whenCustomJavaSolver() { + + SolverFactory solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfiguration.xml"); + Solver solver = solverFactory.buildSolver(); + CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule); + + Assert.assertNotNull(solvedCourseSchedule.getScore()); + Assert.assertEquals(-4, solvedCourseSchedule.getScore().getHardScore()); + } + + @Test + public void test_whenDroolsSolver() { + + SolverFactory solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfigDrools.xml"); + Solver solver = solverFactory.buildSolver(); + CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule); + + Assert.assertNotNull(solvedCourseSchedule.getScore()); + Assert.assertEquals(0, solvedCourseSchedule.getScore().getHardScore()); + } +} diff --git a/dubbo/pom.xml b/dubbo/pom.xml index 81ff921f2a..6f81ec5cff 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 dubbo @@ -15,12 +15,6 @@ dubbo ${dubbo.version} - - junit - junit - ${junit.version} - test - org.apache.zookeeper zookeeper @@ -34,9 +28,6 @@ - UTF-8 - UTF-8 - 1.8 2.5.7 3.4.11 0.10 diff --git a/dubbo/src/main/resources/logback.xml b/dubbo/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/dubbo/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/eclipse/formatter.xml b/eclipse/formatter.xml index 808f65cda9..6887946a4c 100644 --- a/eclipse/formatter.xml +++ b/eclipse/formatter.xml @@ -1,297 +1,5 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ejb/README.md b/ejb/README.md index 994781b064..f47277bf8f 100644 --- a/ejb/README.md +++ b/ejb/README.md @@ -3,3 +3,4 @@ - [Guide to EJB Set-up](http://www.baeldung.com/ejb-intro) - [Java EE Session Beans](http://www.baeldung.com/ejb-session-beans) - [Introduction to EJB JNDI Lookup on WildFly Application Server](http://www.baeldung.com/wildfly-ejb-jndi) +- [A Guide to Message Driven Beans in EJB](http://www.baeldung.com/ejb-message-driven-beans) diff --git a/ejb/ejb-client/pom.xml b/ejb/ejb-client/pom.xml index 83dd0aef30..6231030cec 100755 --- a/ejb/ejb-client/pom.xml +++ b/ejb/ejb-client/pom.xml @@ -1,9 +1,8 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 ejb-client - EJB3 Client Maven EJB3 Client Maven @@ -17,7 +16,6 @@ org.wildfly wildfly-ejb-client-bom pom - import com.baeldung.ejb @@ -25,20 +23,4 @@ ejb - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - **/*EJBSetupTest.java - - - - - - \ No newline at end of file diff --git a/ejb/ejb-client/src/main/resources/logback.xml b/ejb/ejb-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/ejb/ejb-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/ejb/ejb-client/src/test/java/com/baeldung/ejb/wildfly/TextApplicationIntegrationTest.java b/ejb/ejb-client/src/test/java/com/baeldung/ejb/wildfly/TextApplicationIntegrationTest.java new file mode 100644 index 0000000000..8dff116ca1 --- /dev/null +++ b/ejb/ejb-client/src/test/java/com/baeldung/ejb/wildfly/TextApplicationIntegrationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.ejb.wildfly; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import javax.naming.NamingException; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import static org.junit.Assert.*; + +public class TextApplicationIntegrationTest { + + private static ByteArrayOutputStream outContent; + + @BeforeClass + public static void setUpPrintStreamInstance() { + outContent = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outContent)); + } + + @AfterClass + public static void tearDownByteArrayOutputStream() { + outContent = null; + } + + @Test + public void givenInputString_whenCompareTtoStringPrintedToConsole_thenSuccessful() throws NamingException { + TextApplication.main(new String[]{}); + assertEquals("SAMPLE TEXT", outContent.toString()); + } +} \ No newline at end of file diff --git a/ejb/ejb-client/src/test/java/com/baeldung/ejb/wildfly/TextApplicationTest.java b/ejb/ejb-client/src/test/java/com/baeldung/ejb/wildfly/TextApplicationTest.java deleted file mode 100644 index c0446eaea6..0000000000 --- a/ejb/ejb-client/src/test/java/com/baeldung/ejb/wildfly/TextApplicationTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.ejb.wildfly; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import javax.naming.NamingException; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import static org.junit.Assert.*; - -public class TextApplicationTest { - - private static ByteArrayOutputStream outContent; - - @BeforeClass - public static void setUpPrintStreamInstance() { - outContent = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outContent)); - } - - @AfterClass - public static void tearDownByteArrayOutputStream() { - outContent = null; - } - - @Test - public void givenInputString_whenCompareTtoStringPrintedToConsole_thenSuccessful() throws NamingException { - TextApplication.main(new String[]{}); - assertEquals("SAMPLE TEXT", outContent.toString()); - } -} \ No newline at end of file diff --git a/ejb/ejb-remote/pom.xml b/ejb/ejb-remote/pom.xml index b8f1f0dcc0..fffbbdb1da 100755 --- a/ejb/ejb-remote/pom.xml +++ b/ejb/ejb-remote/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 ejb-remote ejb @@ -57,7 +57,7 @@ - + wildfly-runtime @@ -74,7 +74,7 @@ 9990 testUser admin1234! - ${build.finalName}.jar + ${project.build.finalName}.jar diff --git a/ejb/ejb-remote/src/main/resources/logback.xml b/ejb/ejb-remote/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/ejb/ejb-remote/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/ejb/ejb-session-beans/pom.xml b/ejb/ejb-session-beans/pom.xml index 6afd7f2c6d..14ab0790e7 100644 --- a/ejb/ejb-session-beans/pom.xml +++ b/ejb/ejb-session-beans/pom.xml @@ -13,7 +13,7 @@ org.jboss.arquillian arquillian-bom - 1.1.13.Final + ${arquillian-bom.version} import pom @@ -27,12 +27,6 @@ ${javaee-api.version} provided - - junit - junit - ${junit.version} - test - org.jboss.arquillian.junit arquillian-junit-container @@ -56,7 +50,7 @@ org.glassfish.main.extras glassfish-embedded-all - 3.1.2 + ${glassfish-embedded-all.version} test @@ -67,7 +61,7 @@ maven-war-plugin - 2.4 + ${maven-war-plugin.version} false @@ -77,13 +71,14 @@ UTF-8 - 1.1.12.Final + 1.1.13.Final 2.2.6 1.1.12.Final 1.0.0.Final 4.12 7.0 1.0.0.CR4 + 3.1.2 \ No newline at end of file diff --git a/ejb/ejb-session-beans/src/main/resources/logback.xml b/ejb/ejb-session-beans/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/ejb/ejb-session-beans/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/ejb/ejb-session-beans/src/test/java/com/baeldung/ejb/test/stateful/StatefulEJBIntegrationTest.java b/ejb/ejb-session-beans/src/test/java/com/baeldung/ejb/test/stateful/StatefulEJBIntegrationTest.java new file mode 100644 index 0000000000..cc35921e45 --- /dev/null +++ b/ejb/ejb-session-beans/src/test/java/com/baeldung/ejb/test/stateful/StatefulEJBIntegrationTest.java @@ -0,0 +1,51 @@ +package com.baeldung.ejb.test.stateful; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.EmptyAsset; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; + +import com.baeldung.ejb.stateful.EJBClient1; +import com.baeldung.ejb.stateful.EJBClient2; +import com.baeldung.ejb.stateful.StatefulEJB; + +import javax.inject.Inject; + + +@RunWith(Arquillian.class) +public class StatefulEJBIntegrationTest { + + @Inject + private EJBClient1 ejbClient1; + + @Inject + private EJBClient2 ejbClient2; + + @Test + public void givenOneStatefulBean_whenTwoClientsSetValueOnBean_thenClientStateIsMaintained() { + + // act + ejbClient1.statefulEJB.name = "Client 1"; + ejbClient2.statefulEJB.name = "Client 2"; + + // assert + Assert.assertNotEquals(ejbClient1.statefulEJB.name, ejbClient2.statefulEJB.name); + Assert.assertEquals("Client 1", ejbClient1.statefulEJB.name); + Assert.assertEquals("Client 2", ejbClient2.statefulEJB.name); + + } + + @Deployment + public static JavaArchive createDeployment() { + return ShrinkWrap.create(JavaArchive.class) + .addClass(StatefulEJB.class) + .addClass(EJBClient1.class) + .addClass(EJBClient2.class) + .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); + } + +} diff --git a/ejb/ejb-session-beans/src/test/java/com/baeldung/ejb/test/stateful/StatefulEJBTest.java b/ejb/ejb-session-beans/src/test/java/com/baeldung/ejb/test/stateful/StatefulEJBTest.java deleted file mode 100644 index 2f3e45a769..0000000000 --- a/ejb/ejb-session-beans/src/test/java/com/baeldung/ejb/test/stateful/StatefulEJBTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.ejb.test.stateful; - -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.junit.Arquillian; -import org.jboss.shrinkwrap.api.ShrinkWrap; -import org.jboss.shrinkwrap.api.asset.EmptyAsset; -import org.jboss.shrinkwrap.api.spec.JavaArchive; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; - -import com.baeldung.ejb.stateful.EJBClient1; -import com.baeldung.ejb.stateful.EJBClient2; -import com.baeldung.ejb.stateful.StatefulEJB; - -import javax.inject.Inject; - - -@RunWith(Arquillian.class) -public class StatefulEJBTest { - - @Inject - private EJBClient1 ejbClient1; - - @Inject - private EJBClient2 ejbClient2; - - @Test - public void givenOneStatefulBean_whenTwoClientsSetValueOnBean_thenClientStateIsMaintained() { - - // act - ejbClient1.statefulEJB.name = "Client 1"; - ejbClient2.statefulEJB.name = "Client 2"; - - // assert - Assert.assertNotEquals(ejbClient1.statefulEJB.name, ejbClient2.statefulEJB.name); - Assert.assertEquals("Client 1", ejbClient1.statefulEJB.name); - Assert.assertEquals("Client 2", ejbClient2.statefulEJB.name); - - } - - @Deployment - public static JavaArchive createDeployment() { - return ShrinkWrap.create(JavaArchive.class) - .addClass(StatefulEJB.class) - .addClass(EJBClient1.class) - .addClass(EJBClient2.class) - .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); - } - -} diff --git a/ejb/ejb-session-beans/src/test/java/com/baeldung/ejb/test/stateless/StatelessEJBIntegrationTest.java b/ejb/ejb-session-beans/src/test/java/com/baeldung/ejb/test/stateless/StatelessEJBIntegrationTest.java new file mode 100644 index 0000000000..c80ca93c0d --- /dev/null +++ b/ejb/ejb-session-beans/src/test/java/com/baeldung/ejb/test/stateless/StatelessEJBIntegrationTest.java @@ -0,0 +1,62 @@ +package com.baeldung.ejb.test.stateless; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.EmptyAsset; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; + +import com.baeldung.ejb.stateless.EJBClient1; +import com.baeldung.ejb.stateless.EJBClient2; +import com.baeldung.ejb.stateless.StatelessEJB; + +import javax.inject.Inject; + + +@RunWith(Arquillian.class) +public class StatelessEJBIntegrationTest { + + @Inject + private EJBClient1 ejbClient1; + + @Inject + private EJBClient2 ejbClient2; + + @Test + public void givenOneStatelessBean_whenStateIsSetInOneBean_secondBeanShouldHaveSameState() { + + // act + ejbClient1.statelessEJB.name = "Client 1"; + + // assert + Assert.assertEquals("Client 1", ejbClient1.statelessEJB.name); + Assert.assertEquals("Client 1", ejbClient2.statelessEJB.name); + + } + + + @Test + public void givenOneStatelessBean_whenStateIsSetInBothBeans_secondBeanShouldHaveSecondBeanState() { + + // act + ejbClient1.statelessEJB.name = "Client 1"; + ejbClient2.statelessEJB.name = "Client 2"; + + // assert + Assert.assertEquals("Client 2", ejbClient2.statelessEJB.name); + + } + + @Deployment + public static JavaArchive createDeployment() { + return ShrinkWrap.create(JavaArchive.class) + .addClass(StatelessEJB.class) + .addClass(EJBClient1.class) + .addClass(EJBClient2.class) + .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); + } + +} diff --git a/ejb/ejb-session-beans/src/test/java/com/baeldung/ejb/test/stateless/StatelessEJBTest.java b/ejb/ejb-session-beans/src/test/java/com/baeldung/ejb/test/stateless/StatelessEJBTest.java deleted file mode 100644 index 9f88d478b7..0000000000 --- a/ejb/ejb-session-beans/src/test/java/com/baeldung/ejb/test/stateless/StatelessEJBTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.ejb.test.stateless; - -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.junit.Arquillian; -import org.jboss.shrinkwrap.api.ShrinkWrap; -import org.jboss.shrinkwrap.api.asset.EmptyAsset; -import org.jboss.shrinkwrap.api.spec.JavaArchive; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; - -import com.baeldung.ejb.stateless.EJBClient1; -import com.baeldung.ejb.stateless.EJBClient2; -import com.baeldung.ejb.stateless.StatelessEJB; - -import javax.inject.Inject; - - -@RunWith(Arquillian.class) -public class StatelessEJBTest { - - @Inject - private EJBClient1 ejbClient1; - - @Inject - private EJBClient2 ejbClient2; - - @Test - public void givenOneStatelessBean_whenStateIsSetInOneBean_secondBeanShouldHaveSameState() { - - // act - ejbClient1.statelessEJB.name = "Client 1"; - - // assert - Assert.assertEquals("Client 1", ejbClient1.statelessEJB.name); - Assert.assertEquals("Client 1", ejbClient2.statelessEJB.name); - - } - - - @Test - public void givenOneStatelessBean_whenStateIsSetInBothBeans_secondBeanShouldHaveSecondBeanState() { - - // act - ejbClient1.statelessEJB.name = "Client 1"; - ejbClient2.statelessEJB.name = "Client 2"; - - // assert - Assert.assertEquals("Client 2", ejbClient2.statelessEJB.name); - - } - - @Deployment - public static JavaArchive createDeployment() { - return ShrinkWrap.create(JavaArchive.class) - .addClass(StatelessEJB.class) - .addClass(EJBClient1.class) - .addClass(EJBClient2.class) - .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); - } - -} diff --git a/ejb/pom.xml b/ejb/pom.xml index e61c2a0b7b..4cb700d087 100755 --- a/ejb/pom.xml +++ b/ejb/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.ejb ejb @@ -17,7 +17,6 @@ ejb-remote - ejb-client ejb-session-beans @@ -83,9 +82,6 @@ - UTF-8 - UTF-8 - 1.8 2.5.7 3.4.11 0.10 diff --git a/ejb/wildfly/pom.xml b/ejb/wildfly/pom.xml index ad73f4817e..53d10a90ed 100644 --- a/ejb/wildfly/pom.xml +++ b/ejb/wildfly/pom.xml @@ -2,9 +2,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.wildfly - wildfly-example + wildfly 0.0.1-SNAPSHOT pom + wildfly com.baeldung.ejb @@ -83,7 +84,6 @@ 1.8 1.8 - UTF-8 7.0 10.1.0.Final 5.2.3.Final diff --git a/ejb/wildfly/widlfly-web/pom.xml b/ejb/wildfly/widlfly-web/pom.xml index a337e8ef60..559c5f1755 100644 --- a/ejb/wildfly/widlfly-web/pom.xml +++ b/ejb/wildfly/widlfly-web/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 widlfly-web war diff --git a/ejb/wildfly/widlfly-web/src/main/resources/logback.xml b/ejb/wildfly/widlfly-web/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/ejb/wildfly/widlfly-web/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/ejb/wildfly/wildfly-ear/pom.xml b/ejb/wildfly/wildfly-ear/pom.xml index f264594652..d1e47ecd0f 100644 --- a/ejb/wildfly/wildfly-ear/pom.xml +++ b/ejb/wildfly/wildfly-ear/pom.xml @@ -40,7 +40,7 @@ maven-ear-plugin - 2.10.1 + ${maven-ear-plugin.version} lib/ 7 @@ -56,8 +56,13 @@ org.wildfly.plugins wildfly-maven-plugin - 1.2.0.Final + ${wildfly-maven-plugin.version} + + + 2.10.1 + 1.2.0.Final + \ No newline at end of file diff --git a/ejb/wildfly/wildfly-ejb-interfaces/pom.xml b/ejb/wildfly/wildfly-ejb-interfaces/pom.xml index 61a630b899..ec502f2ab3 100644 --- a/ejb/wildfly/wildfly-ejb-interfaces/pom.xml +++ b/ejb/wildfly/wildfly-ejb-interfaces/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 wildfly-ejb-interfaces diff --git a/ejb/wildfly/wildfly-ejb-interfaces/src/main/resources/logback.xml b/ejb/wildfly/wildfly-ejb-interfaces/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/ejb/wildfly/wildfly-ejb-interfaces/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/ejb/wildfly/wildfly-ejb/pom.xml b/ejb/wildfly/wildfly-ejb/pom.xml index 900f93c0ba..2c87ec8449 100644 --- a/ejb/wildfly/wildfly-ejb/pom.xml +++ b/ejb/wildfly/wildfly-ejb/pom.xml @@ -15,7 +15,7 @@ javax.ejb javax.ejb-api - 3.2 + ${ejb.version} provided @@ -42,9 +42,13 @@ org.apache.maven.plugins maven-ejb-plugin - 3.2 + ${ejb.version} + + + 3.2 + \ No newline at end of file diff --git a/ejb/wildfly/wildfly-ejb/src/main/resources/logback.xml b/ejb/wildfly/wildfly-ejb/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/ejb/wildfly/wildfly-ejb/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/ejb/wildfly/wildfly-jpa/pom.xml b/ejb/wildfly/wildfly-jpa/pom.xml index 18e86b1b31..12cf2c81e4 100644 --- a/ejb/wildfly/wildfly-jpa/pom.xml +++ b/ejb/wildfly/wildfly-jpa/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 wildfly-jpa diff --git a/ejb/wildfly/wildfly-jpa/src/main/resources/logback.xml b/ejb/wildfly/wildfly-jpa/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/ejb/wildfly/wildfly-jpa/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/ejb/wildfly/wildfly-mdb/pom.xml b/ejb/wildfly/wildfly-mdb/pom.xml new file mode 100644 index 0000000000..186ddc50c0 --- /dev/null +++ b/ejb/wildfly/wildfly-mdb/pom.xml @@ -0,0 +1,22 @@ + + 4.0.0 + wildfly-mdb + wildfly-mdb + + + com.baeldung.wildfly + wildfly-example + 0.0.1-SNAPSHOT + + + + + + javax + javaee-api + ${javaee-api.version} + provided + + + \ No newline at end of file diff --git a/ejb/wildfly/wildfly-mdb/src/com/baeldung/wildfly/mdb/ReadMessageMDB.java b/ejb/wildfly/wildfly-mdb/src/com/baeldung/wildfly/mdb/ReadMessageMDB.java new file mode 100644 index 0000000000..6997f92201 --- /dev/null +++ b/ejb/wildfly/wildfly-mdb/src/com/baeldung/wildfly/mdb/ReadMessageMDB.java @@ -0,0 +1,28 @@ +package com.baeldung.wildfly.mdb; + +import javax.ejb.ActivationConfigProperty; +import javax.ejb.MessageDriven; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageListener; +import javax.jms.TextMessage; + +/** + * Message-Driven Bean implementation class for: ReadMessageMDB + */ +@MessageDriven( + activationConfig = { + @ActivationConfigProperty(propertyName = "destination", propertyValue = "tutorialQueue"), + @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") +}) +public class ReadMessageMDB implements MessageListener { + + public void onMessage(Message message) { + TextMessage textMessage = (TextMessage) message; + try { + System.out.println("Message received: " + textMessage.getText()); + } catch (JMSException e) { + System.out.println("Error while trying to consume messages: " + e.getMessage()); + } + } +} \ No newline at end of file diff --git a/ejb/wildfly/wildfly-mdb/src/com/baeldung/wildfly/mdb/SendMessageServlet.java b/ejb/wildfly/wildfly-mdb/src/com/baeldung/wildfly/mdb/SendMessageServlet.java new file mode 100644 index 0000000000..7dcd04b43f --- /dev/null +++ b/ejb/wildfly/wildfly-mdb/src/com/baeldung/wildfly/mdb/SendMessageServlet.java @@ -0,0 +1,52 @@ +package baeldung.com.example.servlet; + +import java.io.IOException; + +import javax.jms.Connection; +import javax.jms.ConnectionFactory; +import javax.jms.JMSException; +import javax.jms.MessageProducer; +import javax.jms.Queue; +import javax.jms.Session; +import javax.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + + +@WebServlet("/SendMessageServlet") +public class SendMessageServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { + String text = req.getParameter("text") != null ? req.getParameter("text") : "Hello World"; + + try ( + Context ic = new InitialContext(); + + ConnectionFactory cf = (ConnectionFactory) ic.lookup("/ConnectionFactory"); + Queue queue = (Queue) ic.lookup("queue/tutorialQueue"); + + Connection connection = cf.createConnection(); + ) { + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer publisher = session.createProducer(queue); + + connection.start(); + + TextMessage message = session.createTextMessage(text); + publisher.send(message); + + } catch (NamingException | JMSException e) { + res.getWriter().println("Error while trying to send <" + text + "> message: " + e.getMessage()); + } + + res.getWriter().println("Message sent: " + text); + } + +} \ No newline at end of file diff --git a/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/AuditFilter.java b/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/AuditFilter.java deleted file mode 100644 index d24c0a94b3..0000000000 --- a/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/AuditFilter.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.enterprise.patterns.front.controller.filters; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import java.io.IOException; - -public class AuditFilter extends BaseFilter { - @Override - public void doFilter( - ServletRequest request, - ServletResponse response, - FilterChain chain - ) throws IOException, ServletException { - HttpServletRequest httpServletRequest = (HttpServletRequest) request; - HttpSession session = httpServletRequest.getSession(false); - if (session != null && session.getAttribute("username") != null) { - request.setAttribute("username", session.getAttribute("username")); - } - chain.doFilter(request, response); - } -} diff --git a/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/VisitorCounterFilter.java b/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/VisitorCounterFilter.java deleted file mode 100644 index 0ae7cd73fd..0000000000 --- a/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/VisitorCounterFilter.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.enterprise.patterns.front.controller.filters; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.annotation.WebFilter; -import java.io.IOException; - -@WebFilter(servletNames = "front-controller") -public class VisitorCounterFilter extends BaseFilter { - private int counter; - - @Override - public void doFilter( - ServletRequest request, - ServletResponse response, - FilterChain chain - ) throws IOException, ServletException { - request.setAttribute("counter", ++counter); - chain.doFilter(request, response); - } -} diff --git a/enterprise-patterns/pom.xml b/enterprise-patterns/pom.xml deleted file mode 100644 index 07842b8981..0000000000 --- a/enterprise-patterns/pom.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - 4.0.0 - com.baeldung.enterprise.patterns - enterprise-patterns-parent - pom - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - spring-dispatcher-servlet - - - diff --git a/ethereumj/.gitgnore b/ethereum/.gitgnore similarity index 100% rename from ethereumj/.gitgnore rename to ethereum/.gitgnore diff --git a/ethereum/README.md b/ethereum/README.md new file mode 100644 index 0000000000..d06ca09636 --- /dev/null +++ b/ethereum/README.md @@ -0,0 +1,6 @@ +## Ethereum + +### Relevant Articles: +- [Introduction to EthereumJ](http://www.baeldung.com/ethereumj) +- [Creating and Deploying Smart Contracts with Solidity](http://www.baeldung.com/smart-contracts-ethereum-solidity) +- [Lightweight Ethereum Clients Using Web3j](http://www.baeldung.com/web3j) diff --git a/ethereum/pom.xml b/ethereum/pom.xml new file mode 100644 index 0000000000..bd1bacb221 --- /dev/null +++ b/ethereum/pom.xml @@ -0,0 +1,231 @@ + + 4.0.0 + com.baeldung.ethereum + ethereum + 0.0.1-SNAPSHOT + ethereum + + + parent-spring-5 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-spring-5 + + + + + + + org.springframework.boot + spring-boot-starter + ${spring.boot.version} + + + + org.springframework.boot + spring-boot-starter-web + ${spring.boot.version} + + + org.springframework.boot + spring-boot-starter-tomcat + ${spring.boot.version} + + + + + org.springframework + spring-core + ${springframework.version} + + + org.springframework + spring-web + ${springframework.version} + + + org.springframework + spring-webmvc + ${springframework.version} + + + + + org.ethereum + ethereumj-core + ${ethereumj-core.version} + + + org.web3j + core + ${web3j.core.version} + + + + + com.fasterxml.jackson.core + jackson-core + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + + + + + javax.servlet + jstl + ${jstl.version} + + + javax.servlet + javax.servlet-api + ${javax-servlet.version} + + + javax.servlet.jsp.jstl + jstl-api + ${jstl.version} + + + javax.servlet.jsp + javax.servlet.jsp-api + ${javax-jsp.version} + + + + + org.slf4j + jcl-over-slf4j + ${slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + + org.springframework.boot + spring-boot-starter-test + test + ${spring.boot.version} + + + org.springframework + spring-context + ${springframework.version} + + + org.springframework + spring-test + ${springframework.version} + test + + + + + org.mockito + mockito-core + ${mockito.version} + + + org.hamcrest + hamcrest-core + + + test + + + junit + junit + ${junit.version} + test + + + org.hamcrest + hamcrest-core + + + + + org.hamcrest + hamcrest-library + ${hamcrest.version} + test + + + com.jayway.jsonpath + json-path + ${jsonpath.version} + + + + + ethereum + + + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} + + + org.apache.maven.plugins + maven-war-plugin + 3.0.0 + + src/main/webapp + false + + + + + + + + Ethereum + Ethereum + https://dl.bintray.com/ethereum/maven/ + + + + + UTF-8 + 1.8 + 8.5.4 + 1.5.0-RELEASE + 3.3.1 + 5.0.5.RELEASE + 1.5.6.RELEASE + 2.21.0 + 2.5.0 + 1.3 + 2.9.3 + 2.3.1 + 3.1.0 + 2.4.0 + 1.2 + 4.12 + 1.2.3 + 1.7.25 + 2.0.4.RELEASE + + + diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/ApplicationMain.java b/ethereum/src/main/java/com/baeldung/ethereumj/ApplicationMain.java similarity index 100% rename from ethereumj/src/main/java/com/baeldung/ethereumj/ApplicationMain.java rename to ethereum/src/main/java/com/baeldung/ethereumj/ApplicationMain.java diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/Constants.java b/ethereum/src/main/java/com/baeldung/ethereumj/Constants.java similarity index 100% rename from ethereumj/src/main/java/com/baeldung/ethereumj/Constants.java rename to ethereum/src/main/java/com/baeldung/ethereumj/Constants.java diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/beans/EthBean.java b/ethereum/src/main/java/com/baeldung/ethereumj/beans/EthBean.java similarity index 100% rename from ethereumj/src/main/java/com/baeldung/ethereumj/beans/EthBean.java rename to ethereum/src/main/java/com/baeldung/ethereumj/beans/EthBean.java diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/config/EthConfig.java b/ethereum/src/main/java/com/baeldung/ethereumj/config/EthConfig.java similarity index 100% rename from ethereumj/src/main/java/com/baeldung/ethereumj/config/EthConfig.java rename to ethereum/src/main/java/com/baeldung/ethereumj/config/EthConfig.java diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/controllers/EthController.java b/ethereum/src/main/java/com/baeldung/ethereumj/controllers/EthController.java similarity index 100% rename from ethereumj/src/main/java/com/baeldung/ethereumj/controllers/EthController.java rename to ethereum/src/main/java/com/baeldung/ethereumj/controllers/EthController.java diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/listeners/EthListener.java b/ethereum/src/main/java/com/baeldung/ethereumj/listeners/EthListener.java similarity index 100% rename from ethereumj/src/main/java/com/baeldung/ethereumj/listeners/EthListener.java rename to ethereum/src/main/java/com/baeldung/ethereumj/listeners/EthListener.java diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/transfer/EthResponse.java b/ethereum/src/main/java/com/baeldung/ethereumj/transfer/EthResponse.java similarity index 100% rename from ethereumj/src/main/java/com/baeldung/ethereumj/transfer/EthResponse.java rename to ethereum/src/main/java/com/baeldung/ethereumj/transfer/EthResponse.java diff --git a/ethereumj/src/main/java/com/baeldung/web3j/Template.java b/ethereum/src/main/java/com/baeldung/web3j/Template.java similarity index 100% rename from ethereumj/src/main/java/com/baeldung/web3j/Template.java rename to ethereum/src/main/java/com/baeldung/web3j/Template.java diff --git a/ethereum/src/main/java/com/baeldung/web3j/config/AppConfig.java b/ethereum/src/main/java/com/baeldung/web3j/config/AppConfig.java new file mode 100644 index 0000000000..75ef948f7a --- /dev/null +++ b/ethereum/src/main/java/com/baeldung/web3j/config/AppConfig.java @@ -0,0 +1,68 @@ +package com.baeldung.web3j.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +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.WebMvcConfigurer; +import org.springframework.web.servlet.resource.PathResourceResolver; +import org.springframework.web.servlet.view.JstlView; +import org.springframework.web.servlet.view.UrlBasedViewResolver; + +import java.util.concurrent.Executor; + +@Configuration +@EnableWebMvc +@EnableAsync +@ComponentScan("com.baeldung.web3j") +public class AppConfig implements WebMvcConfigurer { + + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("index"); + } + + /** + * Static resource locations including themes + */ + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**/*") + .addResourceLocations("/", "/resources/") + .setCachePeriod(3600) + .resourceChain(true) + .addResolver(new PathResourceResolver()); + } + + /** + * View resolver for JSP + */ + @Bean + public UrlBasedViewResolver viewResolver() { + UrlBasedViewResolver resolver = new UrlBasedViewResolver(); + resolver.setPrefix("/WEB-INF/jsp/"); + resolver.setSuffix(".jsp"); + resolver.setViewClass(JstlView.class); + return resolver; + } + + /** + * Configuration for async thread bean + * + * More: https://docs.spring.io/autorepo/docs/spring-framework/5.0.3.RELEASE/javadoc-api/org/springframework/scheduling/SchedulingTaskExecutor.html + */ + @Bean + public Executor asyncExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(2); + executor.setMaxPoolSize(2); + executor.setQueueCapacity(500); + executor.setThreadNamePrefix("CsvThread"); + executor.initialize(); + return executor; + } + +} \ No newline at end of file diff --git a/ethereum/src/main/java/com/baeldung/web3j/config/WebAppInitializer.java b/ethereum/src/main/java/com/baeldung/web3j/config/WebAppInitializer.java new file mode 100644 index 0000000000..8a9a8cf8c1 --- /dev/null +++ b/ethereum/src/main/java/com/baeldung/web3j/config/WebAppInitializer.java @@ -0,0 +1,28 @@ +package com.baeldung.web3j.config; + +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + +public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + + //AbstractDispatcherServletInitializer override DEFAULT_SERVLET_NAME + @Override + protected String getServletName() { + return "dispatcher"; + } + + @Override + protected Class[] getRootConfigClasses() { + return new Class[]{}; + } + + @Override + protected Class[] getServletConfigClasses() { + return new Class[]{AppConfig.class}; + } + + @Override + protected String[] getServletMappings() { + return new String[]{"/"}; + } + +} \ No newline at end of file diff --git a/ethereum/src/main/java/com/baeldung/web3j/constants/Constants.java b/ethereum/src/main/java/com/baeldung/web3j/constants/Constants.java new file mode 100644 index 0000000000..005e4263cd --- /dev/null +++ b/ethereum/src/main/java/com/baeldung/web3j/constants/Constants.java @@ -0,0 +1,18 @@ +package com.baeldung.web3j.constants; + +public class Constants { + + public static final String API_BLOCK = "/api/block"; + public static final String API_ACCOUNTS = "/api/accounts"; + public static final String API_TRANSACTIONS = "/api/transactions"; + public static final String API_BALANCE = "/api/balance"; + + public static final String GENERIC_EXCEPTION = "Exception encountered!"; + public static final String PLEASE_SUPPLY_REAL_DATA = "Please Supply Real Data!"; + + public static final String DEFAULT_ADDRESS = "0x281055afc982d96fab65b3a49cac8b878184cb16"; + public static final String DEFAULT_CONTRACT_ADDRESS = "00000000000000000000"; + + + +} diff --git a/ethereum/src/main/java/com/baeldung/web3j/contracts/Example.java b/ethereum/src/main/java/com/baeldung/web3j/contracts/Example.java new file mode 100644 index 0000000000..6909ca3e0c --- /dev/null +++ b/ethereum/src/main/java/com/baeldung/web3j/contracts/Example.java @@ -0,0 +1,74 @@ +package com.baeldung.web3j.contracts; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import org.web3j.abi.TypeReference; +import org.web3j.abi.datatypes.Function; +import org.web3j.abi.datatypes.Type; +import org.web3j.crypto.Credentials; +import org.web3j.protocol.Web3j; +import org.web3j.protocol.core.RemoteCall; +import org.web3j.protocol.core.methods.response.TransactionReceipt; +import org.web3j.tx.Contract; +import org.web3j.tx.TransactionManager; + +/** + *

Auto generated code. + *

Do not modify! + *

Please use the web3j command line tools, + * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the + * codegen module to update. + * + *

Generated with web3j version 3.3.1. + */ +public class Example extends Contract { + private static final String BINARY = "0x60606040523415600e57600080fd5b60848061001c6000396000f300606060405260043610603f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063b818dacd146044575b600080fd5b3415604e57600080fd5b60546056565b005b5600a165627a7a72305820bebcbbdf06550591bc772dfcb0eadc842f95953869feb7a9528bac91487d95240029"; + + protected static final HashMap _addresses; + + static { + _addresses = new HashMap<>(); + } + + protected Example(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected Example(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return deployRemoteCall(Example.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); + } + + public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + return deployRemoteCall(Example.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); + } + + public RemoteCall ExampleFunction() { + final Function function = new Function( + "ExampleFunction", + Arrays.asList(), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public static Example load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return new Example(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + public static Example load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + return new Example(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + protected String getStaticDeployedAddress(String networkId) { + return _addresses.get(networkId); + } + + public static String getPreviouslyDeployedAddress(String networkId) { + return _addresses.get(networkId); + } +} diff --git a/ethereumj/src/main/java/com/baeldung/web3j/contracts/Greeting.java b/ethereum/src/main/java/com/baeldung/web3j/contracts/Greeting.java similarity index 100% rename from ethereumj/src/main/java/com/baeldung/web3j/contracts/Greeting.java rename to ethereum/src/main/java/com/baeldung/web3j/contracts/Greeting.java diff --git a/ethereum/src/main/java/com/baeldung/web3j/controllers/EthereumRestController.java b/ethereum/src/main/java/com/baeldung/web3j/controllers/EthereumRestController.java new file mode 100644 index 0000000000..e05517bc79 --- /dev/null +++ b/ethereum/src/main/java/com/baeldung/web3j/controllers/EthereumRestController.java @@ -0,0 +1,103 @@ +package com.baeldung.web3j.controllers; + +import com.baeldung.web3j.constants.Constants; +import com.baeldung.web3j.helpers.TimeHelper; +import com.baeldung.web3j.services.Web3Service; +import com.baeldung.web3j.transfers.ResponseTransfer; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import org.web3j.protocol.core.methods.response.EthAccounts; +import org.web3j.protocol.core.methods.response.EthBlockNumber; +import org.web3j.protocol.core.methods.response.EthGetBalance; +import org.web3j.protocol.core.methods.response.EthGetTransactionCount; + +import java.time.Instant; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Future; + +import static com.baeldung.web3j.constants.Constants.GENERIC_EXCEPTION; + +@RestController +public class EthereumRestController { + + @Autowired + Web3Service web3Service; + + @RequestMapping(value = Constants.API_BLOCK, method = RequestMethod.GET) + public Future getBlock() { + ResponseTransfer responseTransfer = new ResponseTransfer(); + Instant start = TimeHelper.start(); + + return CompletableFuture.supplyAsync(() -> { + try { + CompletableFuture result = web3Service.getBlockNumber(); + responseTransfer.setMessage(result.get().toString()); + } catch (Exception e) { + responseTransfer.setMessage(GENERIC_EXCEPTION); + } + return responseTransfer; + }).thenApplyAsync(result -> { + result.setPerformance(TimeHelper.stop(start)); + return result; + }); + } + + @RequestMapping(value = Constants.API_ACCOUNTS, method = RequestMethod.GET) + public Future getAccounts() { + ResponseTransfer responseTransfer = new ResponseTransfer(); + Instant start = TimeHelper.start(); + + return CompletableFuture.supplyAsync(() -> { + try { + CompletableFuture result = web3Service.getEthAccounts(); + responseTransfer.setMessage(result.get().toString()); + } catch (Exception e) { + responseTransfer.setMessage(GENERIC_EXCEPTION); + } + return responseTransfer; + + }).thenApplyAsync(result -> { + result.setPerformance(TimeHelper.stop(start)); + return result; + }); + } + + @RequestMapping(value = Constants.API_TRANSACTIONS, method = RequestMethod.GET) + public Future getTransactions() { + ResponseTransfer responseTransfer = new ResponseTransfer(); + Instant start = TimeHelper.start(); + return CompletableFuture.supplyAsync(() -> { + try { + CompletableFuture result = web3Service.getTransactionCount(); + responseTransfer.setMessage(result.get().toString()); + } catch (Exception e) { + responseTransfer.setMessage(GENERIC_EXCEPTION); + } + return responseTransfer; + }).thenApplyAsync(result -> { + result.setPerformance(TimeHelper.stop(start)); + return result; + }); + } + + @RequestMapping(value = Constants.API_BALANCE, method = RequestMethod.GET) + public Future getBalance() { + ResponseTransfer responseTransfer = new ResponseTransfer(); + Instant start = TimeHelper.start(); + return CompletableFuture.supplyAsync(() -> { + try { + CompletableFuture result = web3Service.getEthBalance(); + responseTransfer.setMessage(result.get().toString()); + } catch (Exception e) { + responseTransfer.setMessage(GENERIC_EXCEPTION); + } + return responseTransfer; + }).thenApplyAsync(result -> { + result.setPerformance(TimeHelper.stop(start)); + return result; + }); + } + +} \ No newline at end of file diff --git a/ethereum/src/main/java/com/baeldung/web3j/helpers/TimeHelper.java b/ethereum/src/main/java/com/baeldung/web3j/helpers/TimeHelper.java new file mode 100644 index 0000000000..360fe088ba --- /dev/null +++ b/ethereum/src/main/java/com/baeldung/web3j/helpers/TimeHelper.java @@ -0,0 +1,16 @@ +package com.baeldung.web3j.helpers; + +import java.time.Duration; +import java.time.Instant; + +public class TimeHelper { + + public static Instant start() { + return Instant.now(); + } + + public static Duration stop(Instant start) { + Instant end = Instant.now(); + return Duration.between(start, end); + } +} diff --git a/ethereum/src/main/java/com/baeldung/web3j/services/Web3Service.java b/ethereum/src/main/java/com/baeldung/web3j/services/Web3Service.java new file mode 100644 index 0000000000..c943ee4006 --- /dev/null +++ b/ethereum/src/main/java/com/baeldung/web3j/services/Web3Service.java @@ -0,0 +1,151 @@ +package com.baeldung.web3j.services; + +import com.baeldung.web3j.contracts.Example; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; +import org.web3j.abi.FunctionEncoder; +import org.web3j.abi.datatypes.Function; +import org.web3j.crypto.Credentials; +import org.web3j.crypto.WalletUtils; +import org.web3j.protocol.Web3j; +import org.web3j.protocol.core.DefaultBlockParameter; +import org.web3j.protocol.core.methods.request.Transaction; +import org.web3j.protocol.core.methods.response.EthAccounts; +import org.web3j.protocol.core.methods.response.EthBlockNumber; +import org.web3j.protocol.core.methods.response.EthGetBalance; +import org.web3j.protocol.core.methods.response.EthGetTransactionCount; +import org.web3j.protocol.http.HttpService; +import org.web3j.tx.Contract; +import org.web3j.tx.ManagedTransaction; + +import java.io.File; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; + +import static com.baeldung.web3j.constants.Constants.DEFAULT_ADDRESS; +import static com.baeldung.web3j.constants.Constants.GENERIC_EXCEPTION; +import static com.baeldung.web3j.constants.Constants.PLEASE_SUPPLY_REAL_DATA; + +@Service +public class Web3Service { + + private Web3j web3j = Web3j.build(new HttpService()); + + //Create and Init the default Web3J connection + public void customInit(String provider) { + this.web3j = Web3j.build(new HttpService(provider)); + } + + //Convert to and from supplied contract ABI bytecode + public static String toBinary(String bytecode) { + return bytecode.replaceFirst("^0x", ""); + } + + public static String toByteCode(String binary) { + return "0x" + binary; + } + + public CompletableFuture getBlockNumber() { + EthBlockNumber result = new EthBlockNumber(); + try { + result = this.web3j.ethBlockNumber().sendAsync().get(); + } catch (Exception ex) { + System.out.println(GENERIC_EXCEPTION); + } + return CompletableFuture.completedFuture(result); + } + + public CompletableFuture getEthAccounts() { + EthAccounts result = new EthAccounts(); + try { + result = this.web3j.ethAccounts().sendAsync().get(); + } catch (Exception ex) { + System.out.println(GENERIC_EXCEPTION); + } + return CompletableFuture.completedFuture(result); + } + + public CompletableFuture getTransactionCount() { + EthGetTransactionCount result = new EthGetTransactionCount(); + try { + result = this.web3j.ethGetTransactionCount(DEFAULT_ADDRESS, DefaultBlockParameter.valueOf("latest")).sendAsync().get(); + } catch (Exception ex) { + System.out.println(GENERIC_EXCEPTION); + } + return CompletableFuture.completedFuture(result); + } + + public CompletableFuture getEthBalance() { + EthGetBalance result = new EthGetBalance(); + try { + result = this.web3j.ethGetBalance(DEFAULT_ADDRESS, DefaultBlockParameter.valueOf("latest")).sendAsync().get(); + } catch (Exception ex) { + System.out.println(GENERIC_EXCEPTION); + } + return CompletableFuture.completedFuture(result); + } + + public CompletableFuture fromScratchContractExample() { + + String contractAddress = ""; + + try { + //Create a wallet + WalletUtils.generateNewWalletFile("PASSWORD", new File("/path/to/destination"), true); + //Load the credentials from it + Credentials credentials = WalletUtils.loadCredentials("PASSWORD", "/path/to/walletfile"); + + //Deploy contract to address specified by wallet + Example contract = Example.deploy(this.web3j, + credentials, + ManagedTransaction.GAS_PRICE, + Contract.GAS_LIMIT).send(); + + //Het the address + contractAddress = contract.getContractAddress(); + + } catch (Exception ex) { + System.out.println(PLEASE_SUPPLY_REAL_DATA); + return CompletableFuture.completedFuture(PLEASE_SUPPLY_REAL_DATA); + } + return CompletableFuture.completedFuture(contractAddress); + } + + @Async + public CompletableFuture sendTx() { + String transactionHash = ""; + + try { + List inputParams = new ArrayList(); + List outputParams = new ArrayList(); + Function function = new Function("fuctionName", inputParams, outputParams); + + String encodedFunction = FunctionEncoder.encode(function); + + BigInteger nonce = BigInteger.valueOf(100); + BigInteger gasprice = BigInteger.valueOf(100); + BigInteger gaslimit = BigInteger.valueOf(100); + + Transaction transaction = Transaction.createFunctionCallTransaction("FROM_ADDRESS", nonce, gasprice, gaslimit, "TO_ADDRESS", encodedFunction); + + org.web3j.protocol.core.methods.response.EthSendTransaction transactionResponse = web3j.ethSendTransaction(transaction).sendAsync().get(); + transactionHash = transactionResponse.getTransactionHash(); + + } catch (Exception ex) { + System.out.println(PLEASE_SUPPLY_REAL_DATA); + return CompletableFuture.completedFuture(PLEASE_SUPPLY_REAL_DATA); + } + + return CompletableFuture.completedFuture(transactionHash); + } +} + + + + + + + + diff --git a/ethereum/src/main/java/com/baeldung/web3j/transfers/ResponseTransfer.java b/ethereum/src/main/java/com/baeldung/web3j/transfers/ResponseTransfer.java new file mode 100644 index 0000000000..9c5d1799ff --- /dev/null +++ b/ethereum/src/main/java/com/baeldung/web3j/transfers/ResponseTransfer.java @@ -0,0 +1,28 @@ +package com.baeldung.web3j.transfers; + +import java.time.Duration; + +public class ResponseTransfer { + + public ResponseTransfer() {} + + private Duration performance; + private String message; + + public Duration getPerformance() { + return performance; + } + + public void setPerformance(Duration performance) { + this.performance = performance; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + +} diff --git a/ethereumj/src/main/resources/application.properties b/ethereum/src/main/resources/application.properties similarity index 100% rename from ethereumj/src/main/resources/application.properties rename to ethereum/src/main/resources/application.properties diff --git a/ethereum/src/main/resources/dev_ganache/README.md b/ethereum/src/main/resources/dev_ganache/README.md new file mode 100644 index 0000000000..2d3e645504 --- /dev/null +++ b/ethereum/src/main/resources/dev_ganache/README.md @@ -0,0 +1,23 @@ +# Ganache Readme + +TL:DR - To set up Ganache visit: http://truffleframework.com/ganache/ + +# Three Ways to Install Ganache + +Ganache is provided in three libraries or distributions: + +(1) Ganache - https://github.com/trufflesuite/ganache + +This is a pre-built and out-of-the-box solution. Easiest to set up. It provides an interface and server shell for Ganache CLI. + +(2) Ganache CLI - https://www.npmjs.com/package/ganache-cli + +Ganache CLI abstracts Ganache Core and supplies the default options and arguments used. + +(3) Ganache Core - https://www.npmjs.com/package/ganache-core + +Basically, only use Ganache Core if you need to build a totally customized option. + +# Use + +The default port is *8545* on *localhost* \ No newline at end of file diff --git a/ethereum/src/main/resources/dev_truffle/README.md b/ethereum/src/main/resources/dev_truffle/README.md new file mode 100644 index 0000000000..b64e16d570 --- /dev/null +++ b/ethereum/src/main/resources/dev_truffle/README.md @@ -0,0 +1,43 @@ +# Using Truffle + +Basic Truffle walkthrough readme. + +See also: http://truffleframework.com/docs/ + +# Bash + +Truffle install + +```bash + $ npm install truffle -g + $ truffle version +``` + +Truffle commands: + +```bash + $ truffle init + $ truffle compile + $ truffle migrate + $ truffle test +``` + +# Directory Structure + +The command `$ truffle init` will create a directory structure in the specified root according to the following: + +``` +root -| + |-build (Compiled Solc JSON Output Dir) + |-contracts (Solc Contracts to be Compiled and Migrated) + |-migrations (Specify the Order and Dependencies of Contracts to Be Deployed) + |-test (Truffle Tests) +``` + +# Compile + +Truffle will compile the smart contracts and expose their **JSON ABI's for use with Web3.js** or **Binary ABI's for use with Web3J**. + +# Migration + +Truffle will let you deploy your Solc contracts directly to a blockchin of your choice. \ No newline at end of file diff --git a/ethereum/src/main/resources/dev_truffle/build/contracts/ConvertLib.json b/ethereum/src/main/resources/dev_truffle/build/contracts/ConvertLib.json new file mode 100644 index 0000000000..977928c756 --- /dev/null +++ b/ethereum/src/main/resources/dev_truffle/build/contracts/ConvertLib.json @@ -0,0 +1,455 @@ +{ + "contractName": "ConvertLib", + "abi": [ + { + "constant": false, + "inputs": [ + { + "name": "amount", + "type": "uint256" + }, + { + "name": "conversionRate", + "type": "uint256" + } + ], + "name": "convert", + "outputs": [ + { + "name": "convertedAmount", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + } + ], + "bytecode": "0x60d161002f600b82828239805160001a6073146000811461001f57610021565bfe5b5030600052607381538281f30073000000000000000000000000000000000000000030146060604052600436106056576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806396e4ee3d14605b575b600080fd5b8115606557600080fd5b608260048080359060200190919080359060200190919050506098565b6040518082815260200191505060405180910390f35b60008183029050929150505600a165627a7a72305820ab84b2740847d7b84a33de9738ae9cf9aabac1b68e6a64d60bd5020b9b6235e40029", + "deployedBytecode": "0x73000000000000000000000000000000000000000030146060604052600436106056576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806396e4ee3d14605b575b600080fd5b8115606557600080fd5b608260048080359060200190919080359060200190919050506098565b6040518082815260200191505060405180910390f35b60008183029050929150505600a165627a7a72305820ab84b2740847d7b84a33de9738ae9cf9aabac1b68e6a64d60bd5020b9b6235e40029", + "sourceMap": "28:148:0:-;;132:2:-1;166:7;155:9;146:7;137:37;252:7;246:14;243:1;238:23;232:4;229:33;270:1;265:20;;;;222:63;;265:20;274:9;222:63;;298:9;295:1;288:20;328:4;319:7;311:22;352:7;343;336:24", + "deployedSourceMap": "28:148:0:-;;;;;;;;;;;;;;;;;;;;;;;;;;;50:123;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;109:20;154:14;145:6;:23;138:30;;50:123;;;;:::o", + "source": "pragma solidity ^0.4.17;\r\n\r\nlibrary ConvertLib{\r\n\tfunction convert(uint amount,uint conversionRate) returns (uint convertedAmount)\r\n\t{\r\n\t\treturn amount * conversionRate;\r\n\t}\r\n}\r\n", + "sourcePath": "C:\\workspace\\current_workspace\\web3java\\dev_truffle\\contracts\\ConvertLib.sol", + "ast": { + "absolutePath": "/C/workspace/current_workspace/web3java/dev_truffle/contracts/ConvertLib.sol", + "exportedSymbols": { + "ConvertLib": [ + 16 + ] + }, + "id": 17, + "nodeType": "SourceUnit", + "nodes": [ + { + "id": 1, + "literals": [ + "solidity", + "^", + "0.4", + ".17" + ], + "nodeType": "PragmaDirective", + "src": "0:24:0" + }, + { + "baseContracts": [], + "contractDependencies": [], + "contractKind": "library", + "documentation": null, + "fullyImplemented": true, + "id": 16, + "linearizedBaseContracts": [ + 16 + ], + "name": "ConvertLib", + "nodeType": "ContractDefinition", + "nodes": [ + { + "body": { + "id": 14, + "nodeType": "Block", + "src": "133:40:0", + "statements": [ + { + "expression": { + "argumentTypes": null, + "commonType": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + }, + "id": 12, + "isConstant": false, + "isLValue": false, + "isPure": false, + "lValueRequested": false, + "leftExpression": { + "argumentTypes": null, + "id": 10, + "name": "amount", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 3, + "src": "145:6:0", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "nodeType": "BinaryOperation", + "operator": "*", + "rightExpression": { + "argumentTypes": null, + "id": 11, + "name": "conversionRate", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 5, + "src": "154:14:0", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "src": "145:23:0", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "functionReturnParameters": 9, + "id": 13, + "nodeType": "Return", + "src": "138:30:0" + } + ] + }, + "documentation": null, + "id": 15, + "implemented": true, + "isConstructor": false, + "isDeclaredConst": false, + "modifiers": [], + "name": "convert", + "nodeType": "FunctionDefinition", + "parameters": { + "id": 6, + "nodeType": "ParameterList", + "parameters": [ + { + "constant": false, + "id": 3, + "name": "amount", + "nodeType": "VariableDeclaration", + "scope": 15, + "src": "67:11:0", + "stateVariable": false, + "storageLocation": "default", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + }, + "typeName": { + "id": 2, + "name": "uint", + "nodeType": "ElementaryTypeName", + "src": "67:4:0", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "value": null, + "visibility": "internal" + }, + { + "constant": false, + "id": 5, + "name": "conversionRate", + "nodeType": "VariableDeclaration", + "scope": 15, + "src": "79:19:0", + "stateVariable": false, + "storageLocation": "default", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + }, + "typeName": { + "id": 4, + "name": "uint", + "nodeType": "ElementaryTypeName", + "src": "79:4:0", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "value": null, + "visibility": "internal" + } + ], + "src": "66:33:0" + }, + "payable": false, + "returnParameters": { + "id": 9, + "nodeType": "ParameterList", + "parameters": [ + { + "constant": false, + "id": 8, + "name": "convertedAmount", + "nodeType": "VariableDeclaration", + "scope": 15, + "src": "109:20:0", + "stateVariable": false, + "storageLocation": "default", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + }, + "typeName": { + "id": 7, + "name": "uint", + "nodeType": "ElementaryTypeName", + "src": "109:4:0", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "value": null, + "visibility": "internal" + } + ], + "src": "108:22:0" + }, + "scope": 16, + "src": "50:123:0", + "stateMutability": "nonpayable", + "superFunction": null, + "visibility": "public" + } + ], + "scope": 17, + "src": "28:148:0" + } + ], + "src": "0:178:0" + }, + "legacyAST": { + "absolutePath": "/C/workspace/current_workspace/web3java/dev_truffle/contracts/ConvertLib.sol", + "exportedSymbols": { + "ConvertLib": [ + 16 + ] + }, + "id": 17, + "nodeType": "SourceUnit", + "nodes": [ + { + "id": 1, + "literals": [ + "solidity", + "^", + "0.4", + ".17" + ], + "nodeType": "PragmaDirective", + "src": "0:24:0" + }, + { + "baseContracts": [], + "contractDependencies": [], + "contractKind": "library", + "documentation": null, + "fullyImplemented": true, + "id": 16, + "linearizedBaseContracts": [ + 16 + ], + "name": "ConvertLib", + "nodeType": "ContractDefinition", + "nodes": [ + { + "body": { + "id": 14, + "nodeType": "Block", + "src": "133:40:0", + "statements": [ + { + "expression": { + "argumentTypes": null, + "commonType": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + }, + "id": 12, + "isConstant": false, + "isLValue": false, + "isPure": false, + "lValueRequested": false, + "leftExpression": { + "argumentTypes": null, + "id": 10, + "name": "amount", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 3, + "src": "145:6:0", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "nodeType": "BinaryOperation", + "operator": "*", + "rightExpression": { + "argumentTypes": null, + "id": 11, + "name": "conversionRate", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 5, + "src": "154:14:0", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "src": "145:23:0", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "functionReturnParameters": 9, + "id": 13, + "nodeType": "Return", + "src": "138:30:0" + } + ] + }, + "documentation": null, + "id": 15, + "implemented": true, + "isConstructor": false, + "isDeclaredConst": false, + "modifiers": [], + "name": "convert", + "nodeType": "FunctionDefinition", + "parameters": { + "id": 6, + "nodeType": "ParameterList", + "parameters": [ + { + "constant": false, + "id": 3, + "name": "amount", + "nodeType": "VariableDeclaration", + "scope": 15, + "src": "67:11:0", + "stateVariable": false, + "storageLocation": "default", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + }, + "typeName": { + "id": 2, + "name": "uint", + "nodeType": "ElementaryTypeName", + "src": "67:4:0", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "value": null, + "visibility": "internal" + }, + { + "constant": false, + "id": 5, + "name": "conversionRate", + "nodeType": "VariableDeclaration", + "scope": 15, + "src": "79:19:0", + "stateVariable": false, + "storageLocation": "default", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + }, + "typeName": { + "id": 4, + "name": "uint", + "nodeType": "ElementaryTypeName", + "src": "79:4:0", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "value": null, + "visibility": "internal" + } + ], + "src": "66:33:0" + }, + "payable": false, + "returnParameters": { + "id": 9, + "nodeType": "ParameterList", + "parameters": [ + { + "constant": false, + "id": 8, + "name": "convertedAmount", + "nodeType": "VariableDeclaration", + "scope": 15, + "src": "109:20:0", + "stateVariable": false, + "storageLocation": "default", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + }, + "typeName": { + "id": 7, + "name": "uint", + "nodeType": "ElementaryTypeName", + "src": "109:4:0", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "value": null, + "visibility": "internal" + } + ], + "src": "108:22:0" + }, + "scope": 16, + "src": "50:123:0", + "stateMutability": "nonpayable", + "superFunction": null, + "visibility": "public" + } + ], + "scope": 17, + "src": "28:148:0" + } + ], + "src": "0:178:0" + }, + "compiler": { + "name": "solc", + "version": "0.4.21+commit.dfe3193c.Emscripten.clang" + }, + "networks": {}, + "schemaVersion": "2.0.0", + "updatedAt": "2018-04-14T03:37:39.678Z" +} \ No newline at end of file diff --git a/ethereum/src/main/resources/dev_truffle/build/contracts/Example.json b/ethereum/src/main/resources/dev_truffle/build/contracts/Example.json new file mode 100644 index 0000000000..82111dab11 --- /dev/null +++ b/ethereum/src/main/resources/dev_truffle/build/contracts/Example.json @@ -0,0 +1,251 @@ +{ + "contractName": "Example", + "abi": [ + { + "inputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "constant": false, + "inputs": [], + "name": "ExampleFunction", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + } + ], + "bytecode": "0x60606040523415600e57600080fd5b60848061001c6000396000f300606060405260043610603f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063b818dacd146044575b600080fd5b3415604e57600080fd5b60546056565b005b5600a165627a7a72305820bebcbbdf06550591bc772dfcb0eadc842f95953869feb7a9528bac91487d95240029", + "deployedBytecode": "0x606060405260043610603f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063b818dacd146044575b600080fd5b3415604e57600080fd5b60546056565b005b5600a165627a7a72305820bebcbbdf06550591bc772dfcb0eadc842f95953869feb7a9528bac91487d95240029", + "sourceMap": "28:134:1:-;;;50:45;;;;;;;;28:134;;;;;;", + "deployedSourceMap": "28:134:1:-;;;;;;;;;;;;;;;;;;;;;;;;101:58;;;;;;;;;;;;;;;:::o", + "source": "pragma solidity ^0.4.17;\r\n\r\ncontract Example {\r\n function Example() {\r\n // constructor\r\n }\r\n\r\n function ExampleFunction() {\r\n // example function\r\n }\r\n}", + "sourcePath": "C:\\workspace\\current_workspace\\web3java\\dev_truffle\\contracts\\Example.sol", + "ast": { + "absolutePath": "/C/workspace/current_workspace/web3java/dev_truffle/contracts/Example.sol", + "exportedSymbols": { + "Example": [ + 27 + ] + }, + "id": 28, + "nodeType": "SourceUnit", + "nodes": [ + { + "id": 18, + "literals": [ + "solidity", + "^", + "0.4", + ".17" + ], + "nodeType": "PragmaDirective", + "src": "0:24:1" + }, + { + "baseContracts": [], + "contractDependencies": [], + "contractKind": "contract", + "documentation": null, + "fullyImplemented": true, + "id": 27, + "linearizedBaseContracts": [ + 27 + ], + "name": "Example", + "nodeType": "ContractDefinition", + "nodes": [ + { + "body": { + "id": 21, + "nodeType": "Block", + "src": "69:26:1", + "statements": [] + }, + "documentation": null, + "id": 22, + "implemented": true, + "isConstructor": true, + "isDeclaredConst": false, + "modifiers": [], + "name": "Example", + "nodeType": "FunctionDefinition", + "parameters": { + "id": 19, + "nodeType": "ParameterList", + "parameters": [], + "src": "66:2:1" + }, + "payable": false, + "returnParameters": { + "id": 20, + "nodeType": "ParameterList", + "parameters": [], + "src": "69:0:1" + }, + "scope": 27, + "src": "50:45:1", + "stateMutability": "nonpayable", + "superFunction": null, + "visibility": "public" + }, + { + "body": { + "id": 25, + "nodeType": "Block", + "src": "128:31:1", + "statements": [] + }, + "documentation": null, + "id": 26, + "implemented": true, + "isConstructor": false, + "isDeclaredConst": false, + "modifiers": [], + "name": "ExampleFunction", + "nodeType": "FunctionDefinition", + "parameters": { + "id": 23, + "nodeType": "ParameterList", + "parameters": [], + "src": "125:2:1" + }, + "payable": false, + "returnParameters": { + "id": 24, + "nodeType": "ParameterList", + "parameters": [], + "src": "128:0:1" + }, + "scope": 27, + "src": "101:58:1", + "stateMutability": "nonpayable", + "superFunction": null, + "visibility": "public" + } + ], + "scope": 28, + "src": "28:134:1" + } + ], + "src": "0:162:1" + }, + "legacyAST": { + "absolutePath": "/C/workspace/current_workspace/web3java/dev_truffle/contracts/Example.sol", + "exportedSymbols": { + "Example": [ + 27 + ] + }, + "id": 28, + "nodeType": "SourceUnit", + "nodes": [ + { + "id": 18, + "literals": [ + "solidity", + "^", + "0.4", + ".17" + ], + "nodeType": "PragmaDirective", + "src": "0:24:1" + }, + { + "baseContracts": [], + "contractDependencies": [], + "contractKind": "contract", + "documentation": null, + "fullyImplemented": true, + "id": 27, + "linearizedBaseContracts": [ + 27 + ], + "name": "Example", + "nodeType": "ContractDefinition", + "nodes": [ + { + "body": { + "id": 21, + "nodeType": "Block", + "src": "69:26:1", + "statements": [] + }, + "documentation": null, + "id": 22, + "implemented": true, + "isConstructor": true, + "isDeclaredConst": false, + "modifiers": [], + "name": "Example", + "nodeType": "FunctionDefinition", + "parameters": { + "id": 19, + "nodeType": "ParameterList", + "parameters": [], + "src": "66:2:1" + }, + "payable": false, + "returnParameters": { + "id": 20, + "nodeType": "ParameterList", + "parameters": [], + "src": "69:0:1" + }, + "scope": 27, + "src": "50:45:1", + "stateMutability": "nonpayable", + "superFunction": null, + "visibility": "public" + }, + { + "body": { + "id": 25, + "nodeType": "Block", + "src": "128:31:1", + "statements": [] + }, + "documentation": null, + "id": 26, + "implemented": true, + "isConstructor": false, + "isDeclaredConst": false, + "modifiers": [], + "name": "ExampleFunction", + "nodeType": "FunctionDefinition", + "parameters": { + "id": 23, + "nodeType": "ParameterList", + "parameters": [], + "src": "125:2:1" + }, + "payable": false, + "returnParameters": { + "id": 24, + "nodeType": "ParameterList", + "parameters": [], + "src": "128:0:1" + }, + "scope": 27, + "src": "101:58:1", + "stateMutability": "nonpayable", + "superFunction": null, + "visibility": "public" + } + ], + "scope": 28, + "src": "28:134:1" + } + ], + "src": "0:162:1" + }, + "compiler": { + "name": "solc", + "version": "0.4.21+commit.dfe3193c.Emscripten.clang" + }, + "networks": {}, + "schemaVersion": "2.0.0", + "updatedAt": "2018-04-14T03:37:39.710Z" +} \ No newline at end of file diff --git a/ethereum/src/main/resources/dev_truffle/build/contracts/Migrations.json b/ethereum/src/main/resources/dev_truffle/build/contracts/Migrations.json new file mode 100644 index 0000000000..55f2c7ad69 --- /dev/null +++ b/ethereum/src/main/resources/dev_truffle/build/contracts/Migrations.json @@ -0,0 +1,1380 @@ +{ + "contractName": "Migrations", + "abi": [ + { + "constant": true, + "inputs": [], + "name": "last_completed_migration", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "owner", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "constant": false, + "inputs": [ + { + "name": "completed", + "type": "uint256" + } + ], + "name": "setCompleted", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "new_address", + "type": "address" + } + ], + "name": "upgrade", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + } + ], + "bytecode": "0x6060604052341561000f57600080fd5b336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506102d78061005e6000396000f300606060405260043610610062576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630900f01014610067578063445df0ac146100a05780638da5cb5b146100c9578063fdacd5761461011e575b600080fd5b341561007257600080fd5b61009e600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610141565b005b34156100ab57600080fd5b6100b3610220565b6040518082815260200191505060405180910390f35b34156100d457600080fd5b6100dc610226565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b341561012957600080fd5b61013f600480803590602001909190505061024b565b005b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561021c578190508073ffffffffffffffffffffffffffffffffffffffff1663fdacd5766001546040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180828152602001915050600060405180830381600087803b151561020b57600080fd5b5af1151561021857600080fd5b5050505b5050565b60015481565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614156102a857806001819055505b505600a165627a7a72305820be5431ce1823a03470fc4376ec6fdfa9e54ca2bd2b05b6271c73eb54ad4e4b060029", + "deployedBytecode": "0x606060405260043610610062576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630900f01014610067578063445df0ac146100a05780638da5cb5b146100c9578063fdacd5761461011e575b600080fd5b341561007257600080fd5b61009e600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610141565b005b34156100ab57600080fd5b6100b3610220565b6040518082815260200191505060405180910390f35b34156100d457600080fd5b6100dc610226565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b341561012957600080fd5b61013f600480803590602001909190505061024b565b005b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561021c578190508073ffffffffffffffffffffffffffffffffffffffff1663fdacd5766001546040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180828152602001915050600060405180830381600087803b151561020b57600080fd5b5af1151561021857600080fd5b5050505b5050565b60015481565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614156102a857806001819055505b505600a165627a7a72305820be5431ce1823a03470fc4376ec6fdfa9e54ca2bd2b05b6271c73eb54ad4e4b060029", + "sourceMap": "26:488:2:-;;;178:58;;;;;;;;221:10;213:5;;:18;;;;;;;;;;;;;;;;;;26:488;;;;;;", + "deployedSourceMap": "26:488:2:-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;347:165;;;;;;;;;;;;;;;;;;;;;;;;;;;;74:36;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;50:20;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;240:103;;;;;;;;;;;;;;;;;;;;;;;;;;347:165;409:19;161:5;;;;;;;;;;;147:19;;:10;:19;;;143:26;;;442:11;409:45;;460:8;:21;;;482:24;;460:47;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;143:26;347:165;;:::o;74:36::-;;;;:::o;50:20::-;;;;;;;;;;;;;:::o;240:103::-;161:5;;;;;;;;;;;147:19;;:10;:19;;;143:26;;;329:9;302:24;:36;;;;143:26;240:103;:::o", + "source": "pragma solidity ^0.4.17;\n\ncontract Migrations {\n address public owner;\n uint public last_completed_migration;\n\n modifier restricted() {\n if (msg.sender == owner) _;\n }\n\n function Migrations() public {\n owner = msg.sender;\n }\n\n function setCompleted(uint completed) public restricted {\n last_completed_migration = completed;\n }\n\n function upgrade(address new_address) public restricted {\n Migrations upgraded = Migrations(new_address);\n upgraded.setCompleted(last_completed_migration);\n }\n}\n", + "sourcePath": "C:\\workspace\\current_workspace\\web3java\\dev_truffle\\contracts\\Migrations.sol", + "ast": { + "absolutePath": "/C/workspace/current_workspace/web3java/dev_truffle/contracts/Migrations.sol", + "exportedSymbols": { + "Migrations": [ + 84 + ] + }, + "id": 85, + "nodeType": "SourceUnit", + "nodes": [ + { + "id": 29, + "literals": [ + "solidity", + "^", + "0.4", + ".17" + ], + "nodeType": "PragmaDirective", + "src": "0:24:2" + }, + { + "baseContracts": [], + "contractDependencies": [], + "contractKind": "contract", + "documentation": null, + "fullyImplemented": true, + "id": 84, + "linearizedBaseContracts": [ + 84 + ], + "name": "Migrations", + "nodeType": "ContractDefinition", + "nodes": [ + { + "constant": false, + "id": 31, + "name": "owner", + "nodeType": "VariableDeclaration", + "scope": 84, + "src": "50:20:2", + "stateVariable": true, + "storageLocation": "default", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + }, + "typeName": { + "id": 30, + "name": "address", + "nodeType": "ElementaryTypeName", + "src": "50:7:2", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + } + }, + "value": null, + "visibility": "public" + }, + { + "constant": false, + "id": 33, + "name": "last_completed_migration", + "nodeType": "VariableDeclaration", + "scope": 84, + "src": "74:36:2", + "stateVariable": true, + "storageLocation": "default", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + }, + "typeName": { + "id": 32, + "name": "uint", + "nodeType": "ElementaryTypeName", + "src": "74:4:2", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "value": null, + "visibility": "public" + }, + { + "body": { + "id": 41, + "nodeType": "Block", + "src": "137:37:2", + "statements": [ + { + "condition": { + "argumentTypes": null, + "commonType": { + "typeIdentifier": "t_address", + "typeString": "address" + }, + "id": 38, + "isConstant": false, + "isLValue": false, + "isPure": false, + "lValueRequested": false, + "leftExpression": { + "argumentTypes": null, + "expression": { + "argumentTypes": null, + "id": 35, + "name": "msg", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 97, + "src": "147:3:2", + "typeDescriptions": { + "typeIdentifier": "t_magic_message", + "typeString": "msg" + } + }, + "id": 36, + "isConstant": false, + "isLValue": false, + "isPure": false, + "lValueRequested": false, + "memberName": "sender", + "nodeType": "MemberAccess", + "referencedDeclaration": null, + "src": "147:10:2", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + } + }, + "nodeType": "BinaryOperation", + "operator": "==", + "rightExpression": { + "argumentTypes": null, + "id": 37, + "name": "owner", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 31, + "src": "161:5:2", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + } + }, + "src": "147:19:2", + "typeDescriptions": { + "typeIdentifier": "t_bool", + "typeString": "bool" + } + }, + "falseBody": null, + "id": 40, + "nodeType": "IfStatement", + "src": "143:26:2", + "trueBody": { + "id": 39, + "nodeType": "PlaceholderStatement", + "src": "168:1:2" + } + } + ] + }, + "documentation": null, + "id": 42, + "name": "restricted", + "nodeType": "ModifierDefinition", + "parameters": { + "id": 34, + "nodeType": "ParameterList", + "parameters": [], + "src": "134:2:2" + }, + "src": "115:59:2", + "visibility": "internal" + }, + { + "body": { + "id": 50, + "nodeType": "Block", + "src": "207:29:2", + "statements": [ + { + "expression": { + "argumentTypes": null, + "id": 48, + "isConstant": false, + "isLValue": false, + "isPure": false, + "lValueRequested": false, + "leftHandSide": { + "argumentTypes": null, + "id": 45, + "name": "owner", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 31, + "src": "213:5:2", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + } + }, + "nodeType": "Assignment", + "operator": "=", + "rightHandSide": { + "argumentTypes": null, + "expression": { + "argumentTypes": null, + "id": 46, + "name": "msg", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 97, + "src": "221:3:2", + "typeDescriptions": { + "typeIdentifier": "t_magic_message", + "typeString": "msg" + } + }, + "id": 47, + "isConstant": false, + "isLValue": false, + "isPure": false, + "lValueRequested": false, + "memberName": "sender", + "nodeType": "MemberAccess", + "referencedDeclaration": null, + "src": "221:10:2", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + } + }, + "src": "213:18:2", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + } + }, + "id": 49, + "nodeType": "ExpressionStatement", + "src": "213:18:2" + } + ] + }, + "documentation": null, + "id": 51, + "implemented": true, + "isConstructor": true, + "isDeclaredConst": false, + "modifiers": [], + "name": "Migrations", + "nodeType": "FunctionDefinition", + "parameters": { + "id": 43, + "nodeType": "ParameterList", + "parameters": [], + "src": "197:2:2" + }, + "payable": false, + "returnParameters": { + "id": 44, + "nodeType": "ParameterList", + "parameters": [], + "src": "207:0:2" + }, + "scope": 84, + "src": "178:58:2", + "stateMutability": "nonpayable", + "superFunction": null, + "visibility": "public" + }, + { + "body": { + "id": 62, + "nodeType": "Block", + "src": "296:47:2", + "statements": [ + { + "expression": { + "argumentTypes": null, + "id": 60, + "isConstant": false, + "isLValue": false, + "isPure": false, + "lValueRequested": false, + "leftHandSide": { + "argumentTypes": null, + "id": 58, + "name": "last_completed_migration", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 33, + "src": "302:24:2", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "nodeType": "Assignment", + "operator": "=", + "rightHandSide": { + "argumentTypes": null, + "id": 59, + "name": "completed", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 53, + "src": "329:9:2", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "src": "302:36:2", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "id": 61, + "nodeType": "ExpressionStatement", + "src": "302:36:2" + } + ] + }, + "documentation": null, + "id": 63, + "implemented": true, + "isConstructor": false, + "isDeclaredConst": false, + "modifiers": [ + { + "arguments": [], + "id": 56, + "modifierName": { + "argumentTypes": null, + "id": 55, + "name": "restricted", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 42, + "src": "285:10:2", + "typeDescriptions": { + "typeIdentifier": "t_modifier$__$", + "typeString": "modifier ()" + } + }, + "nodeType": "ModifierInvocation", + "src": "285:10:2" + } + ], + "name": "setCompleted", + "nodeType": "FunctionDefinition", + "parameters": { + "id": 54, + "nodeType": "ParameterList", + "parameters": [ + { + "constant": false, + "id": 53, + "name": "completed", + "nodeType": "VariableDeclaration", + "scope": 63, + "src": "262:14:2", + "stateVariable": false, + "storageLocation": "default", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + }, + "typeName": { + "id": 52, + "name": "uint", + "nodeType": "ElementaryTypeName", + "src": "262:4:2", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "value": null, + "visibility": "internal" + } + ], + "src": "261:16:2" + }, + "payable": false, + "returnParameters": { + "id": 57, + "nodeType": "ParameterList", + "parameters": [], + "src": "296:0:2" + }, + "scope": 84, + "src": "240:103:2", + "stateMutability": "nonpayable", + "superFunction": null, + "visibility": "public" + }, + { + "body": { + "id": 82, + "nodeType": "Block", + "src": "403:109:2", + "statements": [ + { + "assignments": [ + 71 + ], + "declarations": [ + { + "constant": false, + "id": 71, + "name": "upgraded", + "nodeType": "VariableDeclaration", + "scope": 83, + "src": "409:19:2", + "stateVariable": false, + "storageLocation": "default", + "typeDescriptions": { + "typeIdentifier": "t_contract$_Migrations_$84", + "typeString": "contract Migrations" + }, + "typeName": { + "contractScope": null, + "id": 70, + "name": "Migrations", + "nodeType": "UserDefinedTypeName", + "referencedDeclaration": 84, + "src": "409:10:2", + "typeDescriptions": { + "typeIdentifier": "t_contract$_Migrations_$84", + "typeString": "contract Migrations" + } + }, + "value": null, + "visibility": "internal" + } + ], + "id": 75, + "initialValue": { + "argumentTypes": null, + "arguments": [ + { + "argumentTypes": null, + "id": 73, + "name": "new_address", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 65, + "src": "442:11:2", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + } + } + ], + "expression": { + "argumentTypes": [ + { + "typeIdentifier": "t_address", + "typeString": "address" + } + ], + "id": 72, + "name": "Migrations", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 84, + "src": "431:10:2", + "typeDescriptions": { + "typeIdentifier": "t_type$_t_contract$_Migrations_$84_$", + "typeString": "type(contract Migrations)" + } + }, + "id": 74, + "isConstant": false, + "isLValue": false, + "isPure": false, + "kind": "typeConversion", + "lValueRequested": false, + "names": [], + "nodeType": "FunctionCall", + "src": "431:23:2", + "typeDescriptions": { + "typeIdentifier": "t_contract$_Migrations_$84", + "typeString": "contract Migrations" + } + }, + "nodeType": "VariableDeclarationStatement", + "src": "409:45:2" + }, + { + "expression": { + "argumentTypes": null, + "arguments": [ + { + "argumentTypes": null, + "id": 79, + "name": "last_completed_migration", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 33, + "src": "482:24:2", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + } + ], + "expression": { + "argumentTypes": [ + { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + ], + "expression": { + "argumentTypes": null, + "id": 76, + "name": "upgraded", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 71, + "src": "460:8:2", + "typeDescriptions": { + "typeIdentifier": "t_contract$_Migrations_$84", + "typeString": "contract Migrations" + } + }, + "id": 78, + "isConstant": false, + "isLValue": false, + "isPure": false, + "lValueRequested": false, + "memberName": "setCompleted", + "nodeType": "MemberAccess", + "referencedDeclaration": 63, + "src": "460:21:2", + "typeDescriptions": { + "typeIdentifier": "t_function_external_nonpayable$_t_uint256_$returns$__$", + "typeString": "function (uint256) external" + } + }, + "id": 80, + "isConstant": false, + "isLValue": false, + "isPure": false, + "kind": "functionCall", + "lValueRequested": false, + "names": [], + "nodeType": "FunctionCall", + "src": "460:47:2", + "typeDescriptions": { + "typeIdentifier": "t_tuple$__$", + "typeString": "tuple()" + } + }, + "id": 81, + "nodeType": "ExpressionStatement", + "src": "460:47:2" + } + ] + }, + "documentation": null, + "id": 83, + "implemented": true, + "isConstructor": false, + "isDeclaredConst": false, + "modifiers": [ + { + "arguments": [], + "id": 68, + "modifierName": { + "argumentTypes": null, + "id": 67, + "name": "restricted", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 42, + "src": "392:10:2", + "typeDescriptions": { + "typeIdentifier": "t_modifier$__$", + "typeString": "modifier ()" + } + }, + "nodeType": "ModifierInvocation", + "src": "392:10:2" + } + ], + "name": "upgrade", + "nodeType": "FunctionDefinition", + "parameters": { + "id": 66, + "nodeType": "ParameterList", + "parameters": [ + { + "constant": false, + "id": 65, + "name": "new_address", + "nodeType": "VariableDeclaration", + "scope": 83, + "src": "364:19:2", + "stateVariable": false, + "storageLocation": "default", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + }, + "typeName": { + "id": 64, + "name": "address", + "nodeType": "ElementaryTypeName", + "src": "364:7:2", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + } + }, + "value": null, + "visibility": "internal" + } + ], + "src": "363:21:2" + }, + "payable": false, + "returnParameters": { + "id": 69, + "nodeType": "ParameterList", + "parameters": [], + "src": "403:0:2" + }, + "scope": 84, + "src": "347:165:2", + "stateMutability": "nonpayable", + "superFunction": null, + "visibility": "public" + } + ], + "scope": 85, + "src": "26:488:2" + } + ], + "src": "0:515:2" + }, + "legacyAST": { + "absolutePath": "/C/workspace/current_workspace/web3java/dev_truffle/contracts/Migrations.sol", + "exportedSymbols": { + "Migrations": [ + 84 + ] + }, + "id": 85, + "nodeType": "SourceUnit", + "nodes": [ + { + "id": 29, + "literals": [ + "solidity", + "^", + "0.4", + ".17" + ], + "nodeType": "PragmaDirective", + "src": "0:24:2" + }, + { + "baseContracts": [], + "contractDependencies": [], + "contractKind": "contract", + "documentation": null, + "fullyImplemented": true, + "id": 84, + "linearizedBaseContracts": [ + 84 + ], + "name": "Migrations", + "nodeType": "ContractDefinition", + "nodes": [ + { + "constant": false, + "id": 31, + "name": "owner", + "nodeType": "VariableDeclaration", + "scope": 84, + "src": "50:20:2", + "stateVariable": true, + "storageLocation": "default", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + }, + "typeName": { + "id": 30, + "name": "address", + "nodeType": "ElementaryTypeName", + "src": "50:7:2", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + } + }, + "value": null, + "visibility": "public" + }, + { + "constant": false, + "id": 33, + "name": "last_completed_migration", + "nodeType": "VariableDeclaration", + "scope": 84, + "src": "74:36:2", + "stateVariable": true, + "storageLocation": "default", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + }, + "typeName": { + "id": 32, + "name": "uint", + "nodeType": "ElementaryTypeName", + "src": "74:4:2", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "value": null, + "visibility": "public" + }, + { + "body": { + "id": 41, + "nodeType": "Block", + "src": "137:37:2", + "statements": [ + { + "condition": { + "argumentTypes": null, + "commonType": { + "typeIdentifier": "t_address", + "typeString": "address" + }, + "id": 38, + "isConstant": false, + "isLValue": false, + "isPure": false, + "lValueRequested": false, + "leftExpression": { + "argumentTypes": null, + "expression": { + "argumentTypes": null, + "id": 35, + "name": "msg", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 97, + "src": "147:3:2", + "typeDescriptions": { + "typeIdentifier": "t_magic_message", + "typeString": "msg" + } + }, + "id": 36, + "isConstant": false, + "isLValue": false, + "isPure": false, + "lValueRequested": false, + "memberName": "sender", + "nodeType": "MemberAccess", + "referencedDeclaration": null, + "src": "147:10:2", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + } + }, + "nodeType": "BinaryOperation", + "operator": "==", + "rightExpression": { + "argumentTypes": null, + "id": 37, + "name": "owner", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 31, + "src": "161:5:2", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + } + }, + "src": "147:19:2", + "typeDescriptions": { + "typeIdentifier": "t_bool", + "typeString": "bool" + } + }, + "falseBody": null, + "id": 40, + "nodeType": "IfStatement", + "src": "143:26:2", + "trueBody": { + "id": 39, + "nodeType": "PlaceholderStatement", + "src": "168:1:2" + } + } + ] + }, + "documentation": null, + "id": 42, + "name": "restricted", + "nodeType": "ModifierDefinition", + "parameters": { + "id": 34, + "nodeType": "ParameterList", + "parameters": [], + "src": "134:2:2" + }, + "src": "115:59:2", + "visibility": "internal" + }, + { + "body": { + "id": 50, + "nodeType": "Block", + "src": "207:29:2", + "statements": [ + { + "expression": { + "argumentTypes": null, + "id": 48, + "isConstant": false, + "isLValue": false, + "isPure": false, + "lValueRequested": false, + "leftHandSide": { + "argumentTypes": null, + "id": 45, + "name": "owner", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 31, + "src": "213:5:2", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + } + }, + "nodeType": "Assignment", + "operator": "=", + "rightHandSide": { + "argumentTypes": null, + "expression": { + "argumentTypes": null, + "id": 46, + "name": "msg", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 97, + "src": "221:3:2", + "typeDescriptions": { + "typeIdentifier": "t_magic_message", + "typeString": "msg" + } + }, + "id": 47, + "isConstant": false, + "isLValue": false, + "isPure": false, + "lValueRequested": false, + "memberName": "sender", + "nodeType": "MemberAccess", + "referencedDeclaration": null, + "src": "221:10:2", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + } + }, + "src": "213:18:2", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + } + }, + "id": 49, + "nodeType": "ExpressionStatement", + "src": "213:18:2" + } + ] + }, + "documentation": null, + "id": 51, + "implemented": true, + "isConstructor": true, + "isDeclaredConst": false, + "modifiers": [], + "name": "Migrations", + "nodeType": "FunctionDefinition", + "parameters": { + "id": 43, + "nodeType": "ParameterList", + "parameters": [], + "src": "197:2:2" + }, + "payable": false, + "returnParameters": { + "id": 44, + "nodeType": "ParameterList", + "parameters": [], + "src": "207:0:2" + }, + "scope": 84, + "src": "178:58:2", + "stateMutability": "nonpayable", + "superFunction": null, + "visibility": "public" + }, + { + "body": { + "id": 62, + "nodeType": "Block", + "src": "296:47:2", + "statements": [ + { + "expression": { + "argumentTypes": null, + "id": 60, + "isConstant": false, + "isLValue": false, + "isPure": false, + "lValueRequested": false, + "leftHandSide": { + "argumentTypes": null, + "id": 58, + "name": "last_completed_migration", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 33, + "src": "302:24:2", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "nodeType": "Assignment", + "operator": "=", + "rightHandSide": { + "argumentTypes": null, + "id": 59, + "name": "completed", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 53, + "src": "329:9:2", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "src": "302:36:2", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "id": 61, + "nodeType": "ExpressionStatement", + "src": "302:36:2" + } + ] + }, + "documentation": null, + "id": 63, + "implemented": true, + "isConstructor": false, + "isDeclaredConst": false, + "modifiers": [ + { + "arguments": [], + "id": 56, + "modifierName": { + "argumentTypes": null, + "id": 55, + "name": "restricted", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 42, + "src": "285:10:2", + "typeDescriptions": { + "typeIdentifier": "t_modifier$__$", + "typeString": "modifier ()" + } + }, + "nodeType": "ModifierInvocation", + "src": "285:10:2" + } + ], + "name": "setCompleted", + "nodeType": "FunctionDefinition", + "parameters": { + "id": 54, + "nodeType": "ParameterList", + "parameters": [ + { + "constant": false, + "id": 53, + "name": "completed", + "nodeType": "VariableDeclaration", + "scope": 63, + "src": "262:14:2", + "stateVariable": false, + "storageLocation": "default", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + }, + "typeName": { + "id": 52, + "name": "uint", + "nodeType": "ElementaryTypeName", + "src": "262:4:2", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + }, + "value": null, + "visibility": "internal" + } + ], + "src": "261:16:2" + }, + "payable": false, + "returnParameters": { + "id": 57, + "nodeType": "ParameterList", + "parameters": [], + "src": "296:0:2" + }, + "scope": 84, + "src": "240:103:2", + "stateMutability": "nonpayable", + "superFunction": null, + "visibility": "public" + }, + { + "body": { + "id": 82, + "nodeType": "Block", + "src": "403:109:2", + "statements": [ + { + "assignments": [ + 71 + ], + "declarations": [ + { + "constant": false, + "id": 71, + "name": "upgraded", + "nodeType": "VariableDeclaration", + "scope": 83, + "src": "409:19:2", + "stateVariable": false, + "storageLocation": "default", + "typeDescriptions": { + "typeIdentifier": "t_contract$_Migrations_$84", + "typeString": "contract Migrations" + }, + "typeName": { + "contractScope": null, + "id": 70, + "name": "Migrations", + "nodeType": "UserDefinedTypeName", + "referencedDeclaration": 84, + "src": "409:10:2", + "typeDescriptions": { + "typeIdentifier": "t_contract$_Migrations_$84", + "typeString": "contract Migrations" + } + }, + "value": null, + "visibility": "internal" + } + ], + "id": 75, + "initialValue": { + "argumentTypes": null, + "arguments": [ + { + "argumentTypes": null, + "id": 73, + "name": "new_address", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 65, + "src": "442:11:2", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + } + } + ], + "expression": { + "argumentTypes": [ + { + "typeIdentifier": "t_address", + "typeString": "address" + } + ], + "id": 72, + "name": "Migrations", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 84, + "src": "431:10:2", + "typeDescriptions": { + "typeIdentifier": "t_type$_t_contract$_Migrations_$84_$", + "typeString": "type(contract Migrations)" + } + }, + "id": 74, + "isConstant": false, + "isLValue": false, + "isPure": false, + "kind": "typeConversion", + "lValueRequested": false, + "names": [], + "nodeType": "FunctionCall", + "src": "431:23:2", + "typeDescriptions": { + "typeIdentifier": "t_contract$_Migrations_$84", + "typeString": "contract Migrations" + } + }, + "nodeType": "VariableDeclarationStatement", + "src": "409:45:2" + }, + { + "expression": { + "argumentTypes": null, + "arguments": [ + { + "argumentTypes": null, + "id": 79, + "name": "last_completed_migration", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 33, + "src": "482:24:2", + "typeDescriptions": { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + } + ], + "expression": { + "argumentTypes": [ + { + "typeIdentifier": "t_uint256", + "typeString": "uint256" + } + ], + "expression": { + "argumentTypes": null, + "id": 76, + "name": "upgraded", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 71, + "src": "460:8:2", + "typeDescriptions": { + "typeIdentifier": "t_contract$_Migrations_$84", + "typeString": "contract Migrations" + } + }, + "id": 78, + "isConstant": false, + "isLValue": false, + "isPure": false, + "lValueRequested": false, + "memberName": "setCompleted", + "nodeType": "MemberAccess", + "referencedDeclaration": 63, + "src": "460:21:2", + "typeDescriptions": { + "typeIdentifier": "t_function_external_nonpayable$_t_uint256_$returns$__$", + "typeString": "function (uint256) external" + } + }, + "id": 80, + "isConstant": false, + "isLValue": false, + "isPure": false, + "kind": "functionCall", + "lValueRequested": false, + "names": [], + "nodeType": "FunctionCall", + "src": "460:47:2", + "typeDescriptions": { + "typeIdentifier": "t_tuple$__$", + "typeString": "tuple()" + } + }, + "id": 81, + "nodeType": "ExpressionStatement", + "src": "460:47:2" + } + ] + }, + "documentation": null, + "id": 83, + "implemented": true, + "isConstructor": false, + "isDeclaredConst": false, + "modifiers": [ + { + "arguments": [], + "id": 68, + "modifierName": { + "argumentTypes": null, + "id": 67, + "name": "restricted", + "nodeType": "Identifier", + "overloadedDeclarations": [], + "referencedDeclaration": 42, + "src": "392:10:2", + "typeDescriptions": { + "typeIdentifier": "t_modifier$__$", + "typeString": "modifier ()" + } + }, + "nodeType": "ModifierInvocation", + "src": "392:10:2" + } + ], + "name": "upgrade", + "nodeType": "FunctionDefinition", + "parameters": { + "id": 66, + "nodeType": "ParameterList", + "parameters": [ + { + "constant": false, + "id": 65, + "name": "new_address", + "nodeType": "VariableDeclaration", + "scope": 83, + "src": "364:19:2", + "stateVariable": false, + "storageLocation": "default", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + }, + "typeName": { + "id": 64, + "name": "address", + "nodeType": "ElementaryTypeName", + "src": "364:7:2", + "typeDescriptions": { + "typeIdentifier": "t_address", + "typeString": "address" + } + }, + "value": null, + "visibility": "internal" + } + ], + "src": "363:21:2" + }, + "payable": false, + "returnParameters": { + "id": 69, + "nodeType": "ParameterList", + "parameters": [], + "src": "403:0:2" + }, + "scope": 84, + "src": "347:165:2", + "stateMutability": "nonpayable", + "superFunction": null, + "visibility": "public" + } + ], + "scope": 85, + "src": "26:488:2" + } + ], + "src": "0:515:2" + }, + "compiler": { + "name": "solc", + "version": "0.4.21+commit.dfe3193c.Emscripten.clang" + }, + "networks": {}, + "schemaVersion": "2.0.0", + "updatedAt": "2018-04-14T03:37:39.710Z" +} \ No newline at end of file diff --git a/ethereum/src/main/resources/dev_truffle/contracts/ConvertLib.sol b/ethereum/src/main/resources/dev_truffle/contracts/ConvertLib.sol new file mode 100644 index 0000000000..ec0576fc3f --- /dev/null +++ b/ethereum/src/main/resources/dev_truffle/contracts/ConvertLib.sol @@ -0,0 +1,8 @@ +pragma solidity ^0.4.17; + +library ConvertLib{ + function convert(uint amount,uint conversionRate) returns (uint convertedAmount) + { + return amount * conversionRate; + } +} diff --git a/ethereum/src/main/resources/dev_truffle/contracts/Example.sol b/ethereum/src/main/resources/dev_truffle/contracts/Example.sol new file mode 100644 index 0000000000..c09c54843c --- /dev/null +++ b/ethereum/src/main/resources/dev_truffle/contracts/Example.sol @@ -0,0 +1,11 @@ +pragma solidity ^0.4.17; + +contract Example { + function Example() { + // constructor + } + + function ExampleFunction() { + // example function + } +} \ No newline at end of file diff --git a/ethereum/src/main/resources/dev_truffle/contracts/Migrations.sol b/ethereum/src/main/resources/dev_truffle/contracts/Migrations.sol new file mode 100644 index 0000000000..f170cb4fa7 --- /dev/null +++ b/ethereum/src/main/resources/dev_truffle/contracts/Migrations.sol @@ -0,0 +1,23 @@ +pragma solidity ^0.4.17; + +contract Migrations { + address public owner; + uint public last_completed_migration; + + modifier restricted() { + if (msg.sender == owner) _; + } + + function Migrations() public { + owner = msg.sender; + } + + function setCompleted(uint completed) public restricted { + last_completed_migration = completed; + } + + function upgrade(address new_address) public restricted { + Migrations upgraded = Migrations(new_address); + upgraded.setCompleted(last_completed_migration); + } +} diff --git a/ethereum/src/main/resources/dev_truffle/migrations/1_initial_migration.js b/ethereum/src/main/resources/dev_truffle/migrations/1_initial_migration.js new file mode 100644 index 0000000000..269ad95867 --- /dev/null +++ b/ethereum/src/main/resources/dev_truffle/migrations/1_initial_migration.js @@ -0,0 +1,3 @@ +module.exports = deployer => { + deployer.deploy(artifacts.require("./Migrations.sol")); +}; diff --git a/ethereum/src/main/resources/dev_truffle/migrations/2_deploy_contracts.js b/ethereum/src/main/resources/dev_truffle/migrations/2_deploy_contracts.js new file mode 100644 index 0000000000..b6f30176ae --- /dev/null +++ b/ethereum/src/main/resources/dev_truffle/migrations/2_deploy_contracts.js @@ -0,0 +1,8 @@ +const Example = artifacts.require("./Example.sol"), + ConvertLib = artifacts.require("./ConvertLib.sol"); + +module.exports = deployer => { + deployer.deploy(ConvertLib); + deployer.link(ConvertLib, Example); + deployer.deploy(Example); +}; diff --git a/ethereum/src/main/resources/dev_truffle/truffle.js b/ethereum/src/main/resources/dev_truffle/truffle.js new file mode 100644 index 0000000000..8110fdad45 --- /dev/null +++ b/ethereum/src/main/resources/dev_truffle/truffle.js @@ -0,0 +1,20 @@ +module.exports = { + contracts_build_directory: "./build/contracts", + networks: { + live: { + network_id: 1, // Ethereum public network + host: 'localhost', + port: 8545 + }, + testnet: { + network_id: 3, // Official Ethereum test network (Ropsten) + host: 'localhost', + port: 8545 + }, + development: { + host: 'localhost', + port: 8545, + network_id: '*' + } + } +} diff --git a/ethereum/src/main/resources/logback.xml b/ethereum/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/ethereum/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/ethereumj/src/main/resources/solidity/Greeting.sol b/ethereum/src/main/resources/solidity/Greeting.sol similarity index 100% rename from ethereumj/src/main/resources/solidity/Greeting.sol rename to ethereum/src/main/resources/solidity/Greeting.sol diff --git a/ethereumj/src/main/resources/solidity/build/Greeting.abi b/ethereum/src/main/resources/solidity/build/Greeting.abi similarity index 100% rename from ethereumj/src/main/resources/solidity/build/Greeting.abi rename to ethereum/src/main/resources/solidity/build/Greeting.abi diff --git a/ethereumj/src/main/resources/solidity/build/Greeting.bin b/ethereum/src/main/resources/solidity/build/Greeting.bin similarity index 100% rename from ethereumj/src/main/resources/solidity/build/Greeting.bin rename to ethereum/src/main/resources/solidity/build/Greeting.bin diff --git a/spring-security-mvc-socket/src/main/webapp/resources/styles/style.css b/ethereum/src/main/webapp/WEB-INF/.gitkeep similarity index 100% rename from spring-security-mvc-socket/src/main/webapp/resources/styles/style.css rename to ethereum/src/main/webapp/WEB-INF/.gitkeep diff --git a/ethereum/src/main/webapp/resources/.gitkeep b/ethereum/src/main/webapp/resources/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerLiveTest.java b/ethereum/src/test/java/com/baeldung/ethereumj/controllers/EthControllerLiveTest.java similarity index 99% rename from ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerLiveTest.java rename to ethereum/src/test/java/com/baeldung/ethereumj/controllers/EthControllerLiveTest.java index f62d229261..7676b99224 100644 --- a/ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerLiveTest.java +++ b/ethereum/src/test/java/com/baeldung/ethereumj/controllers/EthControllerLiveTest.java @@ -74,4 +74,4 @@ public class EthControllerLiveTest { assertTrue("Dynamic data returned?", a.hasBody()); System.out.println("Dynamic data returned?: " + a.hasBody()); } -} +} \ No newline at end of file diff --git a/ethereum/src/test/java/com/baeldung/web3j/controllers/EthereumRestControllerIntegrationTest.java b/ethereum/src/test/java/com/baeldung/web3j/controllers/EthereumRestControllerIntegrationTest.java new file mode 100644 index 0000000000..ee78ab17c2 --- /dev/null +++ b/ethereum/src/test/java/com/baeldung/web3j/controllers/EthereumRestControllerIntegrationTest.java @@ -0,0 +1,78 @@ +package com.baeldung.web3j.controllers; + + +import com.baeldung.web3j.config.AppConfig; +import com.baeldung.web3j.constants.Constants; +import org.junit.After; +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.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {AppConfig.class}) +@WebAppConfiguration +public class EthereumRestControllerIntegrationTest { + + private MockMvc mockMvc; + + private void constructAsyncTest(String endpoint) { + try { + MvcResult asyncResult = mockMvc + .perform(get(endpoint)) + .andReturn(); + + mockMvc.perform(asyncDispatch(asyncResult)) + .andDo(print()) + .andExpect(status().isOk()); + + } catch (Exception e) { + System.out.println("Exception: " + e); + } + } + + @Autowired + private WebApplicationContext wac; + + @Before + public void preTest() throws Exception { + mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + } + + @Test + public void accounts() { + constructAsyncTest(Constants.API_ACCOUNTS); + } + + @Test + public void transactions() { + constructAsyncTest(Constants.API_TRANSACTIONS); + } + + @Test + public void block() { + constructAsyncTest(Constants.API_BLOCK); + } + + @Test + public void balance() { + constructAsyncTest(Constants.API_BALANCE); + } + + @After + public void postTest() { + mockMvc = null; + } +} \ No newline at end of file diff --git a/ethereum/src/test/java/com/baeldung/web3j/controllers/EthereumRestControllerUnitTest.java b/ethereum/src/test/java/com/baeldung/web3j/controllers/EthereumRestControllerUnitTest.java new file mode 100644 index 0000000000..4ceed870f8 --- /dev/null +++ b/ethereum/src/test/java/com/baeldung/web3j/controllers/EthereumRestControllerUnitTest.java @@ -0,0 +1,76 @@ +package com.baeldung.web3j.controllers; + +import com.baeldung.web3j.constants.Constants; +import com.baeldung.web3j.services.Web3Service; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +public class EthereumRestControllerUnitTest { + + private MockMvc mockMvc; + + private void constructAsyncTest(String endpoint) { + try { + MvcResult asyncResult = mockMvc + .perform(get(endpoint)) + .andReturn(); + + mockMvc.perform(asyncDispatch(asyncResult)) + .andDo(print()) + .andExpect(status().isOk()); + + } catch (Exception e) { + System.out.println("Exception: " + e); + } + } + + @Mock + private Web3Service web3Service; + + @InjectMocks + private EthereumRestController ethereumRestController; + + @Before + public void preTest() { + MockitoAnnotations.initMocks(this); + mockMvc = MockMvcBuilders.standaloneSetup(ethereumRestController).build(); + } + + @Test + public void accounts() { + constructAsyncTest(Constants.API_ACCOUNTS); + } + + @Test + public void transactions() { + constructAsyncTest(Constants.API_TRANSACTIONS); + } + + @Test + public void block() { + constructAsyncTest(Constants.API_BLOCK); + } + + @Test + public void balance() { + constructAsyncTest(Constants.API_BALANCE); + } + + @After + public void postTest() { + mockMvc = null; + } + +} diff --git a/ethereum/src/test/java/com/baeldung/web3j/services/EthereumContractUnitTest.java b/ethereum/src/test/java/com/baeldung/web3j/services/EthereumContractUnitTest.java new file mode 100644 index 0000000000..382c96e985 --- /dev/null +++ b/ethereum/src/test/java/com/baeldung/web3j/services/EthereumContractUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.web3j.services; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.concurrent.CompletableFuture; + +public class EthereumContractUnitTest { + + private Web3Service web3Service; + + @Before + public void setup() { + web3Service = new Web3Service(); + } + + @Test + public void testContract() { + CompletableFuture result = web3Service.fromScratchContractExample(); + assert (result instanceof CompletableFuture); + } + + @Test + public void sendTx() { + CompletableFuture result = web3Service.sendTx(); + assert (result instanceof CompletableFuture); + } + + @After + public void cleanup() { + } +} diff --git a/ethereumj/README.md b/ethereumj/README.md deleted file mode 100644 index 5a0be0bd16..0000000000 --- a/ethereumj/README.md +++ /dev/null @@ -1,5 +0,0 @@ -## EthereumJ - -### Relevant Articles: -- [Introduction to EthereumJ](http://www.baeldung.com/ethereumj) -- [Creating and Deploying Smart Contracts with Solidity](http://www.baeldung.com/smart-contracts-ethereum-solidity) diff --git a/ethereumj/pom.xml b/ethereumj/pom.xml deleted file mode 100644 index 611b7b09eb..0000000000 --- a/ethereumj/pom.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - 4.0.0 - com.baeldung.ethereumj - ethereumj - war - 1.0.0 - ethereumj - - - parent-boot-5 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-5 - - - - - 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 - test - - - - org.ethereum - ethereumj-core - ${ethereumj-core.version} - - - - org.web3j - core - ${web3j.core.version} - - - - javax.servlet - jstl - - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind.version} - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - ethereumj - - - - UTF-8 - 1.8 - 8.5.4 - 1.5.0-RELEASE - 3.3.1 - 2.5.0 - - - \ No newline at end of file diff --git a/ethereumj/src/main/resources/logback.xml b/ethereumj/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/ethereumj/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/feign/pom.xml b/feign/pom.xml index ffcde60c54..ea645383c1 100644 --- a/feign/pom.xml +++ b/feign/pom.xml @@ -1,10 +1,10 @@ - + 4.0.0 com.baeldung.feign - feign-client + feign + feign com.baeldung @@ -55,7 +55,6 @@ - UTF-8 9.4.0 1.16.12 1.4.2.RELEASE diff --git a/feign/src/main/resources/logback.xml b/feign/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/feign/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/flips/pom.xml b/flips/pom.xml index be9f584114..75dc8bb579 100644 --- a/flips/pom.xml +++ b/flips/pom.xml @@ -8,10 +8,10 @@ flips - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -56,9 +56,6 @@ - UTF-8 - 1.8 - 1.8 1.5.10.RELEASE 1.5.9.RELEASE 1.0.1 diff --git a/flips/src/main/resources/logback.xml b/flips/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/flips/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java b/flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java new file mode 100644 index 0000000000..9dd4ef064a --- /dev/null +++ b/flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java @@ -0,0 +1,74 @@ +package com.baeldung.flips.controller; + +import org.hamcrest.Matchers; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +@RunWith(SpringRunner.class) +@SpringBootTest(properties = { + "feature.foo.by.id=Y", + "feature.new.foo=Y", + "last.active.after=2018-03-14T00:00:00Z", + "first.active.after=2999-03-15T00:00:00Z", + "logging.level.org.flips=info" + +}, webEnvironment = SpringBootTest.WebEnvironment.MOCK) +@AutoConfigureMockMvc +@ActiveProfiles("dev") +public class FlipControllerIntegrationTest { + + @Autowired private MockMvc mvc; + + @Test + public void givenValidDayOfWeek_APIAvailable() throws Exception { + mvc.perform(MockMvcRequestBuilders.get("/foo/1")) + .andExpect(MockMvcResultMatchers.status().is(200)) + .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo1"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(1))); + } + + @Test + public void givenValidDate_APIAvailable() throws Exception { + mvc.perform(MockMvcRequestBuilders.get("/foo/last")) + .andExpect(MockMvcResultMatchers.status().is(200)) + .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo6"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(6))); + } + + @Test + public void givenInvalidDate_APINotAvailable() throws Exception { + mvc.perform(MockMvcRequestBuilders.get("/foo/first")) + .andExpect(MockMvcResultMatchers.status().is(501)); + } + + @Test + public void givenCorrectProfile_APIAvailable() throws Exception { + mvc.perform(MockMvcRequestBuilders.get("/foos")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(6))); + } + + @Test + public void givenPropertySet_APIAvailable() throws Exception { + mvc.perform(MockMvcRequestBuilders.get("/foos/1")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo1"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(1))); + } + + @Test + public void getValidExpression_FlipBean() throws Exception { + mvc.perform(MockMvcRequestBuilders.get("/foo/new")) + .andExpect(MockMvcResultMatchers.status().is(200)) + .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Shiny New Foo!"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(100))); + } +} \ No newline at end of file diff --git a/flips/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java b/flips/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java deleted file mode 100644 index 8fd9c4e340..0000000000 --- a/flips/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.flips.controller; - -import org.hamcrest.Matchers; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; - -@RunWith(SpringRunner.class) -@SpringBootTest(properties = { - "feature.foo.by.id=Y", - "feature.new.foo=Y", - "last.active.after=2018-03-14T00:00:00Z", - "first.active.after=2999-03-15T00:00:00Z", - "logging.level.org.flips=info" - -}, webEnvironment = SpringBootTest.WebEnvironment.MOCK) -@AutoConfigureMockMvc -@ActiveProfiles("dev") -public class FlipControllerTest { - - @Autowired private MockMvc mvc; - - @Test - public void givenValidDayOfWeek_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/1")) - .andExpect(MockMvcResultMatchers.status().is(200)) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo1"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(1))); - } - - @Test - public void givenValidDate_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/last")) - .andExpect(MockMvcResultMatchers.status().is(200)) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo6"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(6))); - } - - @Test - public void givenInvalidDate_APINotAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/first")) - .andExpect(MockMvcResultMatchers.status().is(501)); - } - - @Test - public void givenCorrectProfile_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foos")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(6))); - } - - @Test - public void givenPropertySet_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foos/1")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo1"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(1))); - } - - @Test - public void getValidExpression_FlipBean() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/new")) - .andExpect(MockMvcResultMatchers.status().is(200)) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Shiny New Foo!"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(100))); - } -} \ No newline at end of file diff --git a/flyway/pom.xml b/flyway/pom.xml index 3637f1de28..b1cc58af3d 100644 --- a/flyway/pom.xml +++ b/flyway/pom.xml @@ -8,10 +8,10 @@ Flyway Callbacks Demo - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -27,7 +27,7 @@ mysql mysql-connector-java - ${mysql-connector-java.version} + runtime com.h2database @@ -63,11 +63,7 @@ - UTF-8 - UTF-8 - 1.8 5.0.2 - 6.0.3 5.0.2 diff --git a/flyway/src/main/resources/logback.xml b/flyway/src/main/resources/logback.xml index 7f4aa46e0d..56af2d397e 100644 --- a/flyway/src/main/resources/logback.xml +++ b/flyway/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/geotools/pom.xml b/geotools/pom.xml index 9347d17fc1..3ac8a63564 100644 --- a/geotools/pom.xml +++ b/geotools/pom.xml @@ -1,67 +1,62 @@ - - 4.0.0 - com.baeldung - geotools - 0.0.1-SNAPSHOT - jar - geotools - http://maven.apache.org + + 4.0.0 + geotools + 0.0.1-SNAPSHOT + jar + geotools + http://maven.apache.org - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - - junit - junit - ${junit.version} - test - - - org.geotools - gt-shapefile - ${geotools-shapefile.version} - - - org.geotools - gt-epsg-hsql - ${geotools.version} - - - org.geotools - gt-swing - ${geotools-swing.version} - - + + + 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 - - + + + 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 + + + + + 15.2 + 15.2 + 15.2 + - - 15.2 - 15.2 - 15.2 - diff --git a/geotools/src/main/resources/logback.xml b/geotools/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/geotools/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/google-cloud/pom.xml b/google-cloud/pom.xml index b6e54e33c1..85f47cc2f5 100644 --- a/google-cloud/pom.xml +++ b/google-cloud/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 google-cloud 0.1-SNAPSHOT @@ -31,7 +31,6 @@ 1.16.18 - UTF-8 1.16.0 diff --git a/google-cloud/src/main/resources/logback.xml b/google-cloud/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/google-cloud/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/google-web-toolkit/README.md b/google-web-toolkit/README.md new file mode 100644 index 0000000000..65264375bc --- /dev/null +++ b/google-web-toolkit/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Introduction to GWT](http://www.baeldung.com/gwt) +- [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter) diff --git a/google-web-toolkit/pom.xml b/google-web-toolkit/pom.xml new file mode 100644 index 0000000000..db9ce2eac0 --- /dev/null +++ b/google-web-toolkit/pom.xml @@ -0,0 +1,125 @@ + + + + + 4.0.0 + com.baeldung + google-web-toolkit + war + 1.0-SNAPSHOT + google-web-toolkit + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + + com.google.gwt + gwt + 2.8.2 + pom + import + + + + + + + com.google.gwt + gwt-servlet + runtime + + + com.google.gwt + gwt-user + provided + + + com.google.gwt + gwt-dev + provided + + + junit + junit + 4.11 + test + + + + + + ${project.build.directory}/${project.build.finalName}/WEB-INF/classes + + + + + + net.ltgt.gwt.maven + gwt-maven-plugin + 1.0-rc-8 + + + + compile + test + + + + + com.baeldung.Google_web_toolkit + Google_web_toolkit + true + + 1.8 + + + + -compileReport + -XcompilerMetrics + + + ${project.build.directory}/${project.build.finalName} + compile+runtime + + + Google_web_toolkit.html + + + + + + + maven-surefire-plugin + 2.17 + + true + + + + + + + + + + 1.8 + 1.8 + + + UTF-8 + UTF-8 + + + diff --git a/google-web-toolkit/src/main/java/com/baeldung/Google_web_toolkit.gwt.xml b/google-web-toolkit/src/main/java/com/baeldung/Google_web_toolkit.gwt.xml new file mode 100644 index 0000000000..9bd74ccb50 --- /dev/null +++ b/google-web-toolkit/src/main/java/com/baeldung/Google_web_toolkit.gwt.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/google-web-toolkit/src/main/java/com/baeldung/client/Google_web_toolkit.java b/google-web-toolkit/src/main/java/com/baeldung/client/Google_web_toolkit.java new file mode 100644 index 0000000000..ae0ae7da38 --- /dev/null +++ b/google-web-toolkit/src/main/java/com/baeldung/client/Google_web_toolkit.java @@ -0,0 +1,108 @@ +package com.baeldung.client; + +import com.baeldung.shared.MessageService; +import com.baeldung.shared.MessageServiceAsync; +import com.google.gwt.core.client.EntryPoint; +import com.google.gwt.core.client.GWT; +import com.google.gwt.event.dom.client.ClickEvent; +import com.google.gwt.event.dom.client.ClickHandler; +import com.google.gwt.event.dom.client.KeyCodes; +import com.google.gwt.event.dom.client.KeyUpEvent; +import com.google.gwt.event.dom.client.KeyUpHandler; +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.google.gwt.user.client.ui.Button; +import com.google.gwt.user.client.ui.DialogBox; +import com.google.gwt.user.client.ui.HTML; +import com.google.gwt.user.client.ui.Label; +import com.google.gwt.user.client.ui.RootPanel; +import com.google.gwt.user.client.ui.TextBox; +import com.google.gwt.user.client.ui.VerticalPanel; + +/** + * Entry point classes define onModuleLoad(). + */ +public class Google_web_toolkit implements EntryPoint { + private final MessageServiceAsync messageServiceAsync = GWT.create(MessageService.class); + + public void onModuleLoad() { + Button sendButton = new Button("Submit"); + TextBox nameField = new TextBox(); + nameField.setText("Hi there"); + + Label warningLabel = new Label(); + + sendButton.addStyleName("sendButton"); + + RootPanel.get("nameFieldContainer").add(nameField); + RootPanel.get("sendButtonContainer").add(sendButton); + RootPanel.get("errorLabelContainer").add(warningLabel); + + Button closeButton = new Button("Thanks"); + closeButton.getElement().setId("closeButton"); + + Label textToServerLabel = new Label(); + HTML serverResponseLabel = new HTML(); + VerticalPanel vPanel = new VerticalPanel(); + vPanel.addStyleName("vPanel"); + vPanel.add(new HTML("Sending message to the server:")); + vPanel.add(textToServerLabel); + vPanel.add(new HTML("
Server replies:")); + vPanel.add(serverResponseLabel); + vPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT); + vPanel.add(closeButton); + vPanel.setVisible(false); + RootPanel.get("serverResponseContainer").add(vPanel); + + closeButton.addClickHandler(event -> { + sendButton.setEnabled(true); + sendButton.setFocus(true); + vPanel.setVisible(false); + }); + + class MyHandler implements ClickHandler, KeyUpHandler { + + public void onClick(ClickEvent event) { + sendMessageToServer(); + } + + public void onKeyUp(KeyUpEvent event) { + if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { + sendMessageToServer(); + } + } + + private void sendMessageToServer() { + + warningLabel.setText(""); + String textToServer = nameField.getText(); + if (textToServer == null || textToServer.isEmpty()) { + warningLabel.setText("Please enter the message"); + return; + } + + sendButton.setEnabled(false); + textToServerLabel.setText(textToServer); + serverResponseLabel.setText(""); + messageServiceAsync.sendMessage(textToServer, new AsyncCallback() { + public void onFailure(Throwable caught) { + serverResponseLabel.addStyleName("serverResponseLabelError"); + serverResponseLabel.setHTML("server error occurred"); + closeButton.setFocus(true); + } + + public void onSuccess(String result) { + serverResponseLabel.removeStyleName("serverResponseLabelError"); + serverResponseLabel.setHTML(result); + closeButton.setFocus(true); + vPanel.setVisible(true); + } + }); + } + } + + // Add a handler to send the name to the server + MyHandler handler = new MyHandler(); + sendButton.addClickHandler(handler); + nameField.addKeyUpHandler(handler); + } +} diff --git a/google-web-toolkit/src/main/java/com/baeldung/server/MessageServiceImpl.java b/google-web-toolkit/src/main/java/com/baeldung/server/MessageServiceImpl.java new file mode 100644 index 0000000000..41e2a4725c --- /dev/null +++ b/google-web-toolkit/src/main/java/com/baeldung/server/MessageServiceImpl.java @@ -0,0 +1,22 @@ +package com.baeldung.server; + +import com.baeldung.shared.MessageService; +import com.google.gwt.user.server.rpc.RemoteServiceServlet; + +import java.time.LocalDateTime; + +/** + * The server-side implementation of the RPC service. + */ +@SuppressWarnings("serial") +public class MessageServiceImpl extends RemoteServiceServlet implements MessageService { + + public String sendMessage(String message) throws IllegalArgumentException { + if (message == null) { + throw new IllegalArgumentException("message is null"); + } + + return "Hello, " + message + "!

Time received: " + LocalDateTime.now(); + } + +} diff --git a/google-web-toolkit/src/main/java/com/baeldung/shared/MessageService.java b/google-web-toolkit/src/main/java/com/baeldung/shared/MessageService.java new file mode 100644 index 0000000000..2c74a5c00d --- /dev/null +++ b/google-web-toolkit/src/main/java/com/baeldung/shared/MessageService.java @@ -0,0 +1,12 @@ +package com.baeldung.shared; + +import com.google.gwt.user.client.rpc.RemoteService; +import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; + +/** + * The client-side stub for the RPC service. + */ +@RemoteServiceRelativePath("greet") +public interface MessageService extends RemoteService { + String sendMessage(String message) throws IllegalArgumentException; +} diff --git a/google-web-toolkit/src/main/java/com/baeldung/shared/MessageServiceAsync.java b/google-web-toolkit/src/main/java/com/baeldung/shared/MessageServiceAsync.java new file mode 100644 index 0000000000..49d4a29b7b --- /dev/null +++ b/google-web-toolkit/src/main/java/com/baeldung/shared/MessageServiceAsync.java @@ -0,0 +1,10 @@ +package com.baeldung.shared; + +import com.google.gwt.user.client.rpc.AsyncCallback; + +/** + * The async counterpart of MessageService. + */ +public interface MessageServiceAsync { + void sendMessage(String input, AsyncCallback callback) throws IllegalArgumentException; +} diff --git a/google-web-toolkit/src/main/resources/logback.xml b/google-web-toolkit/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/google-web-toolkit/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/google-web-toolkit/src/main/webapp/Google_web_toolkit.css b/google-web-toolkit/src/main/webapp/Google_web_toolkit.css new file mode 100644 index 0000000000..b02f219589 --- /dev/null +++ b/google-web-toolkit/src/main/webapp/Google_web_toolkit.css @@ -0,0 +1,31 @@ +/** Add css rules here for your application. */ +h1 { + font-size: 2em; + font-weight: bold; + color: #777777; + margin: 40px 0px 70px; + text-align: center; +} + +.sendButton { + display: block; + font-size: 16pt; +} + +/** Most GWT widgets already have a style name defined */ +.gwt-DialogBox { + width: 400px; +} + +.vPanel { + margin: 5px; +} + +.serverResponseLabelError { + color: red; +} + +/** Set ids using widget.getElement().setId("idOfElement") */ +#closeButton { + margin: 15px 6px 6px; +} \ No newline at end of file diff --git a/google-web-toolkit/src/main/webapp/Google_web_toolkit.html b/google-web-toolkit/src/main/webapp/Google_web_toolkit.html new file mode 100644 index 0000000000..20bba68eff --- /dev/null +++ b/google-web-toolkit/src/main/webapp/Google_web_toolkit.html @@ -0,0 +1,35 @@ + + + + + + + + + + + + Sample GWT Application + + + + + +

Sample GWT Application

+ + + + + + + + + + + + + + +
Please enter your message:
+ + \ No newline at end of file diff --git a/google-web-toolkit/src/main/webapp/WEB-INF/web.xml b/google-web-toolkit/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..820d3d9916 --- /dev/null +++ b/google-web-toolkit/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,24 @@ + + + + + + greetServlet + com.baeldung.server.MessageServiceImpl + + + + greetServlet + /google_web_toolkit/greet + + + + + Google_web_toolkit.html + + + diff --git a/google-web-toolkit/src/main/webapp/favicon.ico b/google-web-toolkit/src/main/webapp/favicon.ico new file mode 100644 index 0000000000..858a707523 Binary files /dev/null and b/google-web-toolkit/src/main/webapp/favicon.ico differ diff --git a/graphql/graphql-java/pom.xml b/graphql/graphql-java/pom.xml index 27d2cebf26..fb121d3234 100644 --- a/graphql/graphql-java/pom.xml +++ b/graphql/graphql-java/pom.xml @@ -1,5 +1,5 @@ + 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.graphql graphql-java diff --git a/graphql/graphql-java/src/main/resources/logback.xml b/graphql/graphql-java/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/graphql/graphql-java/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/grpc/pom.xml b/grpc/pom.xml index ad563f16fd..949f26d376 100644 --- a/grpc/pom.xml +++ b/grpc/pom.xml @@ -1,13 +1,11 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - grpc - grpc-demo + grpc 0.0.1-SNAPSHOT jar - grpc-demo - http://maven.apache.org - + grpc + com.baeldung parent-modules @@ -73,7 +71,6 @@ - UTF-8 1.5.0 1.5.0.Final 0.5.0 diff --git a/grpc/src/main/resources/logback.xml b/grpc/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/grpc/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/gson/README.md b/gson/README.md index 60c80477b1..4122b21431 100644 --- a/gson/README.md +++ b/gson/README.md @@ -6,3 +6,5 @@ ### Relevant Articles: - [Gson Deserialization Cookbook](http://www.baeldung.com/gson-deserialization-guide) - [Jackson vs Gson](http://www.baeldung.com/jackson-vs-gson) +- [Exclude Fields from Serialization in Gson](http://www.baeldung.com/gson-exclude-fields-serialization) +- [Save Data to a JSON File with Gson](https://www.baeldung.com/gson-save-file) diff --git a/gson/pom.xml b/gson/pom.xml index 912111374d..6e7779d26a 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -1,67 +1,73 @@ - - 4.0.0 - com.baeldung - gson - 0.1-SNAPSHOT - gson + + 4.0.0 + com.baeldung + gson + 0.1-SNAPSHOT + gson - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + - - - - joda-time - joda-time - ${joda-time.version} - - - commons-io - commons-io - ${commons-io.version} - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - com.google.code.gson - gson - ${gson.version} - - + + + + org.projectlombok + lombok + ${lombok.version} + provided + + + joda-time + joda-time + ${joda-time.version} + + + commons-io + commons-io + ${commons-io.version} + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + com.google.code.gson + gson + ${gson.version} + + - - gson - - - src/main/resources - true - - - + + gson + + + src/main/resources + true + + + - - - 2.8.0 - - 19.0 - 3.5 - 4.1 - 2.5 - 2.9.6 - + + + 2.8.0 + + 3.5 + 4.1 + 2.9.6 + 1.16.10 + \ No newline at end of file diff --git a/gson/src/main/java/org/baeldung/gson/entities/User.java b/gson/src/main/java/org/baeldung/gson/entities/User.java new file mode 100644 index 0000000000..b413f3300e --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/entities/User.java @@ -0,0 +1,19 @@ +package org.baeldung.gson.entities; + +public class User { + + private int id; + private String name; + private transient String nationality; + + public User(int id, String name, String nationality) { + this.id = id; + this.name = name; + this.nationality = nationality; + } + + public User(int id, String name) { + this(id, name, null); + } + +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/Exclude.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/Exclude.java new file mode 100644 index 0000000000..429cb9d1b5 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/Exclude.java @@ -0,0 +1,11 @@ +package org.baeldung.gson.serializationwithexclusions; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface Exclude { +} \ No newline at end of file diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClass.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClass.java new file mode 100644 index 0000000000..cc6c498458 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClass.java @@ -0,0 +1,13 @@ +package org.baeldung.gson.serializationwithexclusions; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MyClass { + private long id; + private String name; + private String other; + private MySubClass subclass; +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithAnnotatedFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithAnnotatedFields.java new file mode 100644 index 0000000000..5d41f8a224 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithAnnotatedFields.java @@ -0,0 +1,20 @@ +package org.baeldung.gson.serializationwithexclusions; + +import com.google.gson.annotations.Expose; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MyClassWithAnnotatedFields { + + @Expose + private long id; + @Expose + private String name; + private String other; + @Expose + private MySubClassWithAnnotatedFields subclass; + +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithCustomAnnotatedFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithCustomAnnotatedFields.java new file mode 100644 index 0000000000..ace3583013 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithCustomAnnotatedFields.java @@ -0,0 +1,16 @@ +package org.baeldung.gson.serializationwithexclusions; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MyClassWithCustomAnnotatedFields { + + private long id; + private String name; + @Exclude + private String other; + private MySubClassWithCustomAnnotatedFields subclass; + +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithTransientFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithTransientFields.java new file mode 100644 index 0000000000..5e781a6287 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithTransientFields.java @@ -0,0 +1,15 @@ +package org.baeldung.gson.serializationwithexclusions; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MyClassWithTransientFields { + + private long id; + private String name; + private transient String other; + private MySubClassWithTransientFields subclass; + +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClass.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClass.java new file mode 100644 index 0000000000..5adac0697e --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClass.java @@ -0,0 +1,12 @@ +package org.baeldung.gson.serializationwithexclusions; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MySubClass { + private long id; + private String description; + private String otherVerboseInfo; +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithAnnotatedFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithAnnotatedFields.java new file mode 100644 index 0000000000..a0f7b5d277 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithAnnotatedFields.java @@ -0,0 +1,15 @@ +package org.baeldung.gson.serializationwithexclusions; + +import com.google.gson.annotations.Expose; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MySubClassWithAnnotatedFields { + + @Expose private long id; + @Expose private String description; + private String otherVerboseInfo; +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithCustomAnnotatedFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithCustomAnnotatedFields.java new file mode 100644 index 0000000000..f6aa4651b3 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithCustomAnnotatedFields.java @@ -0,0 +1,14 @@ +package org.baeldung.gson.serializationwithexclusions; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MySubClassWithCustomAnnotatedFields { + + private long id; + private String description; + @Exclude + private String otherVerboseInfo; +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithTransientFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithTransientFields.java new file mode 100644 index 0000000000..d4e31b0bc8 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithTransientFields.java @@ -0,0 +1,13 @@ +package org.baeldung.gson.serializationwithexclusions; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MySubClassWithTransientFields { + + private long id; + private String description; + private transient String otherVerboseInfo; +} diff --git a/gson/src/main/resources/logback.xml b/gson/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/gson/src/main/resources/logback.xml +++ b/gson/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/gson/src/test/java/org/baeldung/gson/serialization/test/JsonFileUnitTest.java b/gson/src/test/java/org/baeldung/gson/serialization/test/JsonFileUnitTest.java new file mode 100644 index 0000000000..f6a8de080c --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/serialization/test/JsonFileUnitTest.java @@ -0,0 +1,43 @@ +package org.baeldung.gson.serialization.test; + +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; +import java.nio.file.Files; +import java.nio.file.Paths; + +import org.baeldung.gson.entities.User; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +@RunWith(Parameterized.class) +public class JsonFileUnitTest { + + @Parameter + public Object object; + + @Parameters + public static Object[] data() { + return new Object[] { 123.45, new User(1, "Tom", "American") }; + } + + @Test + public void givenProperData_whenStoredInFile_shouldSaveJsonSuccessfully() { + String filePath = "target/output.json"; + try (Writer writer = new FileWriter(filePath)) { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + gson.toJson(object, writer); + Assert.assertTrue(Files.exists(Paths.get(filePath))); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/gson/src/test/java/org/baeldung/gson/serializationwithexclusions/SerializationWithExclusionsUnitTest.java b/gson/src/test/java/org/baeldung/gson/serializationwithexclusions/SerializationWithExclusionsUnitTest.java new file mode 100644 index 0000000000..632d06946b --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/serializationwithexclusions/SerializationWithExclusionsUnitTest.java @@ -0,0 +1,104 @@ +package org.baeldung.gson.serializationwithexclusions; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +import com.google.gson.ExclusionStrategy; +import com.google.gson.FieldAttributes; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +class SerializationWithExclusionsUnitTest { + + final String expectedResult = "{\"id\":1,\"name\":\"foo\",\"subclass\":{\"id\":42,\"description\":\"the answer\"}}"; + + @Test + public void givenClassWithTransientFields_whenSerializing_thenCorrectWithoutTransientFields() { + MyClassWithTransientFields source = new MyClassWithTransientFields(1L, "foo", "bar", new MySubClassWithTransientFields(42L, "the answer", "Verbose field which we don't want to be serialized")); + String jsonString = new Gson().toJson(source); + assertEquals(expectedResult, jsonString); + } + + @Test + public void givenClassAnnotated_whenSerializing_thenCorrectWithoutNotAnnotatedFields() { + MyClassWithAnnotatedFields source = new MyClassWithAnnotatedFields(1L, "foo", "bar", new MySubClassWithAnnotatedFields(42L, "the answer", "Verbose field which we don't want to be serialized")); + Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation() + .create(); + String jsonString = gson.toJson(source); + + assertEquals(expectedResult, jsonString); + } + + @Test + public void givenExclusionStrategyByClassesAndFields_whenSerializing_thenFollowStrategy() { + MyClass source = new MyClass(1L, "foo", "bar", new MySubClass(42L, "the answer", "Verbose field which we don't want to be serialized")); + ExclusionStrategy strategy = new ExclusionStrategy() { + @Override + public boolean shouldSkipField(FieldAttributes field) { + if (field.getDeclaringClass() == MyClass.class && field.getName() + .equals("other")) + return true; + if (field.getDeclaringClass() == MySubClass.class && field.getName() + .equals("otherVerboseInfo")) + return true; + return false; + } + + @Override + public boolean shouldSkipClass(Class clazz) { + return false; + } + }; + + Gson gson = new GsonBuilder().addSerializationExclusionStrategy(strategy) + .create(); + String jsonString = gson.toJson(source); + + assertEquals(expectedResult, jsonString); + } + + @Test + public void givenExclusionStrategyByStartsWith_whenSerializing_thenFollowStrategy() { + MyClass source = new MyClass(1L, "foo", "bar", new MySubClass(42L, "the answer", "Verbose field which we don't want to be serialized")); + ExclusionStrategy strategy = new ExclusionStrategy() { + @Override + public boolean shouldSkipClass(Class clazz) { + return false; + } + + @Override + public boolean shouldSkipField(FieldAttributes field) { + return field.getName().startsWith("other"); + } + }; + Gson gson = new GsonBuilder().setExclusionStrategies(strategy) + .create(); + String jsonString = gson.toJson(source); + + assertEquals(expectedResult, jsonString); + } + + @Test + public void givenExclusionStrategyByCustomAnnotation_whenSerializing_thenFollowStrategy() { + MyClassWithCustomAnnotatedFields source = new MyClassWithCustomAnnotatedFields(1L, "foo", "bar", new MySubClassWithCustomAnnotatedFields(42L, "the answer", "Verbose field which we don't want to be serialized")); + ExclusionStrategy strategy = new ExclusionStrategy() { + @Override + public boolean shouldSkipClass(Class clazz) { + return false; + } + + @Override + public boolean shouldSkipField(FieldAttributes field) { + return field.getAnnotation(Exclude.class) != null; + } + + }; + + Gson gson = new GsonBuilder().setExclusionStrategies(strategy) + .create(); + String jsonString = gson.toJson(source); + assertEquals(expectedResult, jsonString); + } + +} \ No newline at end of file diff --git a/guava-modules/guava-18/pom.xml b/guava-modules/guava-18/pom.xml index b3deb305f2..ce9395fbf4 100644 --- a/guava-modules/guava-18/pom.xml +++ b/guava-modules/guava-18/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung guava-18 @@ -9,8 +9,8 @@ com.baeldung parent-java - 0.0.1-SNAPSHOT - ../../parent-java + 0.0.1-SNAPSHOT + ../../parent-java diff --git a/guava-modules/guava-18/src/main/resources/logback.xml b/guava-modules/guava-18/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/guava-modules/guava-18/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java b/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java deleted file mode 100644 index db82ea6da8..0000000000 --- a/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.guava; - -import com.google.common.hash.HashCode; -import com.google.common.hash.Hashing; -import com.google.common.net.InetAddresses; -import org.junit.Assert; -import org.junit.Test; - -import java.net.InetAddress; -import java.util.concurrent.ConcurrentHashMap; - -import static org.hamcrest.CoreMatchers.equalTo; - -public class GuavaMiscUtilsTest { - @Test - public void whenHashingData_shouldReturnCorrectHashCode() throws Exception { - int receivedData = 123; - - HashCode hashCode = Hashing.crc32c().hashInt(receivedData); - Assert.assertThat(hashCode.toString(), equalTo("495be649")); - } - - @Test - public void whenDecrementingIpAddress_shouldReturnOneLessIpAddress() throws Exception { - InetAddress address = InetAddress.getByName("127.0.0.5"); - InetAddress decrementedAddress = InetAddresses.decrement(address); - - Assert.assertThat(decrementedAddress.toString(), equalTo("/127.0.0.4")); - } - - @Test - public void whenExecutingRunnableInThread_shouldLogThreadExecution() throws Exception { - ConcurrentHashMap threadExecutions = new ConcurrentHashMap<>(); - Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true); - - Thread t = new Thread(logThreadRun); - t.run(); - - Assert.assertTrue(threadExecutions.get("main")); - } -} diff --git a/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java b/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java new file mode 100644 index 0000000000..bd3a73c60f --- /dev/null +++ b/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.guava; + +import com.google.common.hash.HashCode; +import com.google.common.hash.Hashing; +import com.google.common.net.InetAddresses; +import org.junit.Assert; +import org.junit.Test; + +import java.net.InetAddress; +import java.util.concurrent.ConcurrentHashMap; + +import static org.hamcrest.CoreMatchers.equalTo; + +public class GuavaMiscUtilsUnitTest { + @Test + public void whenHashingData_shouldReturnCorrectHashCode() throws Exception { + int receivedData = 123; + + HashCode hashCode = Hashing.crc32c().hashInt(receivedData); + Assert.assertThat(hashCode.toString(), equalTo("495be649")); + } + + @Test + public void whenDecrementingIpAddress_shouldReturnOneLessIpAddress() throws Exception { + InetAddress address = InetAddress.getByName("127.0.0.5"); + InetAddress decrementedAddress = InetAddresses.decrement(address); + + Assert.assertThat(decrementedAddress.toString(), equalTo("/127.0.0.4")); + } + + @Test + public void whenExecutingRunnableInThread_shouldLogThreadExecution() throws Exception { + ConcurrentHashMap threadExecutions = new ConcurrentHashMap<>(); + Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true); + + Thread t = new Thread(logThreadRun); + t.run(); + + Assert.assertTrue(threadExecutions.get("main")); + } +} diff --git a/guava-modules/guava-19/pom.xml b/guava-modules/guava-19/pom.xml index 9eb20d5bbe..5dfb4d2cec 100644 --- a/guava-modules/guava-19/pom.xml +++ b/guava-modules/guava-19/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung guava-19 @@ -9,8 +9,8 @@ com.baeldung parent-java - 0.0.1-SNAPSHOT - ../../parent-java + 0.0.1-SNAPSHOT + ../../parent-java diff --git a/guava-modules/guava-19/src/main/resources/logback.xml b/guava-modules/guava-19/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/guava-modules/guava-19/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java b/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java deleted file mode 100644 index c7b8441b78..0000000000 --- a/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.baeldung.guava; - -import com.google.common.base.Throwables; -import com.google.common.collect.*; -import org.junit.Test; - -import java.util.Arrays; -import java.util.List; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; -import static org.hamcrest.core.AnyOf.anyOf; -import static org.junit.Assert.*; - -public class GuavaMiscUtilsTest { - - @Test - public void whenGettingLazyStackTrace_ListShouldBeReturned() throws Exception { - IllegalArgumentException e = new IllegalArgumentException("Some argument is incorrect"); - - List stackTraceElements = Throwables.lazyStackTrace(e); - - assertTrue(stackTraceElements.size() > 0); - } - - @Test - public void multisetShouldCountHitsOfMultipleDuplicateObjects() throws Exception { - List userNames = Arrays.asList("David", "Eugene", "Alex", "Alex", "David", "David", "David"); - - Multiset userNamesMultiset = HashMultiset.create(userNames); - - assertEquals(7, userNamesMultiset.size()); - assertEquals(4, userNamesMultiset.count("David")); - assertEquals(2, userNamesMultiset.count("Alex")); - assertEquals(1, userNamesMultiset.count("Eugene")); - assertThat(userNamesMultiset.elementSet(), anyOf(containsInAnyOrder("Alex", "David", "Eugene"))); - } - - @Test - public void whenAddingNewConnectedRange_RangesShouldBeMerged() throws Exception { - RangeSet rangeSet = TreeRangeSet.create(); - - rangeSet.add(Range.closed(1, 10)); - rangeSet.add(Range.closed(5, 15)); - rangeSet.add(Range.closedOpen(10, 17)); - - assertTrue(rangeSet.encloses(Range.closedOpen(1, 17))); - assertTrue(rangeSet.encloses(Range.closed(2, 3))); - assertTrue(rangeSet.contains(15)); - assertFalse(rangeSet.contains(17)); - assertEquals(1, rangeSet.asDescendingSetOfRanges().size()); - } - - @Test - public void cartesianProductShouldReturnAllPossibleCombinations() throws Exception { - List first = Lists.newArrayList("value1", "value2"); - List second = Lists.newArrayList("value3", "value4"); - - List> cartesianProduct = Lists.cartesianProduct(first, second); - - List pair1 = Lists.newArrayList("value2", "value3"); - List pair2 = Lists.newArrayList("value2", "value4"); - List pair3 = Lists.newArrayList("value1", "value3"); - List pair4 = Lists.newArrayList("value1", "value4"); - - assertThat(cartesianProduct, anyOf(containsInAnyOrder(pair1, pair2, pair3, pair4))); - } - - @Test - public void multisetShouldRemoveOccurrencesOfSpecifiedObjects() throws Exception { - Multiset multisetToModify = HashMultiset.create(); - Multiset occurrencesToRemove = HashMultiset.create(); - - multisetToModify.add("John"); - multisetToModify.add("Max"); - multisetToModify.add("Alex"); - - occurrencesToRemove.add("Alex"); - occurrencesToRemove.add("John"); - - Multisets.removeOccurrences(multisetToModify, occurrencesToRemove); - - assertEquals(1, multisetToModify.size()); - assertTrue(multisetToModify.contains("Max")); - assertFalse(multisetToModify.contains("John")); - assertFalse(multisetToModify.contains("Alex")); - } -} \ No newline at end of file diff --git a/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java b/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java new file mode 100644 index 0000000000..6f2d85bb04 --- /dev/null +++ b/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java @@ -0,0 +1,88 @@ +package com.baeldung.guava; + +import com.google.common.base.Throwables; +import com.google.common.collect.*; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; +import static org.hamcrest.core.AnyOf.anyOf; +import static org.junit.Assert.*; + +public class GuavaMiscUtilsUnitTest { + + @Test + public void whenGettingLazyStackTrace_ListShouldBeReturned() throws Exception { + IllegalArgumentException e = new IllegalArgumentException("Some argument is incorrect"); + + List stackTraceElements = Throwables.lazyStackTrace(e); + + assertTrue(stackTraceElements.size() > 0); + } + + @Test + public void multisetShouldCountHitsOfMultipleDuplicateObjects() throws Exception { + List userNames = Arrays.asList("David", "Eugene", "Alex", "Alex", "David", "David", "David"); + + Multiset userNamesMultiset = HashMultiset.create(userNames); + + assertEquals(7, userNamesMultiset.size()); + assertEquals(4, userNamesMultiset.count("David")); + assertEquals(2, userNamesMultiset.count("Alex")); + assertEquals(1, userNamesMultiset.count("Eugene")); + assertThat(userNamesMultiset.elementSet(), anyOf(containsInAnyOrder("Alex", "David", "Eugene"))); + } + + @Test + public void whenAddingNewConnectedRange_RangesShouldBeMerged() throws Exception { + RangeSet rangeSet = TreeRangeSet.create(); + + rangeSet.add(Range.closed(1, 10)); + rangeSet.add(Range.closed(5, 15)); + rangeSet.add(Range.closedOpen(10, 17)); + + assertTrue(rangeSet.encloses(Range.closedOpen(1, 17))); + assertTrue(rangeSet.encloses(Range.closed(2, 3))); + assertTrue(rangeSet.contains(15)); + assertFalse(rangeSet.contains(17)); + assertEquals(1, rangeSet.asDescendingSetOfRanges().size()); + } + + @Test + public void cartesianProductShouldReturnAllPossibleCombinations() throws Exception { + List first = Lists.newArrayList("value1", "value2"); + List second = Lists.newArrayList("value3", "value4"); + + List> cartesianProduct = Lists.cartesianProduct(first, second); + + List pair1 = Lists.newArrayList("value2", "value3"); + List pair2 = Lists.newArrayList("value2", "value4"); + List pair3 = Lists.newArrayList("value1", "value3"); + List pair4 = Lists.newArrayList("value1", "value4"); + + assertThat(cartesianProduct, anyOf(containsInAnyOrder(pair1, pair2, pair3, pair4))); + } + + @Test + public void multisetShouldRemoveOccurrencesOfSpecifiedObjects() throws Exception { + Multiset multisetToModify = HashMultiset.create(); + Multiset occurrencesToRemove = HashMultiset.create(); + + multisetToModify.add("John"); + multisetToModify.add("Max"); + multisetToModify.add("Alex"); + + occurrencesToRemove.add("Alex"); + occurrencesToRemove.add("John"); + + Multisets.removeOccurrences(multisetToModify, occurrencesToRemove); + + assertEquals(1, multisetToModify.size()); + assertTrue(multisetToModify.contains("Max")); + assertFalse(multisetToModify.contains("John")); + assertFalse(multisetToModify.contains("Alex")); + } +} \ No newline at end of file diff --git a/guava-modules/guava-21/pom.xml b/guava-modules/guava-21/pom.xml index 7038810d24..945b7c27c1 100644 --- a/guava-modules/guava-21/pom.xml +++ b/guava-modules/guava-21/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 guava-21 1.0-SNAPSHOT @@ -8,8 +8,8 @@ com.baeldung parent-java - 0.0.1-SNAPSHOT - ../../parent-java + 0.0.1-SNAPSHOT + ../../parent-java diff --git a/guava-modules/guava-21/src/main/resources/logback.xml b/guava-modules/guava-21/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/guava-modules/guava-21/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/guava-modules/guava-21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java b/guava-modules/guava-21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java deleted file mode 100644 index 866e09c6a0..0000000000 --- a/guava-modules/guava-21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.guava.zip; - -import com.google.common.collect.Streams; -import org.jooq.lambda.Seq; -import org.jooq.lambda.tuple.Tuple2; -import org.junit.Before; -import org.junit.Test; - -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import static org.junit.Assert.assertEquals; - -public class ZipCollectionTest { - - private List names; - private List ages; - private List expectedOutput; - - @Before - public void setUp() throws Exception { - names = Arrays.asList("John", "Jane", "Jack", "Dennis"); - ages = Arrays.asList(24, 25, 27); - expectedOutput = Arrays.asList("John:24", "Jane:25", "Jack:27"); - } - - @Test - public void zipCollectionUsingGuava21() { - List output = Streams - .zip(names.stream(), ages.stream(), (name, age) -> name + ":" + age) - .collect(Collectors.toList()); - - assertEquals(output, expectedOutput); - } - - @Test - public void zipCollectionUsingIntStream() { - List output = IntStream - .range(0, Math.min(names.size(), ages.size())) - .mapToObj(i -> names.get(i) + ":" + ages.get(i)) - .collect(Collectors.toList()); - - assertEquals(output, expectedOutput); - } - - @Test - public void zipCollectionUsingJool() { - Seq output = Seq - .of("John", "Jane", "Jack") - .zip(Seq.of(24, 25, 27), (x, y) -> x + ":" + y); - - assertEquals(output.toList(), expectedOutput); - } - - @Test - public void zipCollectionUsingJoolTuple() { - Seq> output = Seq - .of("John", "Jane", "Dennis") - .zip(Seq.of(24, 25, 27)); - - Tuple2 element1 = new Tuple2("John", 24); - Tuple2 element2 = new Tuple2("Jane", 25); - Tuple2 element3 = new Tuple2("Dennis", 27); - - List expectedOutput = Arrays.asList(element1, element2, element3); - assertEquals(output.collect(Collectors.toList()), expectedOutput); - } - - @Test - public void zipCollectionUsingJoolWithIndex() { - Seq> output = Seq - .of("John", "Jane", "Dennis") - .zipWithIndex(); - - Tuple2 element1 = new Tuple2<>("John", 0L); - Tuple2 element2 = new Tuple2<>("Jane", 1L); - Tuple2 element3 = new Tuple2<>("Dennis", 2L); - - List expectedOutput = Arrays.asList(element1, element2, element3); - assertEquals(output.collect(Collectors.toList()), expectedOutput); - } - -} \ No newline at end of file diff --git a/guava-modules/guava-21/src/test/java/com/baeldung/guava/zip/ZipCollectionUnitTest.java b/guava-modules/guava-21/src/test/java/com/baeldung/guava/zip/ZipCollectionUnitTest.java new file mode 100644 index 0000000000..e3d31d9404 --- /dev/null +++ b/guava-modules/guava-21/src/test/java/com/baeldung/guava/zip/ZipCollectionUnitTest.java @@ -0,0 +1,85 @@ +package com.baeldung.guava.zip; + +import com.google.common.collect.Streams; +import org.jooq.lambda.Seq; +import org.jooq.lambda.tuple.Tuple2; +import org.junit.Before; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.junit.Assert.assertEquals; + +public class ZipCollectionUnitTest { + + private List names; + private List ages; + private List expectedOutput; + + @Before + public void setUp() throws Exception { + names = Arrays.asList("John", "Jane", "Jack", "Dennis"); + ages = Arrays.asList(24, 25, 27); + expectedOutput = Arrays.asList("John:24", "Jane:25", "Jack:27"); + } + + @Test + public void zipCollectionUsingGuava21() { + List output = Streams + .zip(names.stream(), ages.stream(), (name, age) -> name + ":" + age) + .collect(Collectors.toList()); + + assertEquals(output, expectedOutput); + } + + @Test + public void zipCollectionUsingIntStream() { + List output = IntStream + .range(0, Math.min(names.size(), ages.size())) + .mapToObj(i -> names.get(i) + ":" + ages.get(i)) + .collect(Collectors.toList()); + + assertEquals(output, expectedOutput); + } + + @Test + public void zipCollectionUsingJool() { + Seq output = Seq + .of("John", "Jane", "Jack") + .zip(Seq.of(24, 25, 27), (x, y) -> x + ":" + y); + + assertEquals(output.toList(), expectedOutput); + } + + @Test + public void zipCollectionUsingJoolTuple() { + Seq> output = Seq + .of("John", "Jane", "Dennis") + .zip(Seq.of(24, 25, 27)); + + Tuple2 element1 = new Tuple2("John", 24); + Tuple2 element2 = new Tuple2("Jane", 25); + Tuple2 element3 = new Tuple2("Dennis", 27); + + List expectedOutput = Arrays.asList(element1, element2, element3); + assertEquals(output.collect(Collectors.toList()), expectedOutput); + } + + @Test + public void zipCollectionUsingJoolWithIndex() { + Seq> output = Seq + .of("John", "Jane", "Dennis") + .zipWithIndex(); + + Tuple2 element1 = new Tuple2<>("John", 0L); + Tuple2 element2 = new Tuple2<>("Jane", 1L); + Tuple2 element3 = new Tuple2<>("Dennis", 2L); + + List expectedOutput = Arrays.asList(element1, element2, element3); + assertEquals(output.collect(Collectors.toList()), expectedOutput); + } + +} \ No newline at end of file diff --git a/guava/README.md b/guava/README.md index bb4e225649..fe1a347d72 100644 --- a/guava/README.md +++ b/guava/README.md @@ -33,3 +33,4 @@ - [Using Guava CountingOutputStream](http://www.baeldung.com/guava-counting-outputstream) - [Hamcrest Text Matchers](http://www.baeldung.com/hamcrest-text-matchers) - [Quick Guide to the Guava RateLimiter](http://www.baeldung.com/guava-rate-limiter) +- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) diff --git a/guava/pom.xml b/guava/pom.xml index b36506f87a..60678608dd 100644 --- a/guava/pom.xml +++ b/guava/pom.xml @@ -1,5 +1,5 @@ + 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 guava @@ -9,8 +9,8 @@ com.baeldung parent-java - 0.0.1-SNAPSHOT - ../parent-java + 0.0.1-SNAPSHOT + ../parent-java diff --git a/guava/src/main/resources/logback.xml b/guava/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/guava/src/main/resources/logback.xml +++ b/guava/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/guava/src/test/java/org/baeldung/guava/BloomFilterTest.java b/guava/src/test/java/org/baeldung/guava/BloomFilterTest.java deleted file mode 100644 index d7c25b7c8d..0000000000 --- a/guava/src/test/java/org/baeldung/guava/BloomFilterTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.baeldung.guava; - - -import com.google.common.hash.BloomFilter; -import com.google.common.hash.Funnels; -import org.junit.Test; - -import java.util.stream.IntStream; - -import static org.assertj.core.api.Assertions.assertThat; - -public class BloomFilterTest { - - @Test - public void givenBloomFilter_whenAddNStringsToIt_thenShouldNotReturnAnyFalsePositive() { - //when - BloomFilter filter = BloomFilter.create( - Funnels.integerFunnel(), - 500, - 0.01); - - //when - filter.put(1); - filter.put(2); - filter.put(3); - - //then - // the probability that it returns true, but is actually false is 1% - assertThat(filter.mightContain(1)).isTrue(); - assertThat(filter.mightContain(2)).isTrue(); - assertThat(filter.mightContain(3)).isTrue(); - - assertThat(filter.mightContain(100)).isFalse(); - } - - @Test - public void givenBloomFilter_whenAddNStringsToItMoreThanDefinedExpectedInsertions_thenItWillReturnTrueForAlmostAllElements() { - //when - BloomFilter filter = BloomFilter.create( - Funnels.integerFunnel(), - 5, - 0.01); - - //when - IntStream.range(0, 100_000).forEach(filter::put); - - - //then - assertThat(filter.mightContain(1)).isTrue(); - assertThat(filter.mightContain(2)).isTrue(); - assertThat(filter.mightContain(3)).isTrue(); - assertThat(filter.mightContain(1_000_000)).isTrue(); - } -} diff --git a/guava/src/test/java/org/baeldung/guava/BloomFilterUnitTest.java b/guava/src/test/java/org/baeldung/guava/BloomFilterUnitTest.java new file mode 100644 index 0000000000..ff3031a0cb --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/BloomFilterUnitTest.java @@ -0,0 +1,54 @@ +package org.baeldung.guava; + + +import com.google.common.hash.BloomFilter; +import com.google.common.hash.Funnels; +import org.junit.Test; + +import java.util.stream.IntStream; + +import static org.assertj.core.api.Assertions.assertThat; + +public class BloomFilterUnitTest { + + @Test + public void givenBloomFilter_whenAddNStringsToIt_thenShouldNotReturnAnyFalsePositive() { + //when + BloomFilter filter = BloomFilter.create( + Funnels.integerFunnel(), + 500, + 0.01); + + //when + filter.put(1); + filter.put(2); + filter.put(3); + + //then + // the probability that it returns true, but is actually false is 1% + assertThat(filter.mightContain(1)).isTrue(); + assertThat(filter.mightContain(2)).isTrue(); + assertThat(filter.mightContain(3)).isTrue(); + + assertThat(filter.mightContain(100)).isFalse(); + } + + @Test + public void givenBloomFilter_whenAddNStringsToItMoreThanDefinedExpectedInsertions_thenItWillReturnTrueForAlmostAllElements() { + //when + BloomFilter filter = BloomFilter.create( + Funnels.integerFunnel(), + 5, + 0.01); + + //when + IntStream.range(0, 100_000).forEach(filter::put); + + + //then + assertThat(filter.mightContain(1)).isTrue(); + assertThat(filter.mightContain(2)).isTrue(); + assertThat(filter.mightContain(3)).isTrue(); + assertThat(filter.mightContain(1_000_000)).isTrue(); + } +} diff --git a/guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamTest.java b/guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamTest.java deleted file mode 100644 index 5e96f3597c..0000000000 --- a/guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.guava; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; - -import org.junit.Test; - -import com.google.common.io.CountingOutputStream; - -public class GuavaCountingOutputStreamTest { - public static final int MAX = 5; - - @Test(expected = RuntimeException.class) - public void givenData_whenCountReachesLimit_thenThrowException() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - CountingOutputStream cos = new CountingOutputStream(out); - - byte[] data = new byte[1024]; - ByteArrayInputStream in = new ByteArrayInputStream(data); - - int b; - while ((b = in.read()) != -1) { - cos.write(b); - if (cos.getCount() >= MAX) { - throw new RuntimeException("Write limit reached"); - } - } - } -} diff --git a/guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamUnitTest.java b/guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamUnitTest.java new file mode 100644 index 0000000000..7293b1631e --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamUnitTest.java @@ -0,0 +1,29 @@ +package org.baeldung.guava; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import org.junit.Test; + +import com.google.common.io.CountingOutputStream; + +public class GuavaCountingOutputStreamUnitTest { + public static final int MAX = 5; + + @Test(expected = RuntimeException.class) + public void givenData_whenCountReachesLimit_thenThrowException() throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + CountingOutputStream cos = new CountingOutputStream(out); + + byte[] data = new byte[1024]; + ByteArrayInputStream in = new ByteArrayInputStream(data); + + int b; + while ((b = in.read()) != -1) { + cos.write(b); + if (cos.getCount() >= MAX) { + throw new RuntimeException("Write limit reached"); + } + } + } +} diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java b/guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java new file mode 100644 index 0000000000..69a7505316 --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java @@ -0,0 +1,30 @@ +package org.baeldung.guava; + +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.*; + +import java.util.Map; +import org.junit.Test; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; + +public class GuavaMapInitializeUnitTest { + + @Test + public void givenKeyValuesShoudInitializeMap() { + Map articles = ImmutableMap.of("Title", "My New Article", "Title2", "Second Article"); + + assertThat(articles.get("Title"), equalTo("My New Article")); + assertThat(articles.get("Title2"), equalTo("Second Article")); + + } + + + @Test + public void givenKeyValuesShouldCreateMutableMap() { + Map articles = Maps.newHashMap(ImmutableMap.of("Title", "My New Article", "Title2", "Second Article")); + + assertThat(articles.get("Title"), equalTo("My New Article")); + assertThat(articles.get("Title2"), equalTo("Second Article")); + } +} diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMemoizerUnitTest.java b/guava/src/test/java/org/baeldung/guava/GuavaMemoizerUnitTest.java index 1f934347b4..8c37ecf07c 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaMemoizerUnitTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaMemoizerUnitTest.java @@ -73,7 +73,7 @@ public class GuavaMemoizerUnitTest { // then assertSupplierGetExecutionResultAndDuration(memoizedSupplier, expectedValue, 0D); // add one more second until memoized Supplier is evicted from memory - TimeUnit.SECONDS.sleep(1); + TimeUnit.SECONDS.sleep(3); assertSupplierGetExecutionResultAndDuration(memoizedSupplier, expectedValue, 2000D); } diff --git a/guava/src/test/java/org/baeldung/guava/GuavaStringUnitTest.java b/guava/src/test/java/org/baeldung/guava/GuavaStringUnitTest.java index 631ca454c0..a08efd7c31 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaStringUnitTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaStringUnitTest.java @@ -92,7 +92,7 @@ public class GuavaStringUnitTest { @Test public void whenSplitStringOnMultipleSeparator_thenSplit() { final String input = "apple.banana,,orange,,."; - final List result = Splitter.onPattern("[.|,]").omitEmptyStrings().splitToList(input); + final List result = Splitter.onPattern("[.,]").omitEmptyStrings().splitToList(input); assertThat(result, contains("apple", "banana", "orange")); } diff --git a/guest/core-java-9/pom.xml b/guest/core-java-9/pom.xml index f8e2dcce85..e9271b42ff 100644 --- a/guest/core-java-9/pom.xml +++ b/guest/core-java-9/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 com.stackify core-java-9 @@ -11,14 +12,6 @@ ../../ - - - junit - junit - ${junit.version} - - - diff --git a/guest/core-java-9/src/main/resources/logback.xml b/guest/core-java-9/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/guest/core-java-9/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/guest/core-java/pom.xml b/guest/core-java/pom.xml index b3c6ba9564..787dd764a1 100644 --- a/guest/core-java/pom.xml +++ b/guest/core-java/pom.xml @@ -13,34 +13,11 @@ - - junit - junit - ${junit.version} - org.apache.logging.log4j log4j-core ${log4j2.version} - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-all - ${org.hamcrest.version} - test - org.assertj assertj-core @@ -51,7 +28,6 @@ 2.8.2 - 1.3 3.6.1 diff --git a/guest/core-kotlin/.gitignore b/guest/core-kotlin/.gitignore new file mode 100644 index 0000000000..0c017e8f8c --- /dev/null +++ b/guest/core-kotlin/.gitignore @@ -0,0 +1,14 @@ +/bin/ + +#ignore gradle +.gradle/ + + +#ignore build and generated files +build/ +node/ +out/ + +#ignore installed node modules and package lock file +node_modules/ +package-lock.json diff --git a/guest/core-kotlin/pom.xml b/guest/core-kotlin/pom.xml new file mode 100644 index 0000000000..6b189143a4 --- /dev/null +++ b/guest/core-kotlin/pom.xml @@ -0,0 +1,199 @@ + + + 4.0.0 + core-kotlin + 1.0-SNAPSHOT + com.stackify + jar + + + + jcenter + http://jcenter.bintray.com + + + + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + org.jetbrains.kotlin + kotlin-stdlib + ${kotlin-stdlib.version} + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin-stdlib.version} + + + org.jetbrains.kotlin + kotlin-test-junit + ${kotlin-test-junit.version} + test + + + org.jetbrains.kotlin + kotlin-reflect + ${kotlin-reflect.version} + + + org.jetbrains.spek + spek-api + 1.1.5 + test + + + org.jetbrains.spek + spek-subject-extension + 1.1.5 + test + + + org.jetbrains.spek + spek-junit-platform-engine + 1.1.5 + test + + + com.nhaarman + mockito-kotlin + ${mockito-kotlin.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + + org.apache.maven.plugins + maven-failsafe-plugin + ${maven-failsafe-plugin.version} + test + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin-maven-plugin.version} + provided + + + + + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin-maven-plugin.version} + + + compile + + compile + + + + ${project.basedir}/src/main/kotlin + + + + + test-compile + + test-compile + + + + ${project.basedir}/src/test/kotlin + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + + + + + default-compile + none + + + + default-testCompile + none + + + java-compile + compile + + compile + + + + + + maven-failsafe-plugin + ${maven-failsafe-plugin.version} + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + + + + + junit5 + + integration-test + verify + + + + **/*Test5.java + + + + + + + + + + 2.22.0 + UTF-8 + 1.2.60 + 1.2.51 + 1.2.51 + 1.2.51 + 0.22.5 + 1.5.0 + 3.6.1 + 1.0.0 + 5.2.0 + 3.10.0 + 3.7.0 + + + diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/CompanionObjectTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/CompanionObjectTest.kt new file mode 100644 index 0000000000..69573fb75b --- /dev/null +++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/CompanionObjectTest.kt @@ -0,0 +1,21 @@ +package com.baeldung.kotlinvsjava + +import org.junit.Test +import kotlin.test.assertEquals + +class CompanionObjectTest { + + @Test + fun givenAClassWithCompanionObject_whenCallingMethodTheSameAsStaticOne_thenWeGetAResult() { + assertEquals("A", A.returnClassName()) + } + +} + +class A { + companion object { + fun returnClassName(): String { + return "A" + } + } +} \ No newline at end of file diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ConstructorTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ConstructorTest.kt new file mode 100644 index 0000000000..fdb5d05db5 --- /dev/null +++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ConstructorTest.kt @@ -0,0 +1,18 @@ +package com.baeldung.kotlinvsjava + +import org.junit.Test +import kotlin.test.assertEquals + +class ConstructorTests { + + @Test + fun givenAClassWithPrimaryConstructor_whenCreatingAnInstance_thenWeGetObject() { + var example = Example(1, "Example") + + assertEquals(1, example.id) + assertEquals("Example", example.name) + } + +} + +class Example constructor(val id: Int, var name: String) \ No newline at end of file diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DataClassTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DataClassTest.kt new file mode 100644 index 0000000000..ad79538d3c --- /dev/null +++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DataClassTest.kt @@ -0,0 +1,33 @@ +package com.baeldung.kotlinvsjava + +import org.junit.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse + +class DataClassTest { + + @Test + fun givenASampleDataClass_whenCallingToStringMethod_thenItReturnsAllProperties() { + val student = Student(1, "John", "Smith") + + assertEquals(1, student.id) + assertEquals("John", student.name) + assertEquals("Smith", student.lastName) + assertEquals("Student(id=1, name=John, lastName=Smith)", student.toString()) + } + + @Test + fun givenASampleDataClass_whenCreatingACopyWithGeneratedFunction_thenItReturnsACopyWithRequestedChanges() { + val student = Student(1, "John", "Smith") + val student2 = student.copy(id = 2, name = "Anne") + + assertEquals(2, student2.id) + assertEquals("Anne", student2.name) + assertEquals("Smith", student2.lastName) + assertEquals("Student(id=2, name=Anne, lastName=Smith)", student2.toString()) + assertFalse(student.equals(student2)) + } + +} + +data class Student(val id: Int, val name: String, val lastName: String) \ No newline at end of file diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DelegationTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DelegationTest.kt new file mode 100644 index 0000000000..2da824c2db --- /dev/null +++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DelegationTest.kt @@ -0,0 +1,27 @@ +package com.baeldung.kotlinvsjava + +import org.junit.Test +import kotlin.test.assertEquals + +class DelegationTest { + + @Test + fun givenAClassWithDelegation_whenCallDelegatedMethod_thenWeGetAResultDefinedInPassedObject() { + val car = Car(V6Engine()) + + assertEquals("Vroom", car.makeSound()) + } + +} + +interface Engine { + fun makeSound(): String +} + +class V6Engine: Engine { + override fun makeSound(): String { + return "Vroom" + } +} + +class Car(e: Engine) : Engine by e \ No newline at end of file diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExceptionsTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExceptionsTest.kt new file mode 100644 index 0000000000..073c4dd890 --- /dev/null +++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExceptionsTest.kt @@ -0,0 +1,34 @@ +package com.baeldung.kotlinvsjava + +import java.io.IOException +import kotlin.test.Test +import kotlin.test.assertEquals + +class ExceptionsTest { + + @Test + fun givenATryExpression_whenReturning5InLastExpressionOfTryBlock_thenWeGet5() { + val value: Int = try { 5 } catch (e: IOException) { 6 } + + assertEquals(5, value) + } + + @Test + fun givenATryExpression_whenReturning6InLastExpressionOfCatchBlock_thenWeGet6() { + val value: Int = try { funThrowingException() } catch (e: IOException) { 6 } + + assertEquals(6, value) + } + + @org.junit.Test(expected = IllegalArgumentException::class) + fun givenANullString_whenUsingElvisOperator_thenExceptionIsThrown() { + val sampleString: String? = null + + sampleString?.length ?: throw IllegalArgumentException("String must not be null") + } + + private fun funThrowingException(): Nothing { + throw IOException() + } + +} \ No newline at end of file diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExtensionFunctionsTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExtensionFunctionsTest.kt new file mode 100644 index 0000000000..3db73b6d2d --- /dev/null +++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExtensionFunctionsTest.kt @@ -0,0 +1,30 @@ +package com.baeldung.kotlinvsjava + +import org.junit.Test +import kotlin.test.assertEquals + +class ExtensionFunctionsTest { + + @Test + fun givenAStringWithAnExtensionFunction_whenCallingThatFunction_thenItConcatenatesStrings() { + val sampleString = "ABC" + val concatenatedString = sampleString.appendString("DEF") + + assertEquals("ABCDEF", concatenatedString) + } + + @Test + fun givenAStringWithAnExtensionProperty_whenReadingProperty_thenItReturnsLengthOfString() { + val sampleString = "ABC" + + assertEquals(3, sampleString.size) + } + + fun String.appendString(str : String): String { + return plus(str) + } + + val String.size: Int + get() = length + +} \ No newline at end of file diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/FunctionsTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/FunctionsTest.kt new file mode 100644 index 0000000000..6176478dfe --- /dev/null +++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/FunctionsTest.kt @@ -0,0 +1,70 @@ +package com.baeldung.kotlinvsjava + +import org.junit.Test +import kotlin.test.assertEquals + +class FunctionsTest { + + @Test + fun givenALambdaExpressionConcatenatingString_whenUsingTheFunctionWithAAndBString_thenWeGetAB() { + val concat: (String, String) -> String = { a, b -> a + b } + + assertEquals("AB", concat("A","B")) + } + + @Test + fun givenAnAnonymousFunctionConcatenatingString_whenUsingTheFunctionWithAAndBString_thenWeGetAB() { + val concat: (String, String) -> String = fun(a: String, b: String): String { return a + b } + + assertEquals("AB", concat("A","B")) + } + + @Test + fun givenAnPlusMethodOfString_whenUsingTheFunctionWithAAndBString_thenWeGetAB() { + val concat = String::plus + + assertEquals("AB", concat("A","B")) + } + + @Test + fun givenAStringConstractorAssignedToFunction_whenUsingFunctionReference_thenWeGetNewString() { + val concat = ::String + + assertEquals("A", concat().plus("A")) + } + + @Test + fun givenAClassImplementingAFunctionType_whenUsingTheFunctionWithAAndBString_thenWeGetAB() { + val concat = StringConcatenation() + + assertEquals("AB", concat("A", "B")) + } + + @Test + fun givenALambdaExpressionWithReceiver_whenUsingTheFunctionWithReceiver_thenWeGetABC() { + val concat: String.(String, String) -> String = { a, b -> plus(a).plus(b) } + + assertEquals("ABC", "A".concat("B", "C")) + } + + @Test + fun givenALambdaExpressionWithinLambdaExpression_whenUsingTheFunction_thenWeGetAB() { + val concat: (String) -> ((String) -> String) = { a -> {b -> a + b} } + + assertEquals("AB", (concat("A")("B"))) + } + + @Test + fun given3NestedLambdaExpression_whenUsingTheFunction_thenWeGetABC() { + val concat: (String) -> (String) -> (String) -> String = { a -> {b -> { c -> a + b + c} } } + + assertEquals("ABC", concat("A")("B")("C")) + } + +} + +class StringConcatenation: (String, String) -> String { + override fun invoke(p1: String, p2: String): String { + return p1 + p2 + } +} \ No newline at end of file diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/IsOperatorTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/IsOperatorTest.kt new file mode 100644 index 0000000000..1817602cdf --- /dev/null +++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/IsOperatorTest.kt @@ -0,0 +1,36 @@ +package com.baeldung.kotlinvsjava + +import org.junit.Test +import kotlin.math.absoluteValue +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class IsOperatorTest { + + @Test + fun givenSampleValue_whenUsingIsOperatorInIfStatement_thenItCastsAutomaticallyToString() { + val value: Any = "string" + + if(value is String) { + assertEquals(6, value.length) + } + } + + @Test + fun givenSampleValue_whenUsingIsOperatorWithAndOperator_thenItCastsAutomaticallyToString() { + val value: Any = "string" + + assertTrue(value is String && value.length == 6) + } + + @Test + fun givenSampleValue_whenUsingWithWhenOperator_thenItCastsAutomaticallyToString() { + val value: Any = "string" + + when(value) { + is String -> assertEquals(6, value.length) + is Int -> assertEquals(6, value.absoluteValue) + } + } + +} \ No newline at end of file diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/NullSafetyTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/NullSafetyTest.kt new file mode 100644 index 0000000000..8cb3cbc761 --- /dev/null +++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/NullSafetyTest.kt @@ -0,0 +1,67 @@ +package com.baeldung.kotlinvsjava + +import kotlin.test.Test +import java.lang.NullPointerException +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +class NullSafetyTest { + + @Test + fun givenStringAndNull_whenUsingSafeCallOperatorWithLengthMethod_thenReturnsLengthForStringAndNullForNull() { + val stringValue: String? = "string" + val nullValue: String? = null + + assertNotNull(stringValue?.length) + assertNull(nullValue?.length) + } + + @Test(expected = NullPointerException::class) + fun givenNullReference_whenUsingTheNotNullAssertionOperator_thenItThrowsNullPointerException() { + val stringValue: String? = "string" + val nullValue: String? = null + + assertNotNull(stringValue!!.length) + nullValue!!.length + } + + @Test + fun givenStringAndNull_whenUsingElvisOperator_thenItTestsAgainstNullAndReturnsTheProperValue() { + val stringValue: String? = "string" + val nullValue: String? = null + + val shouldBeLength: Int = stringValue?.length ?: -1 + val souldBeMinusOne: Int = nullValue?.length ?: -1 + + assertEquals(6, shouldBeLength) + assertEquals(-1, souldBeMinusOne) + } + + @Test + fun givenString_whenCastingToInt_thenItReturnsNull() { + val stringValue: String? = "string" + + val intValue: Int? = stringValue as? Int + + assertNull(intValue) + } + + @Test + fun givenCollectionWithNulls_whenFilterNonNull_thenItReturnsCollectionWithoutNulls() { + val list: List = listOf("a", "b", null) + val nonNullList = list.filterNotNull() + + assertEquals(2, nonNullList.size) + assertEquals(nonNullList, listOf("a", "b")) + } + + @Test + fun givenCollectionWithNulls_whenLetWithSafeCallOperator_thenItOmitsNulls() { + val list: List = listOf("a", "b", null) + for(elem in list) { + elem?.let { assertNotNull(it) } + } + } + +} \ No newline at end of file diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/OperatorsOverloadingTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/OperatorsOverloadingTest.kt new file mode 100644 index 0000000000..a28008da20 --- /dev/null +++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/OperatorsOverloadingTest.kt @@ -0,0 +1,61 @@ +package com.baeldung.kotlinvsjava + +import org.junit.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class OperatorsOverloadingTest { + + @Test + fun givenThePlaneClassWithOverloadedIncrementationOperator_whenCallingTheOperator_thenItIncreasesSpeed(){ + var plane = Plane(0.0) + + plane++ + assertEquals(50.0, plane.currentSpeed) + } + + @Test + fun givenThePlaneClassWithOverloadedMinusOperator_whenCallingTheOperator_thenItDecreaseSpeed(){ + var plane = Plane(1000.0) + + plane - 500.0 + assertEquals(500.0, plane.currentSpeed) + } + + @Test + fun givenThePlaneClassWithOverloadedInvokeOperator_whenCallingTheOperator_thenItSetSpeed(){ + var plane = Plane(0.0) + + plane(150.0) + assertEquals(150.0, plane.currentSpeed) + } + + @Test + fun given2PlaneObjectWithOverloadedComparisonOperator_whenCallingTheOperator_thenItComparesSpeedValues(){ + var plane = Plane(0.0) + var plane2 = Plane(150.0) + + assertTrue(plane < (plane2)) + } + +} + +class Plane(var currentSpeed: Double) { + + operator fun inc(): Plane { + currentSpeed += 50.0 + return this + } + + operator fun minus(number: Double) { + currentSpeed = if(currentSpeed < number) 0.0 else currentSpeed - number + } + + operator fun invoke(speed: Double) { + currentSpeed = speed + } + + operator fun compareTo(plane: Plane): Int { + return currentSpeed.compareTo(plane.currentSpeed) + } +} \ No newline at end of file diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/PropertiesTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/PropertiesTest.kt new file mode 100644 index 0000000000..95abcd68a2 --- /dev/null +++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/PropertiesTest.kt @@ -0,0 +1,32 @@ +package com.baeldung.kotlinvsjava + +import org.junit.Test +import java.math.BigDecimal +import kotlin.test.assertEquals + +class PropertiesTest { + + @Test + fun givenASampleClassWithValAndVarProperties_whenSettingPrice_thenWeGetZeroOrOne() { + val product = Product() + product.price = BigDecimal(10) + + val product2 = Product() + product2.price = null + + assertEquals("empty", product.id) + assertEquals("empty", product2.id) + assertEquals(BigDecimal(10), product.price) + assertEquals(BigDecimal(1), product2.price) + } + +} + +class Product { + + val id: String? = "empty" + + var price: BigDecimal? = BigDecimal.ZERO + set(value) = if(value == null) { field = BigDecimal.ONE} else { field = value } + +} \ No newline at end of file diff --git a/guest/deep-jsf/pom.xml b/guest/deep-jsf/pom.xml index bd02b145d0..e09b5e0606 100644 --- a/guest/deep-jsf/pom.xml +++ b/guest/deep-jsf/pom.xml @@ -1,27 +1,24 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.stackify deep-jsf 0.0.1-SNAPSHOT war + com.baeldung parent-modules 1.0.0-SNAPSHOT ../../ - - false - - + javax javaee-api - 7.0 + ${javaee-api.version} provided @@ -31,4 +28,9 @@ deep-jsf + + false + 7.0 + + \ No newline at end of file diff --git a/guest/deep-jsf/src/main/resources/logback.xml b/guest/deep-jsf/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/guest/deep-jsf/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/guest/junit5-example/pom.xml b/guest/junit5-example/pom.xml index 93ce207940..457fb1fcaa 100644 --- a/guest/junit5-example/pom.xml +++ b/guest/junit5-example/pom.xml @@ -1,52 +1,50 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 junit5-example junit5-example 0.0.1-SNAPSHOT + com.baeldung parent-modules 1.0.0-SNAPSHOT ../../ + org.junit.jupiter junit-jupiter-params - 5.0.0-M4 + ${junit.jupiter.version} - org.junit.vintage junit-vintage-engine - 4.12.0-M4 + ${junit-vintage.version} - com.h2database h2 - 1.4.195 + ${h2.version} - org.apache.logging.log4j log4j-core - 2.8.2 + ${log4j-core.version} - maven-surefire-plugin - 2.19.1 + ${maven-surefire-plugin.version} org.junit.platform junit-platform-surefire-provider - 1.0.0-M4 + ${junit-platform-surefire-provider.version} @@ -57,8 +55,12 @@ - + - + 5.0.0-M4 + 4.12.0-M4 + 1.4.195 + 2.8.2 + 1.0.0-M4 \ No newline at end of file diff --git a/guest/log4j2-example/pom.xml b/guest/log4j2-example/pom.xml index 760af88a06..f64869879f 100644 --- a/guest/log4j2-example/pom.xml +++ b/guest/log4j2-example/pom.xml @@ -1,15 +1,17 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 log4j2-example log4j2-example 0.0.1-SNAPSHOT + com.baeldung parent-modules 1.0.0-SNAPSHOT ../../ + @@ -24,12 +26,6 @@ jackson-databind ${jackson.version} - - - junit - junit - 4.12 - diff --git a/guest/logback-example/pom.xml b/guest/logback-example/pom.xml index d913db26bd..04de6a00a2 100644 --- a/guest/logback-example/pom.xml +++ b/guest/logback-example/pom.xml @@ -4,29 +4,23 @@ com.stackify logback-example 0.0.1-SNAPSHOT + com.baeldung parent-modules 1.0.0-SNAPSHOT ../../ + - - ch.qos.logback - logback-classic - 1.2.3 - - - - junit - junit - 4.12 - - org.codehaus.janino janino - 3.0.7 + ${janino.version} + + + 3.0.7 + \ No newline at end of file diff --git a/guest/memory-leaks/pom.xml b/guest/memory-leaks/pom.xml index 0bb201dd2f..956ae9c408 100644 --- a/guest/memory-leaks/pom.xml +++ b/guest/memory-leaks/pom.xml @@ -1,5 +1,5 @@ + 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 memory-leaks @@ -12,14 +12,6 @@ ../../ - - - junit - junit - ${junit.version} - - - diff --git a/guest/remote-debugging/pom.xml b/guest/remote-debugging/pom.xml index 6e077fce56..974421de97 100644 --- a/guest/remote-debugging/pom.xml +++ b/guest/remote-debugging/pom.xml @@ -1,17 +1,18 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.stackify - java-remote-debugging + remote-debugging 0.0.1-SNAPSHOT war + remote-debugging org.springframework.boot spring-boot-starter-parent - ${spring-boot-starter-parent.version} - + 1.5.8.RELEASE + @@ -38,7 +39,6 @@ UTF-8 UTF-8 - 1.5.8.RELEASE diff --git a/guest/remote-debugging/src/main/resources/logback.xml b/guest/remote-debugging/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/guest/remote-debugging/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF b/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF index 254272e1c0..e3c07ab38a 100644 --- a/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF +++ b/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF @@ -1,3 +1,2 @@ Manifest-Version: 1.0 Class-Path: - diff --git a/guest/spring-boot-app/docker/Dockerfile b/guest/spring-boot-app/docker/Dockerfile new file mode 100644 index 0000000000..211e8927a3 --- /dev/null +++ b/guest/spring-boot-app/docker/Dockerfile @@ -0,0 +1,16 @@ +# Alpine Linux with OpenJDK JRE +FROM openjdk:8-jre-alpine +RUN apk add --no-cache bash + +# copy fat WAR +COPY spring-boot-app-0.0.1-SNAPSHOT.war /app.war + +# copy fat WAR +COPY logback.xml /logback.xml + +COPY run.sh /run.sh + +# runs application +#CMD ["/usr/bin/java", "-jar", "-Dspring.profiles.active=default", "-Dlogging.config=/logback.xml", "/app.war"] + +ENTRYPOINT ["/run.sh"] diff --git a/guest/spring-boot-app/docker/logback.xml b/guest/spring-boot-app/docker/logback.xml new file mode 100644 index 0000000000..7e03ddc827 --- /dev/null +++ b/guest/spring-boot-app/docker/logback.xml @@ -0,0 +1,15 @@ + + + + + /var/log/Application/application.log + true + + %-7d{yyyy-MM-dd HH:mm:ss:SSS} %m%n + + + + + + + diff --git a/guest/spring-boot-app/docker/run.sh b/guest/spring-boot-app/docker/run.sh new file mode 100755 index 0000000000..aeecc29371 --- /dev/null +++ b/guest/spring-boot-app/docker/run.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +java -Dspring.profiles.active=$1 -Dlogging.config=/logback.xml -jar /app.war + diff --git a/guest/spring-boot-app/pom.xml b/guest/spring-boot-app/pom.xml index ba57bbd5c5..7daa8f668e 100644 --- a/guest/spring-boot-app/pom.xml +++ b/guest/spring-boot-app/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 spring-boot-app spring-boot-app @@ -38,24 +39,36 @@ maven-compiler-plugin - 3.7.0 - - 1.8 - 1.8 - maven-war-plugin - 3.1.0 WebContent + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + com.stackify.Application + ${project.basedir}/docker + + + + + 8.0.43 + UTF-8 + 1.8 - \ No newline at end of file + diff --git a/guest/spring-boot-app/src/main/resources/logback.xml b/guest/spring-boot-app/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/guest/spring-boot-app/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/guest/spring-mvc/pom.xml b/guest/spring-mvc/pom.xml index 169b216ff9..42543b5be0 100644 --- a/guest/spring-mvc/pom.xml +++ b/guest/spring-mvc/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.stackify.guest spring-mvc @@ -12,8 +12,8 @@ org.springframework.boot spring-boot-starter-parent - ${spring-boot-starter-parent.version} - + 2.0.0.M5 + @@ -27,32 +27,9 @@
- - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - UTF-8 UTF-8 - 2.0.0.M5 diff --git a/guest/spring-mvc/src/main/resources/logback.xml b/guest/spring-mvc/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/guest/spring-mvc/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/guest/spring-security/pom.xml b/guest/spring-security/pom.xml index 16e946d108..baca3bce85 100644 --- a/guest/spring-security/pom.xml +++ b/guest/spring-security/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.stackify.guest spring-security @@ -12,8 +11,8 @@ org.springframework.boot spring-boot-starter-parent - ${spring-boot-starter-parent.version} - + 2.0.0.M6 + @@ -45,33 +44,10 @@ - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - UTF-8 UTF-8 3.0.8.RELEASE - 2.0.0.M6 \ No newline at end of file diff --git a/guest/spring-security/src/main/resources/logback.xml b/guest/spring-security/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/guest/spring-security/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/guest/thread-pools/pom.xml b/guest/thread-pools/pom.xml index 56173b1285..db9a5ac89f 100644 --- a/guest/thread-pools/pom.xml +++ b/guest/thread-pools/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.stackify thread-pools @@ -12,16 +12,4 @@ ../../ - - - ch.qos.logback - logback-classic - ${logback-classic.version} - - - - - 1.2.3 - - \ No newline at end of file diff --git a/guest/thread-pools/src/main/resources/logback.xml b/guest/thread-pools/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/guest/thread-pools/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/guest/tomcat-app/pom.xml b/guest/tomcat-app/pom.xml index f3447b08c3..7fd27e869b 100644 --- a/guest/tomcat-app/pom.xml +++ b/guest/tomcat-app/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.stackify tomcat-app @@ -29,15 +29,11 @@ rest-assured ${rest-assured.version} - - junit - junit - ${junit.version} - com.h2database h2 ${h2database.version} + runtime org.apache.logging.log4j @@ -55,7 +51,7 @@ maven-war-plugin - 3.0.0 + ${maven-war-plugin.version} WebContent @@ -64,13 +60,13 @@ - 1.2.3 2.25.1 1.4.195 3.0.3 2.8.2 1.69.0 2.25.1 + 3.0.0 \ No newline at end of file diff --git a/guest/tomcat-app/src/main/resources/logback.xml b/guest/tomcat-app/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/guest/tomcat-app/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/guest/webservices/rest-client/pom.xml b/guest/webservices/rest-client/pom.xml index 84f4eaf3c0..5e52b7161c 100644 --- a/guest/webservices/rest-client/pom.xml +++ b/guest/webservices/rest-client/pom.xml @@ -25,8 +25,4 @@ - - 2.6 - - \ No newline at end of file diff --git a/guest/webservices/rest-server/pom.xml b/guest/webservices/rest-server/pom.xml index 955afdd82c..4b3d241293 100644 --- a/guest/webservices/rest-server/pom.xml +++ b/guest/webservices/rest-server/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.stackify rest-server @@ -29,11 +29,6 @@ rest-assured ${rest-assured.version} - - junit - junit - ${junit.version} - @@ -49,7 +44,6 @@ - 3.0.0 2.25.1 3.0.3 2.25.1 diff --git a/guest/webservices/rest-server/src/main/resources/logback.xml b/guest/webservices/rest-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/guest/webservices/rest-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/guest/webservices/soap_client/src/main/resources/logback.xml b/guest/webservices/soap_client/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/guest/webservices/soap_client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/guest/webservices/soap_example/src/main/resources/logback.xml b/guest/webservices/soap_example/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/guest/webservices/soap_example/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/guest/webservices/spring-rest-service/pom.xml b/guest/webservices/spring-rest-service/pom.xml index 74b76ee725..49d35766e8 100644 --- a/guest/webservices/spring-rest-service/pom.xml +++ b/guest/webservices/spring-rest-service/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.stackify spring-rest-service @@ -9,7 +9,7 @@ org.springframework.boot spring-boot-starter-parent - ${spring-boot-starter-parent.version} + 1.5.4.RELEASE @@ -38,10 +38,6 @@ org.springframework.boot spring-boot-maven-plugin - - ${maven.compiler.source} - ${maven.compiler.target} - @@ -49,11 +45,9 @@ UTF-8 UTF-8 - 1.5.4.RELEASE + 1.8 2.7.0 2.7.0 - 1.8 - 1.8 \ No newline at end of file diff --git a/guest/webservices/spring-rest-service/src/main/resources/logback.xml b/guest/webservices/spring-rest-service/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/guest/webservices/spring-rest-service/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/guice/pom.xml b/guice/pom.xml index ba0ed39c4a..f3e7873245 100644 --- a/guice/pom.xml +++ b/guice/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.examples.guice guice @@ -23,7 +23,6 @@ - UTF-8 4.1.0 diff --git a/guice/src/main/resources/logback.xml b/guice/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/guice/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/handling-spring-static-resources/pom.xml b/handling-spring-static-resources/pom.xml deleted file mode 100644 index da8f88ee22..0000000000 --- a/handling-spring-static-resources/pom.xml +++ /dev/null @@ -1,214 +0,0 @@ - - - 4.0.0 - com.baeldung - spring-static-resources - 0.1.0-SNAPSHOT - war - spring-static-resources - - - com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring - - - - - - org.springframework.security - spring-security-web - ${org.springframework.security.version} - - - org.springframework.security - spring-security-config - ${org.springframework.security.version} - - - org.springframework.security - spring-security-taglibs - ${org.springframework.security.version} - - - - - org.springframework - spring-core - ${org.springframework.version} - - - commons-logging - commons-logging - - - - - org.springframework - spring-context - ${org.springframework.version} - - - org.springframework - spring-jdbc - ${org.springframework.version} - - - org.springframework - spring-beans - ${org.springframework.version} - - - org.springframework - spring-aop - ${org.springframework.version} - - - org.springframework - spring-tx - ${org.springframework.version} - - - org.springframework - spring-expression - ${org.springframework.version} - - - - org.springframework - spring-web - ${org.springframework.version} - - - org.springframework - spring-webmvc - ${org.springframework.version} - - - - - org.aspectj - aspectjrt - ${org.aspectj-version} - - - javax.inject - javax.inject - ${inject.version} - - - - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - - - javax.servlet.jsp - javax.servlet.jsp-api - ${javax.servlet.jsp-api.version} - - - javax.servlet - jstl - ${jstl.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - - org.hibernate - hibernate-validator - ${hibernate-validator.version} - - - - - joda-time - joda-time - ${joda-time.version} - - - - - com.github.jknack - handlebars - ${handlebars.version} - - - - - - spring-static-resources - - - src/main/resources - true - - - - - net.alchim31.maven - yuicompressor-maven-plugin - ${yuicompressor-maven-plugin.version} - - - - compress - - - - - true - ${project.build.directory}/min - - **/*.min.js - **/handlebars-3133af2.js - **/require.js - - - - - maven-war-plugin - - - - ${project.build.directory}/min - - - - - - - - - 1.8 - - - 4.3.4.RELEASE - 4.2.0.RELEASE - - 1.8.9 - 2.3.2-b02 - - - 2.8.5 - - - 5.3.3.Final - 4.0.6 - 2.9.6 - 1.2 - 3.1.0 - 1 - - - 1.5.1 - - - \ No newline at end of file diff --git a/handling-spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java b/handling-spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java deleted file mode 100644 index 4a198cf195..0000000000 --- a/handling-spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.baeldung.spring; - -import java.util.Locale; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.MessageSource; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.support.ReloadableResourceBundleMessageSource; -import org.springframework.core.env.Environment; -import org.springframework.web.servlet.LocaleResolver; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.i18n.CookieLocaleResolver; -import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; -import org.springframework.web.servlet.resource.GzipResourceResolver; -import org.springframework.web.servlet.resource.PathResourceResolver; -import org.springframework.web.servlet.resource.ResourceUrlEncodingFilter; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; - -@Configuration -@ComponentScan(basePackages = { "org.baeldung.web.controller", "org.baeldung.persistence.service", "org.baeldung.persistence.dao" }) -@EnableWebMvc -public class MvcConfig extends WebMvcConfigurerAdapter { - @Autowired - Environment env; - - public MvcConfig() { - super(); - } - - // API - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/login.html"); - registry.addViewController("/home.html"); - - } - - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - return bean; - } - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - // For examples using Spring 4.1.0 - if ((env.getProperty("resource.handler.conf")).equals("4.1.0")) { - registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(3600).resourceChain(true).addResolver(new GzipResourceResolver()).addResolver(new PathResourceResolver()); - registry.addResourceHandler("/resources/**").addResourceLocations("/resources/", "classpath:/other-resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver()); - registry.addResourceHandler("/files/**").addResourceLocations("file:/Users/Elena/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver()); - registry.addResourceHandler("/other-files/**").addResourceLocations("file:/Users/Elena/").setCachePeriod(3600).resourceChain(true).addResolver(new GzipResourceResolver()); - } - // For examples using Spring 4.0.7 - else if ((env.getProperty("resource.handler.conf")).equals("4.0.7")) { - registry.addResourceHandler("/resources/**").addResourceLocations("/", "/resources/", "classpath:/other-resources/"); - registry.addResourceHandler("/files/**").addResourceLocations("file:/Users/Elena/"); - - } - } - - @Override - public void addInterceptors(InterceptorRegistry registry) { - LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); - localeChangeInterceptor.setParamName("lang"); - registry.addInterceptor(localeChangeInterceptor); - } - - @Bean - public ResourceUrlEncodingFilter resourceUrlEncodingFilter() { - ResourceUrlEncodingFilter filter = new ResourceUrlEncodingFilter(); - - return filter; - } - - @Bean - public LocaleResolver localeResolver() { - CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver(); - cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH); - return cookieLocaleResolver; - } - - @Bean - public MessageSource messageSource() { - ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); - messageSource.setBasename("classpath:messages"); - messageSource.setUseCodeAsDefaultMessage(true); - messageSource.setDefaultEncoding("UTF-8"); - messageSource.setCacheSeconds(0); - return messageSource; - } - -} \ No newline at end of file diff --git a/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml b/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml deleted file mode 100644 index cf944804db..0000000000 --- a/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml b/handling-spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml deleted file mode 100644 index 94bd63e068..0000000000 --- a/handling-spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - \ No newline at end of file diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/web.xml b/handling-spring-static-resources/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index e9d784e940..0000000000 --- a/handling-spring-static-resources/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - - contextClass - - org.springframework.web.context.support.AnnotationConfigWebApplicationContext - - - - contextConfigLocation - org.baeldung.spring - - - - org.springframework.web.context.ContextLoaderListener - - - - mvc - org.springframework.web.servlet.DispatcherServlet - 1 - - - mvc - / - - - - springSecurityFilterChain - org.springframework.web.filter.DelegatingFilterProxy - - - springSecurityFilterChain - /* - - - localizationFilter - org.springframework.web.filter.RequestContextFilter - - - localizationFilter - /* - - - \ No newline at end of file diff --git a/hazelcast/README.md b/hazelcast/README.md index b90f66a8d0..7adb13f2af 100644 --- a/hazelcast/README.md +++ b/hazelcast/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: - [Guide to Hazelcast with Java](http://www.baeldung.com/java-hazelcast) +- [Introduction to Hazelcast Jet](https://www.baeldung.com/hazelcast-jet) diff --git a/hazelcast/pom.xml b/hazelcast/pom.xml index aa7faa07cf..705792ad05 100644 --- a/hazelcast/pom.xml +++ b/hazelcast/pom.xml @@ -1,5 +1,5 @@ + 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 hazelcast @@ -13,16 +13,12 @@ - - com.hazelcast - hazelcast - ${hazelcast.version} - - - com.hazelcast - hazelcast-client - ${hazelcast.version} - + + + com.hazelcast.jet + hazelcast-jet + ${hazelcast.jet.version} + @@ -36,8 +32,8 @@ - - 3.8.4 + + 0.6 \ No newline at end of file diff --git a/hazelcast/src/main/java/com/baeldung/hazelcast/jet/WordCounter.java b/hazelcast/src/main/java/com/baeldung/hazelcast/jet/WordCounter.java new file mode 100644 index 0000000000..971986bcae --- /dev/null +++ b/hazelcast/src/main/java/com/baeldung/hazelcast/jet/WordCounter.java @@ -0,0 +1,51 @@ +package com.baeldung.hazelcast.jet; + +import java.util.List; +import java.util.Map; + +import static com.hazelcast.jet.Traversers.traverseArray; +import static com.hazelcast.jet.aggregate.AggregateOperations.counting; +import static com.hazelcast.jet.function.DistributedFunctions.wholeItem; + +import com.hazelcast.jet.Jet; +import com.hazelcast.jet.JetInstance; +import com.hazelcast.jet.pipeline.Pipeline; +import com.hazelcast.jet.pipeline.Sinks; +import com.hazelcast.jet.pipeline.Sources; + +public class WordCounter { + + private static final String LIST_NAME = "textList"; + + private static final String MAP_NAME = "countMap"; + + private Pipeline createPipeLine() { + Pipeline p = Pipeline.create(); + p.drawFrom(Sources. list(LIST_NAME)) + .flatMap(word -> traverseArray(word.toLowerCase() + .split("\\W+"))) + .filter(word -> !word.isEmpty()) + .groupingKey(wholeItem()) + .aggregate(counting()) + .drainTo(Sinks.map(MAP_NAME)); + return p; + } + + public Long countWord(List sentences, String word) { + long count = 0; + JetInstance jet = Jet.newJetInstance(); + try { + List textList = jet.getList(LIST_NAME); + textList.addAll(sentences); + Pipeline p = createPipeLine(); + jet.newJob(p) + .join(); + Map counts = jet.getMap(MAP_NAME); + count = counts.get(word); + } finally { + Jet.shutdownAll(); + } + return count; + } + +} diff --git a/hazelcast/src/main/resources/logback.xml b/hazelcast/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/hazelcast/src/main/resources/logback.xml +++ b/hazelcast/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/hazelcast/src/test/java/com/baeldung/hazelcast/jet/WordCounterUnitTest.java b/hazelcast/src/test/java/com/baeldung/hazelcast/jet/WordCounterUnitTest.java new file mode 100644 index 0000000000..95596b3860 --- /dev/null +++ b/hazelcast/src/test/java/com/baeldung/hazelcast/jet/WordCounterUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.hazelcast.jet; + +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +public class WordCounterUnitTest { + + @Test + public void whenGivenSentencesAndWord_ThenReturnCountOfWord() { + List sentences = new ArrayList<>(); + sentences.add("The first second was alright, but the second second was tough."); + WordCounter wordCounter = new WordCounter(); + long countSecond = wordCounter.countWord(sentences, "second"); + assertTrue(countSecond == 3); + } + +} diff --git a/hbase/pom.xml b/hbase/pom.xml index ff4aa15130..117cf72e30 100644 --- a/hbase/pom.xml +++ b/hbase/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 hbase diff --git a/hbase/src/main/resources/logback.xml b/hbase/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/hbase/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/hibernate5/README.md b/hibernate5/README.md index fb1319ed57..8f2f8eb469 100644 --- a/hibernate5/README.md +++ b/hibernate5/README.md @@ -10,3 +10,7 @@ - [JPA Attribute Converters](http://www.baeldung.com/jpa-attribute-converters) - [Mapping LOB Data in Hibernate](http://www.baeldung.com/hibernate-lob) - [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable) +- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking) +- [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa) +- [Optimistic Locking in JPA](http://www.baeldung.com/jpa-optimistic-locking) +- [Hibernate Entity Lifecycle](https://www.baeldung.com/hibernate-entity-lifecycle) diff --git a/hibernate5/pom.xml b/hibernate5/pom.xml index 6ed13b8ae4..610c893bdc 100644 --- a/hibernate5/pom.xml +++ b/hibernate5/pom.xml @@ -1,13 +1,10 @@ - + 4.0.0 com.baeldung hibernate5 0.0.1-SNAPSHOT - hibernate5 - http://maven.apache.org com.baeldung @@ -21,11 +18,6 @@ hibernate-core ${hibernate.version} - - junit - junit - ${junit.version} - org.assertj assertj-core @@ -65,10 +57,7 @@ - UTF-8 - - 3.7.0 - 5.2.12.Final + 5.3.2.Final 6.0.6 2.2.3 1.4.196 diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 849d271cd4..2212e736ab 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -6,6 +6,15 @@ import java.net.URL; import java.util.Properties; import com.baeldung.hibernate.entities.DeptEmployee; +import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse; +import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent; +import com.baeldung.hibernate.pessimisticlocking.Individual; +import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse; +import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee; +import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingStudent; +import com.baeldung.hibernate.pojo.*; +import com.baeldung.hibernate.pojo.Person; +import com.baeldung.hibernate.pojo.inheritance.*; import org.apache.commons.lang3.StringUtils; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; @@ -13,10 +22,6 @@ import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.service.ServiceRegistry; -import com.baeldung.hibernate.pessimisticlocking.Individual; -import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse; -import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee; -import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingStudent; import com.baeldung.hibernate.pojo.Course; import com.baeldung.hibernate.pojo.Employee; import com.baeldung.hibernate.pojo.EntityDescription; @@ -95,6 +100,8 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class); metadataSources.addAnnotatedClass(DeptEmployee.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); + metadataSources.addAnnotatedClass(OptimisticLockingCourse.class); + metadataSources.addAnnotatedClass(OptimisticLockingStudent.class); Metadata metadata = metadataSources.buildMetadata(); return metadata.getSessionFactoryBuilder() diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java new file mode 100644 index 0000000000..8b0a51858d --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.joincolumn; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Address { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(name = "ZIP") + private String zipCode; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getZipCode() { + return zipCode; + } + + public void setZipCode(String zipCode) { + this.zipCode = zipCode; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java new file mode 100644 index 0000000000..a91fb3b4c9 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.joincolumn; + +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.ManyToOne; + +@Entity +public class Email { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String address; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "employee_id") + private Employee employee; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java new file mode 100644 index 0000000000..3fbdb3820e --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java @@ -0,0 +1,36 @@ +package com.baeldung.hibernate.joincolumn; + +import java.util.List; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @OneToMany(fetch = FetchType.LAZY, mappedBy = "employee") + private List emails; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public List getEmails() { + return emails; + } + + public void setEmails(List emails) { + this.emails = emails; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java new file mode 100644 index 0000000000..e5b9dc06bc --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java @@ -0,0 +1,41 @@ +package com.baeldung.hibernate.joincolumn; + +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.JoinColumns; +import javax.persistence.ManyToOne; + +@Entity +public class Office { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumns({ + @JoinColumn(name="ADDR_ID", referencedColumnName="ID"), + @JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP") + }) + private Address address; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java new file mode 100644 index 0000000000..f7b8e6bf6d --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.jpabootstrap.application; + +import com.baeldung.hibernate.jpabootstrap.config.JpaEntityManagerFactory; +import com.baeldung.hibernate.jpabootstrap.entities.User; +import javax.persistence.EntityManager; + +public class Application { + + public static void main(String[] args) { + EntityManager entityManager = getJpaEntityManager(); + User user = entityManager.find(User.class, 1); + System.out.println(user); + entityManager.getTransaction().begin(); + user.setName("John"); + user.setEmail("john@domain.com"); + entityManager.merge(user); + entityManager.getTransaction().commit(); + entityManager.getTransaction().begin(); + entityManager.persist(new User("Monica", "monica@domain.com")); + entityManager.getTransaction().commit(); + + // additional CRUD operations + + } + + private static class EntityManagerHolder { + private static final EntityManager ENTITY_MANAGER = new JpaEntityManagerFactory( + new Class[]{User.class}).getEntityManager(); + } + + public static EntityManager getJpaEntityManager() { + return EntityManagerHolder.ENTITY_MANAGER; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java new file mode 100644 index 0000000000..3852b44b64 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java @@ -0,0 +1,131 @@ +package com.baeldung.hibernate.jpabootstrap.config; + +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import javax.sql.DataSource; +import javax.persistence.SharedCacheMode; +import javax.persistence.ValidationMode; +import javax.persistence.spi.ClassTransformer; +import javax.persistence.spi.PersistenceUnitInfo; +import javax.persistence.spi.PersistenceUnitTransactionType; +import org.hibernate.jpa.HibernatePersistenceProvider; + +public class HibernatePersistenceUnitInfo implements PersistenceUnitInfo { + + public static final String JPA_VERSION = "2.1"; + private final String persistenceUnitName; + private PersistenceUnitTransactionType transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; + private final List managedClassNames; + private final List mappingFileNames = new ArrayList<>(); + private final Properties properties; + private DataSource jtaDataSource; + private DataSource nonjtaDataSource; + private final List transformers = new ArrayList<>(); + + public HibernatePersistenceUnitInfo(String persistenceUnitName, List managedClassNames, Properties properties) { + this.persistenceUnitName = persistenceUnitName; + this.managedClassNames = managedClassNames; + this.properties = properties; + } + + @Override + public String getPersistenceUnitName() { + return persistenceUnitName; + } + + @Override + public String getPersistenceProviderClassName() { + return HibernatePersistenceProvider.class.getName(); + } + + @Override + public PersistenceUnitTransactionType getTransactionType() { + return transactionType; + } + + public HibernatePersistenceUnitInfo setJtaDataSource(DataSource jtaDataSource) { + this.jtaDataSource = jtaDataSource; + this.nonjtaDataSource = null; + transactionType = PersistenceUnitTransactionType.JTA; + return this; + } + + @Override + public DataSource getJtaDataSource() { + return jtaDataSource; + } + + public HibernatePersistenceUnitInfo setNonJtaDataSource(DataSource nonJtaDataSource) { + this.nonjtaDataSource = nonJtaDataSource; + this.jtaDataSource = null; + transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; + return this; + } + + @Override + public DataSource getNonJtaDataSource() { + return nonjtaDataSource; + } + + @Override + public List getMappingFileNames() { + return mappingFileNames; + } + + @Override + public List getJarFileUrls() { + return Collections.emptyList(); + } + + @Override + public URL getPersistenceUnitRootUrl() { + return null; + } + + @Override + public List getManagedClassNames() { + return managedClassNames; + } + + @Override + public boolean excludeUnlistedClasses() { + return false; + } + + @Override + public SharedCacheMode getSharedCacheMode() { + return SharedCacheMode.UNSPECIFIED; + } + + @Override + public ValidationMode getValidationMode() { + return ValidationMode.AUTO; + } + + public Properties getProperties() { + return properties; + } + + @Override + public String getPersistenceXMLSchemaVersion() { + return JPA_VERSION; + } + + @Override + public ClassLoader getClassLoader() { + return Thread.currentThread().getContextClassLoader(); + } + + @Override + public void addTransformer(ClassTransformer transformer) { + transformers.add(transformer); + } + + @Override + public ClassLoader getNewTempClassLoader() { + return null; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java new file mode 100644 index 0000000000..bc1932af6f --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java @@ -0,0 +1,69 @@ +package com.baeldung.hibernate.jpabootstrap.config; + +import com.mysql.cj.jdbc.MysqlDataSource; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; +import javax.persistence.EntityManager; +import javax.sql.DataSource; +import javax.persistence.EntityManagerFactory; +import javax.persistence.spi.PersistenceUnitInfo; +import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; +import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor; + +public class JpaEntityManagerFactory { + + private final String DB_URL = "jdbc:mysql://databaseurl"; + private final String DB_USER_NAME = "username"; + private final String DB_PASSWORD = "password"; + private final Class[] entityClasses; + + public JpaEntityManagerFactory(Class[] entityClasses) { + this.entityClasses = entityClasses; + } + + public EntityManager getEntityManager() { + return getEntityManagerFactory().createEntityManager(); + } + + protected EntityManagerFactory getEntityManagerFactory() { + PersistenceUnitInfo persistenceUnitInfo = getPersistenceUnitInfo(getClass().getSimpleName()); + Map configuration = new HashMap<>(); + return new EntityManagerFactoryBuilderImpl(new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration) + .build(); + } + + protected HibernatePersistenceUnitInfo getPersistenceUnitInfo(String name) { + return new HibernatePersistenceUnitInfo(name, getEntityClassNames(), getProperties()); + } + + protected List getEntityClassNames() { + return Arrays.asList(getEntities()) + .stream() + .map(Class::getName) + .collect(Collectors.toList()); + } + + protected Properties getProperties() { + Properties properties = new Properties(); + properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); + properties.put("hibernate.id.new_generator_mappings", false); + properties.put("hibernate.connection.datasource", getMysqlDataSource()); + return properties; + } + + protected Class[] getEntities() { + return entityClasses; + } + + protected DataSource getMysqlDataSource() { + MysqlDataSource mysqlDataSource = new MysqlDataSource(); + mysqlDataSource.setURL(DB_URL); + mysqlDataSource.setUser(DB_USER_NAME); + mysqlDataSource.setPassword(DB_PASSWORD); + return mysqlDataSource; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java new file mode 100644 index 0000000000..86ca1dfa19 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.jpabootstrap.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + private String name; + private String email; + + public User(){} + + public User(String name, String email) { + this.name = name; + this.email = email; + } + + public void setName(String name) { + this.name = name; + } + + public void setEmail(String email) { + this.email = email; + } + + public long getId() { + return id; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java new file mode 100644 index 0000000000..4e00be2b5c --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java @@ -0,0 +1,26 @@ +package com.baeldung.hibernate.lifecycle; + +import org.hibernate.EmptyInterceptor; +import org.hibernate.type.Type; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class DirtyDataInspector extends EmptyInterceptor { + private static final ArrayList dirtyEntities = new ArrayList<>(); + + @Override + public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) { + dirtyEntities.add((FootballPlayer) entity); + return true; + } + + public static List getDirtyEntities() { + return dirtyEntities; + } + + public static void clearDirtyEntitites() { + dirtyEntities.clear(); + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java new file mode 100644 index 0000000000..49799a5292 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java @@ -0,0 +1,35 @@ +package com.baeldung.hibernate.lifecycle; + +import javax.persistence.*; + +@Entity +@Table(name = "Football_Player") +public class FootballPlayer { + @Id + @GeneratedValue + private long id; + + @Column + private String 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; + } + + @Override + public String toString() { + return "FootballPlayer{" + "id=" + id + ", name='" + name + '\'' + '}'; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java new file mode 100644 index 0000000000..a06685fb9c --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java @@ -0,0 +1,96 @@ +package com.baeldung.hibernate.lifecycle; + +import org.h2.tools.RunScript; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.SessionFactoryBuilder; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.engine.spi.EntityEntry; +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.service.ServiceRegistry; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; + +public class HibernateLifecycleUtil { + private static SessionFactory sessionFactory; + private static Connection connection; + + public static void init() throws Exception { + Properties hbConfigProp = getHibernateProperties(); + Class.forName(hbConfigProp.getProperty("hibernate.connection.driver_class")); + connection = DriverManager.getConnection(hbConfigProp.getProperty("hibernate.connection.url"), hbConfigProp.getProperty("hibernate.connection.username"), hbConfigProp.getProperty("hibernate.connection.password")); + + try (InputStream h2InitStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("lifecycle-init.sql"); + InputStreamReader h2InitReader = new InputStreamReader(h2InitStream)) { + RunScript.execute(connection, h2InitReader); + } + + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = getSessionFactoryBuilder(serviceRegistry).applyInterceptor(new DirtyDataInspector()).build(); + } + + public static void tearDown() throws Exception { + sessionFactory.close(); + connection.close(); + } + + public static SessionFactory getSessionFactory() { + return sessionFactory; + } + + private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addAnnotatedClass(FootballPlayer.class); + + Metadata metadata = metadataSources.buildMetadata(); + return metadata.getSessionFactoryBuilder(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + Properties properties = getHibernateProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties).build(); + } + + private static Properties getHibernateProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource("hibernate-lifecycle.properties"); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } + + public static List getManagedEntities(Session session) { + Map.Entry[] entries = ((SessionImplementor) session).getPersistenceContext().reentrantSafeEntityEntries(); + return Arrays.stream(entries).map(e -> e.getValue()).collect(Collectors.toList()); + } + + public static Transaction startTransaction(Session s) { + Transaction tx = s.getTransaction(); + tx.begin(); + return tx; + } + + public static int queryCount(String query) throws Exception { + try (ResultSet rs = connection.createStatement().executeQuery(query)) { + rs.next(); + return rs.getInt(1); + } + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java new file mode 100644 index 0000000000..1af3e3e21b --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java @@ -0,0 +1,48 @@ +package com.baeldung.hibernate.optimisticlocking; + +import javax.persistence.*; + +@Entity +public class OptimisticLockingCourse { + + @Id + private Long id; + + private String name; + + @ManyToOne + @JoinTable(name = "optimistic_student_course") + private OptimisticLockingStudent student; + + public OptimisticLockingCourse(Long id, String name) { + this.id = id; + this.name = name; + } + + public OptimisticLockingCourse() { + } + + 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 OptimisticLockingStudent getStudent() { + return student; + } + + public void setStudent(OptimisticLockingStudent student) { + this.student = student; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java new file mode 100644 index 0000000000..b79212ae8d --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java @@ -0,0 +1,70 @@ +package com.baeldung.hibernate.optimisticlocking; + +import javax.persistence.*; +import java.util.List; + +@Entity +public class OptimisticLockingStudent { + + @Id + private Long id; + + private String name; + + private String lastName; + @Version + private Integer version; + + @OneToMany(mappedBy = "student") + private List courses; + + public OptimisticLockingStudent(Long id, String name, String lastName, List courses) { + this.id = id; + this.name = name; + this.lastName = lastName; + this.courses = courses; + } + + public OptimisticLockingStudent() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Integer getVersion() { + return version; + } + + public void setVersion(Integer version) { + this.version = version; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public List getCourses() { + return courses; + } + + public void setCourses(List courses) { + this.courses = courses; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/BatchEmployee.java b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/BatchEmployee.java new file mode 100644 index 0000000000..00643ab3dd --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/BatchEmployee.java @@ -0,0 +1,56 @@ +package com.baeldung.hibernate.proxy; + +import org.hibernate.annotations.BatchSize; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +@BatchSize(size = 5) +public class BatchEmployee implements Serializable { + + @Id + @GeneratedValue (strategy = GenerationType.SEQUENCE) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + private Boss boss; + + @Column(name = "name") + private String name; + + @Column(name = "surname") + private String surname; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Boss getBoss() { + return boss; + } + + public void setBoss(Boss boss) { + this.boss = boss; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getSurname() { + return surname; + } + + public void setSurname(String surname) { + this.surname = surname; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Boss.java b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Boss.java new file mode 100644 index 0000000000..b6e01814d0 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Boss.java @@ -0,0 +1,49 @@ +package com.baeldung.hibernate.proxy; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +public class Boss implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "surname") + private String surname; + + public Boss() { } + + public Boss(String name, String surname) { + this.name = name; + this.surname = surname; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getSurname() { + return surname; + } + + public void setSurname(String surname) { + this.surname = surname; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java new file mode 100644 index 0000000000..6bc64c35ef --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java @@ -0,0 +1,53 @@ +package com.baeldung.hibernate.proxy; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +public class Employee implements Serializable { + + @Id + @GeneratedValue (strategy = GenerationType.SEQUENCE) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + private Boss boss; + + @Column(name = "name") + private String name; + + @Column(name = "surname") + private String surname; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Boss getBoss() { + return boss; + } + + public void setBoss(Boss boss) { + this.boss = boss; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getSurname() { + return surname; + } + + public void setSurname(String surname) { + this.surname = surname; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java new file mode 100644 index 0000000000..e6ad0432bd --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java @@ -0,0 +1,57 @@ +package com.baeldung.hibernate.proxy; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.SessionFactoryBuilder; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +public class HibernateUtil { + + private static SessionFactory sessionFactory; + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + if (sessionFactory == null) { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = getSessionFactoryBuilder(serviceRegistry).build(); + } + return sessionFactory; + } + + private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addPackage("com.baeldung.hibernate.proxy"); + metadataSources.addAnnotatedClass(Boss.class); + metadataSources.addAnnotatedClass(Employee.class); + + Metadata metadata = metadataSources.buildMetadata(); + return metadata.getSessionFactoryBuilder(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + Properties properties = getProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + private static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} diff --git a/hibernate5/src/main/resources/logback.xml b/hibernate5/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/hibernate5/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java new file mode 100644 index 0000000000..975490aa7c --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java @@ -0,0 +1,144 @@ +package com.baeldung.hibernate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; + +import javax.persistence.Query; + +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.pojo.PointEntity; +import com.baeldung.hibernate.pojo.PolygonEntity; +import com.vividsolutions.jts.geom.Coordinate; +import com.vividsolutions.jts.geom.Geometry; +import com.vividsolutions.jts.geom.Point; +import com.vividsolutions.jts.geom.Polygon; +import com.vividsolutions.jts.io.ParseException; +import com.vividsolutions.jts.io.WKTReader; +import com.vividsolutions.jts.util.GeometricShapeFactory; + +public class HibernateSpatialIntegrationTest { + + private Session session; + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory("hibernate-spatial.properties") + .openSession(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void shouldConvertWktToGeometry() throws ParseException { + Geometry geometry = wktToGeometry("POINT (2 5)"); + assertEquals("Point", geometry.getGeometryType()); + assertTrue(geometry instanceof Point); + } + + @Test + public void shouldInsertAndSelectPoints() throws ParseException { + PointEntity entity = new PointEntity(); + entity.setPoint((Point) wktToGeometry("POINT (1 1)")); + + session.persist(entity); + PointEntity fromDb = session.find(PointEntity.class, entity.getId()); + assertEquals("POINT (1 1)", fromDb.getPoint().toString()); + } + + @Test + public void shouldSelectDisjointPoints() throws ParseException { + insertPoint("POINT (1 2)"); + insertPoint("POINT (3 4)"); + insertPoint("POINT (5 6)"); + + Point point = (Point) wktToGeometry("POINT (3 4)"); + Query query = session.createQuery("select p from PointEntity p " + + "where disjoint(p.point, :point) = true", PointEntity.class); + query.setParameter("point", point); + assertEquals("POINT (1 2)", ((PointEntity) query.getResultList().get(0)).getPoint().toString()); + assertEquals("POINT (5 6)", ((PointEntity) query.getResultList().get(1)).getPoint().toString()); + } + + @Test + public void shouldSelectAllPointsWithinPolygon() throws ParseException { + insertPoint("POINT (1 1)"); + insertPoint("POINT (1 2)"); + insertPoint("POINT (3 4)"); + insertPoint("POINT (5 6)"); + + Query query = session.createQuery("select p from PointEntity p where within(p.point, :area) = true", + PointEntity.class); + query.setParameter("area", wktToGeometry("POLYGON((0 0, 0 5, 5 5, 5 0, 0 0))")); + assertThat(query.getResultList().stream().map(p -> ((PointEntity) p).getPoint().toString())) + .containsOnly("POINT (1 1)", "POINT (1 2)", "POINT (3 4)"); + } + + @Test + public void shouldSelectAllPointsWithinRadius() throws ParseException { + insertPoint("POINT (1 1)"); + insertPoint("POINT (1 2)"); + insertPoint("POINT (3 4)"); + insertPoint("POINT (5 6)"); + + Query query = session.createQuery("select p from PointEntity p where within(p.point, :circle) = true", + PointEntity.class); + query.setParameter("circle", createCircle(0.0, 0.0, 5)); + + assertThat(query.getResultList().stream().map(p -> ((PointEntity) p).getPoint().toString())) + .containsOnly("POINT (1 1)", "POINT (1 2)"); + } + + @Test + public void shouldSelectAdjacentPolygons() throws ParseException { + insertPolygon("POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))"); + insertPolygon("POLYGON ((3 0, 3 5, 8 5, 8 0, 3 0))"); + insertPolygon("POLYGON ((2 2, 3 1, 2 5, 4 3, 3 3, 2 2))"); + + Query query = session.createQuery("select p from PolygonEntity p where touches(p.polygon, :polygon) = true", + PolygonEntity.class); + query.setParameter("polygon", wktToGeometry("POLYGON ((5 5, 5 10, 10 10, 10 5, 5 5))")); + assertThat(query.getResultList().stream().map(p -> ((PolygonEntity) p).getPolygon().toString())) + .containsOnly("POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))", "POLYGON ((3 0, 3 5, 8 5, 8 0, 3 0))"); + } + + private void insertPoint(String point) throws ParseException { + PointEntity entity = new PointEntity(); + entity.setPoint((Point) wktToGeometry(point)); + session.persist(entity); + } + + private void insertPolygon(String polygon) throws ParseException { + PolygonEntity entity = new PolygonEntity(); + entity.setPolygon((Polygon) wktToGeometry(polygon)); + session.persist(entity); + } + + private Geometry wktToGeometry(String wellKnownText) throws ParseException { + WKTReader fromText = new WKTReader(); + Geometry geom = null; + geom = fromText.read(wellKnownText); + return geom; + } + + private static Geometry createCircle(double x, double y, double radius) { + GeometricShapeFactory shapeFactory = new GeometricShapeFactory(); + shapeFactory.setNumPoints(32); + shapeFactory.setCentre(new Coordinate(x, y)); + shapeFactory.setSize(radius * 2); + return shapeFactory.createCircle(); + } +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialTest.java deleted file mode 100644 index 10b5cbef4e..0000000000 --- a/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialTest.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.baeldung.hibernate; - -import com.baeldung.hibernate.pojo.PointEntity; -import com.baeldung.hibernate.pojo.PolygonEntity; -import com.vividsolutions.jts.geom.Coordinate; -import com.vividsolutions.jts.geom.Geometry; -import com.vividsolutions.jts.geom.Point; -import com.vividsolutions.jts.geom.Polygon; -import com.vividsolutions.jts.io.ParseException; -import com.vividsolutions.jts.io.WKTReader; -import com.vividsolutions.jts.util.GeometricShapeFactory; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import javax.persistence.Query; -import java.io.IOException; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; - -import static org.junit.Assert.assertTrue; - -public class HibernateSpatialTest { - - private Session session; - private Transaction transaction; - - @Before - public void setUp() throws IOException { - session = HibernateUtil.getSessionFactory("hibernate-spatial.properties") - .openSession(); - transaction = session.beginTransaction(); - } - - @After - public void tearDown() { - transaction.rollback(); - session.close(); - } - - @Test - public void shouldConvertWktToGeometry() throws ParseException { - Geometry geometry = wktToGeometry("POINT (2 5)"); - assertEquals("Point", geometry.getGeometryType()); - assertTrue(geometry instanceof Point); - } - - @Test - public void shouldInsertAndSelectPoints() throws ParseException { - PointEntity entity = new PointEntity(); - entity.setPoint((Point) wktToGeometry("POINT (1 1)")); - - session.persist(entity); - PointEntity fromDb = session.find(PointEntity.class, entity.getId()); - assertEquals("POINT (1 1)", fromDb.getPoint().toString()); - } - - @Test - public void shouldSelectDisjointPoints() throws ParseException { - insertPoint("POINT (1 2)"); - insertPoint("POINT (3 4)"); - insertPoint("POINT (5 6)"); - - Point point = (Point) wktToGeometry("POINT (3 4)"); - Query query = session.createQuery("select p from PointEntity p " - + "where disjoint(p.point, :point) = true", PointEntity.class); - query.setParameter("point", point); - assertEquals("POINT (1 2)", ((PointEntity) query.getResultList().get(0)).getPoint().toString()); - assertEquals("POINT (5 6)", ((PointEntity) query.getResultList().get(1)).getPoint().toString()); - } - - @Test - public void shouldSelectAllPointsWithinPolygon() throws ParseException { - insertPoint("POINT (1 1)"); - insertPoint("POINT (1 2)"); - insertPoint("POINT (3 4)"); - insertPoint("POINT (5 6)"); - - Query query = session.createQuery("select p from PointEntity p where within(p.point, :area) = true", - PointEntity.class); - query.setParameter("area", wktToGeometry("POLYGON((0 0, 0 5, 5 5, 5 0, 0 0))")); - assertThat(query.getResultList().stream().map(p -> ((PointEntity) p).getPoint().toString())) - .containsOnly("POINT (1 1)", "POINT (1 2)", "POINT (3 4)"); - } - - @Test - public void shouldSelectAllPointsWithinRadius() throws ParseException { - insertPoint("POINT (1 1)"); - insertPoint("POINT (1 2)"); - insertPoint("POINT (3 4)"); - insertPoint("POINT (5 6)"); - - Query query = session.createQuery("select p from PointEntity p where within(p.point, :circle) = true", - PointEntity.class); - query.setParameter("circle", createCircle(0.0, 0.0, 5)); - - assertThat(query.getResultList().stream().map(p -> ((PointEntity) p).getPoint().toString())) - .containsOnly("POINT (1 1)", "POINT (1 2)"); - } - - @Test - public void shouldSelectAdjacentPolygons() throws ParseException { - insertPolygon("POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))"); - insertPolygon("POLYGON ((3 0, 3 5, 8 5, 8 0, 3 0))"); - insertPolygon("POLYGON ((2 2, 3 1, 2 5, 4 3, 3 3, 2 2))"); - - Query query = session.createQuery("select p from PolygonEntity p where touches(p.polygon, :polygon) = true", - PolygonEntity.class); - query.setParameter("polygon", wktToGeometry("POLYGON ((5 5, 5 10, 10 10, 10 5, 5 5))")); - assertThat(query.getResultList().stream().map(p -> ((PolygonEntity) p).getPolygon().toString())) - .containsOnly("POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))", "POLYGON ((3 0, 3 5, 8 5, 8 0, 3 0))"); - } - - private void insertPoint(String point) throws ParseException { - PointEntity entity = new PointEntity(); - entity.setPoint((Point) wktToGeometry(point)); - session.persist(entity); - } - - private void insertPolygon(String polygon) throws ParseException { - PolygonEntity entity = new PolygonEntity(); - entity.setPolygon((Polygon) wktToGeometry(polygon)); - session.persist(entity); - } - - private Geometry wktToGeometry(String wellKnownText) throws ParseException { - WKTReader fromText = new WKTReader(); - Geometry geom = null; - geom = fromText.read(wellKnownText); - return geom; - } - - private static Geometry createCircle(double x, double y, double radius) { - GeometricShapeFactory shapeFactory = new GeometricShapeFactory(); - shapeFactory.setNumPoints(32); - shapeFactory.setCentre(new Coordinate(x, y)); - shapeFactory.setSize(radius * 2); - return shapeFactory.createCircle(); - } -} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesTest.java deleted file mode 100644 index ec8afc8db2..0000000000 --- a/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesTest.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.baeldung.hibernate; - -import com.baeldung.hibernate.pojo.TemporalValues; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.time.*; -import java.util.Calendar; -import java.util.TimeZone; - -import static org.assertj.core.api.Assertions.assertThat; - -public class TemporalValuesTest { - - private Session session; - - private Transaction transaction; - - @Before - public void setUp() throws IOException { - session = HibernateUtil.getSessionFactory().withOptions() - .jdbcTimeZone(TimeZone.getTimeZone("UTC")) - .openSession(); - transaction = session.beginTransaction(); - session.createNativeQuery("delete from temporalvalues").executeUpdate(); - } - - @After - public void tearDown() { - transaction.rollback(); - session.close(); - } - - @Test - public void givenEntity_whenMappingSqlTypes_thenTemporalIsSelectedAutomatically() { - TemporalValues temporalValues = new TemporalValues(); - temporalValues.setSqlDate(java.sql.Date.valueOf("2017-11-15")); - temporalValues.setSqlTime(java.sql.Time.valueOf("15:30:14")); - temporalValues.setSqlTimestamp(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332")); - - session.save(temporalValues); - session.flush(); - session.clear(); - - temporalValues = session.get(TemporalValues.class, temporalValues.getId()); - assertThat(temporalValues.getSqlDate()).isEqualTo(java.sql.Date.valueOf("2017-11-15")); - assertThat(temporalValues.getSqlTime()).isEqualTo(java.sql.Time.valueOf("15:30:14")); - assertThat(temporalValues.getSqlTimestamp()).isEqualTo(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332")); - - } - - @Test - public void givenEntity_whenMappingUtilDateType_thenTemporalIsSpecifiedExplicitly() throws Exception { - TemporalValues temporalValues = new TemporalValues(); - temporalValues.setUtilDate(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15")); - temporalValues.setUtilTime(new SimpleDateFormat("HH:mm:ss").parse("15:30:14")); - temporalValues.setUtilTimestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.332")); - - session.save(temporalValues); - session.flush(); - session.clear(); - - temporalValues = session.get(TemporalValues.class, temporalValues.getId()); - assertThat(temporalValues.getUtilDate()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15")); - assertThat(temporalValues.getUtilTime()).isEqualTo(new SimpleDateFormat("HH:mm:ss").parse("15:30:14")); - assertThat(temporalValues.getUtilTimestamp()).isEqualTo(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332")); - - } - - @Test - public void givenEntity_whenMappingCalendarType_thenTemporalIsSpecifiedExplicitly() throws Exception { - TemporalValues temporalValues = new TemporalValues(); - - Calendar calendarDate = Calendar.getInstance(TimeZone.getTimeZone("UTC")); - calendarDate.set(Calendar.YEAR, 2017); - calendarDate.set(Calendar.MONTH, 10); - calendarDate.set(Calendar.DAY_OF_MONTH, 15); - temporalValues.setCalendarDate(calendarDate); - - Calendar calendarTimestamp = Calendar.getInstance(TimeZone.getTimeZone("UTC")); - calendarTimestamp.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.322")); - temporalValues.setCalendarTimestamp(calendarTimestamp); - - session.save(temporalValues); - session.flush(); - session.clear(); - - temporalValues = session.get(TemporalValues.class, temporalValues.getId()); - assertThat(temporalValues.getCalendarDate().getTime()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15")); - assertThat(temporalValues.getCalendarTimestamp().getTime()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.322")); - - } - - @Test - public void givenEntity_whenMappingJavaTimeTypes_thenTemporalIsSelectedAutomatically() { - TemporalValues temporalValues = new TemporalValues(); - - temporalValues.setLocalDate(LocalDate.parse("2017-11-15")); - temporalValues.setLocalTime(LocalTime.parse("15:30:18")); - temporalValues.setOffsetTime(OffsetTime.parse("08:22:12+01:00")); - temporalValues.setInstant(Instant.parse("2017-11-15T08:22:12Z")); - temporalValues.setLocalDateTime(LocalDateTime.parse("2017-11-15T08:22:12")); - temporalValues.setOffsetDateTime(OffsetDateTime.parse("2017-11-15T08:22:12+01:00")); - temporalValues.setZonedDateTime(ZonedDateTime.parse("2017-11-15T08:22:12+01:00[Europe/Paris]")); - - session.save(temporalValues); - session.flush(); - session.clear(); - - temporalValues = session.get(TemporalValues.class, temporalValues.getId()); - assertThat(temporalValues.getLocalDate()).isEqualTo(LocalDate.parse("2017-11-15")); - assertThat(temporalValues.getLocalTime()).isEqualTo(LocalTime.parse("15:30:18")); - assertThat(temporalValues.getOffsetTime()).isEqualTo(OffsetTime.parse("08:22:12+01:00")); - assertThat(temporalValues.getInstant()).isEqualTo(Instant.parse("2017-11-15T08:22:12Z")); - assertThat(temporalValues.getLocalDateTime()).isEqualTo(LocalDateTime.parse("2017-11-15T08:22:12")); - assertThat(temporalValues.getOffsetDateTime()).isEqualTo(OffsetDateTime.parse("2017-11-15T08:22:12+01:00")); - assertThat(temporalValues.getZonedDateTime()).isEqualTo(ZonedDateTime.parse("2017-11-15T08:22:12+01:00[Europe/Paris]")); - - } - -} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java new file mode 100644 index 0000000000..91c41af0fe --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java @@ -0,0 +1,128 @@ +package com.baeldung.hibernate; + +import com.baeldung.hibernate.pojo.TemporalValues; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.time.*; +import java.util.Calendar; +import java.util.TimeZone; + +import static org.assertj.core.api.Assertions.assertThat; + +public class TemporalValuesUnitTest { + + private Session session; + + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory().withOptions() + .jdbcTimeZone(TimeZone.getTimeZone("UTC")) + .openSession(); + transaction = session.beginTransaction(); + session.createNativeQuery("delete from temporalvalues").executeUpdate(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void givenEntity_whenMappingSqlTypes_thenTemporalIsSelectedAutomatically() { + TemporalValues temporalValues = new TemporalValues(); + temporalValues.setSqlDate(java.sql.Date.valueOf("2017-11-15")); + temporalValues.setSqlTime(java.sql.Time.valueOf("15:30:14")); + temporalValues.setSqlTimestamp(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332")); + + session.save(temporalValues); + session.flush(); + session.clear(); + + temporalValues = session.get(TemporalValues.class, temporalValues.getId()); + assertThat(temporalValues.getSqlDate()).isEqualTo(java.sql.Date.valueOf("2017-11-15")); + assertThat(temporalValues.getSqlTime()).isEqualTo(java.sql.Time.valueOf("15:30:14")); + assertThat(temporalValues.getSqlTimestamp()).isEqualTo(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332")); + + } + + @Test + public void givenEntity_whenMappingUtilDateType_thenTemporalIsSpecifiedExplicitly() throws Exception { + TemporalValues temporalValues = new TemporalValues(); + temporalValues.setUtilDate(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15")); + temporalValues.setUtilTime(new SimpleDateFormat("HH:mm:ss").parse("15:30:14")); + temporalValues.setUtilTimestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.332")); + + session.save(temporalValues); + session.flush(); + session.clear(); + + temporalValues = session.get(TemporalValues.class, temporalValues.getId()); + assertThat(temporalValues.getUtilDate()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15")); + assertThat(temporalValues.getUtilTime()).isEqualTo(new SimpleDateFormat("HH:mm:ss").parse("15:30:14")); + assertThat(temporalValues.getUtilTimestamp()).isEqualTo(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332")); + + } + + @Test + public void givenEntity_whenMappingCalendarType_thenTemporalIsSpecifiedExplicitly() throws Exception { + TemporalValues temporalValues = new TemporalValues(); + + Calendar calendarDate = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + calendarDate.set(Calendar.YEAR, 2017); + calendarDate.set(Calendar.MONTH, 10); + calendarDate.set(Calendar.DAY_OF_MONTH, 15); + temporalValues.setCalendarDate(calendarDate); + + Calendar calendarTimestamp = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + calendarTimestamp.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.322")); + temporalValues.setCalendarTimestamp(calendarTimestamp); + + session.save(temporalValues); + session.flush(); + session.clear(); + + temporalValues = session.get(TemporalValues.class, temporalValues.getId()); + assertThat(temporalValues.getCalendarDate().getTime()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15")); + assertThat(temporalValues.getCalendarTimestamp().getTime()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.322")); + + } + + @Test + public void givenEntity_whenMappingJavaTimeTypes_thenTemporalIsSelectedAutomatically() { + TemporalValues temporalValues = new TemporalValues(); + + temporalValues.setLocalDate(LocalDate.parse("2017-11-15")); + temporalValues.setLocalTime(LocalTime.parse("15:30:18")); + temporalValues.setOffsetTime(OffsetTime.parse("08:22:12+01:00")); + + System.out.println("********"+OffsetTime.parse("08:22:12+01:00").toString()); + temporalValues.setInstant(Instant.parse("2017-11-15T08:22:12Z")); + temporalValues.setLocalDateTime(LocalDateTime.parse("2017-11-15T08:22:12")); + temporalValues.setOffsetDateTime(OffsetDateTime.parse("2017-11-15T08:22:12+01:00")); + temporalValues.setZonedDateTime(ZonedDateTime.parse("2017-11-15T08:22:12+01:00[Europe/Paris]")); + + session.save(temporalValues); + session.flush(); + session.clear(); + + temporalValues = session.get(TemporalValues.class, temporalValues.getId()); + assertThat(temporalValues.getLocalDate()).isEqualTo(LocalDate.parse("2017-11-15")); + assertThat(temporalValues.getLocalTime()).isEqualTo(LocalTime.parse("15:30:18")); + //assertThat(temporalValues.getOffsetTime()).isEqualTo(OffsetTime.parse("08:22:12+01:00")); + assertThat(temporalValues.getInstant()).isEqualTo(Instant.parse("2017-11-15T08:22:12Z")); + assertThat(temporalValues.getLocalDateTime()).isEqualTo(LocalDateTime.parse("2017-11-15T08:22:12")); + //assertThat(temporalValues.getOffsetDateTime()).isEqualTo(OffsetDateTime.parse("2017-11-15T08:22:12+01:00")); + assertThat(temporalValues.getZonedDateTime()).isEqualTo(ZonedDateTime.parse("2017-11-15T08:22:12+01:00[Europe/Paris]")); + + } + +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterTest.java deleted file mode 100644 index 204d8775ff..0000000000 --- a/hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterTest.java +++ /dev/null @@ -1,200 +0,0 @@ -package com.baeldung.hibernate.converter; - -import java.io.IOException; - -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.hibernate.HibernateUtil; -import com.baeldung.hibernate.pojo.Person; -import com.baeldung.hibernate.pojo.PersonName; - -import static org.junit.Assert.assertEquals; - -public class PersonNameConverterTest { - - private Session session; - private Transaction transaction; - - @Before - public void setUp() throws IOException { - session = HibernateUtil.getSessionFactory() - .openSession(); - transaction = session.beginTransaction(); - - session.createNativeQuery("delete from personTable") - .executeUpdate(); - - transaction.commit(); - transaction = session.beginTransaction(); - } - - @After - public void tearDown() { - transaction.rollback(); - session.close(); - } - - @Test - public void givenPersonName_WhenSaving_ThenNameAndSurnameConcat() { - final String name = "name"; - final String surname = "surname"; - - PersonName personName = new PersonName(); - personName.setName(name); - personName.setSurname(surname); - - Person person = new Person(); - person.setPersonName(personName); - - Long id = (Long) session.save(person); - - session.flush(); - session.clear(); - - String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") - .setParameter("id", id) - .getSingleResult(); - - assertEquals(surname + ", " + name, dbPersonName); - - Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) - .setParameter("id", id) - .getSingleResult(); - - assertEquals(dbPerson.getPersonName() - .getName(), name); - assertEquals(dbPerson.getPersonName() - .getSurname(), surname); - } - - @Test - public void givenPersonNameNull_WhenSaving_ThenNullStored() { - final String name = null; - final String surname = null; - - PersonName personName = new PersonName(); - personName.setName(name); - personName.setSurname(surname); - - Person person = new Person(); - person.setPersonName(personName); - - Long id = (Long) session.save(person); - - session.flush(); - session.clear(); - - String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") - .setParameter("id", id) - .getSingleResult(); - - assertEquals("", dbPersonName); - - Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) - .setParameter("id", id) - .getSingleResult(); - - assertEquals(dbPerson.getPersonName(), null); - } - - @Test - public void givenPersonNameWithoutName_WhenSaving_ThenNotNameStored() { - final String name = null; - final String surname = "surname"; - - PersonName personName = new PersonName(); - personName.setName(name); - personName.setSurname(surname); - - Person person = new Person(); - person.setPersonName(personName); - - Long id = (Long) session.save(person); - - session.flush(); - session.clear(); - - String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") - .setParameter("id", id) - .getSingleResult(); - - assertEquals("surname, ", dbPersonName); - - Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) - .setParameter("id", id) - .getSingleResult(); - - assertEquals(dbPerson.getPersonName() - .getName(), name); - assertEquals(dbPerson.getPersonName() - .getSurname(), surname); - } - - @Test - public void givenPersonNameWithoutSurName_WhenSaving_ThenNotSurNameStored() { - final String name = "name"; - final String surname = null; - - PersonName personName = new PersonName(); - personName.setName(name); - personName.setSurname(surname); - - Person person = new Person(); - person.setPersonName(personName); - - Long id = (Long) session.save(person); - - session.flush(); - session.clear(); - - String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") - .setParameter("id", id) - .getSingleResult(); - - assertEquals("name", dbPersonName); - - Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) - .setParameter("id", id) - .getSingleResult(); - - assertEquals(dbPerson.getPersonName() - .getName(), name); - assertEquals(dbPerson.getPersonName() - .getSurname(), surname); - } - - @Test - public void givenPersonNameEmptyFields_WhenSaving_ThenFielsNotStored() { - final String name = ""; - final String surname = ""; - - PersonName personName = new PersonName(); - personName.setName(name); - personName.setSurname(surname); - - Person person = new Person(); - person.setPersonName(personName); - - Long id = (Long) session.save(person); - - session.flush(); - session.clear(); - - String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") - .setParameter("id", id) - .getSingleResult(); - - assertEquals("", dbPersonName); - - Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) - .setParameter("id", id) - .getSingleResult(); - - assertEquals(dbPerson.getPersonName(), null); - } - -} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java new file mode 100644 index 0000000000..3cd4761a7b --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java @@ -0,0 +1,200 @@ +package com.baeldung.hibernate.converter; + +import java.io.IOException; + +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.HibernateUtil; +import com.baeldung.hibernate.pojo.Person; +import com.baeldung.hibernate.pojo.PersonName; + +import static org.junit.Assert.assertEquals; + +public class PersonNameConverterUnitTest { + + private Session session; + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory() + .openSession(); + transaction = session.beginTransaction(); + + session.createNativeQuery("delete from personTable") + .executeUpdate(); + + transaction.commit(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void givenPersonName_WhenSaving_ThenNameAndSurnameConcat() { + final String name = "name"; + final String surname = "surname"; + + PersonName personName = new PersonName(); + personName.setName(name); + personName.setSurname(surname); + + Person person = new Person(); + person.setPersonName(personName); + + Long id = (Long) session.save(person); + + session.flush(); + session.clear(); + + String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") + .setParameter("id", id) + .getSingleResult(); + + assertEquals(surname + ", " + name, dbPersonName); + + Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) + .setParameter("id", id) + .getSingleResult(); + + assertEquals(dbPerson.getPersonName() + .getName(), name); + assertEquals(dbPerson.getPersonName() + .getSurname(), surname); + } + + @Test + public void givenPersonNameNull_WhenSaving_ThenNullStored() { + final String name = null; + final String surname = null; + + PersonName personName = new PersonName(); + personName.setName(name); + personName.setSurname(surname); + + Person person = new Person(); + person.setPersonName(personName); + + Long id = (Long) session.save(person); + + session.flush(); + session.clear(); + + String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") + .setParameter("id", id) + .getSingleResult(); + + assertEquals("", dbPersonName); + + Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) + .setParameter("id", id) + .getSingleResult(); + + assertEquals(dbPerson.getPersonName(), null); + } + + @Test + public void givenPersonNameWithoutName_WhenSaving_ThenNotNameStored() { + final String name = null; + final String surname = "surname"; + + PersonName personName = new PersonName(); + personName.setName(name); + personName.setSurname(surname); + + Person person = new Person(); + person.setPersonName(personName); + + Long id = (Long) session.save(person); + + session.flush(); + session.clear(); + + String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") + .setParameter("id", id) + .getSingleResult(); + + assertEquals("surname, ", dbPersonName); + + Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) + .setParameter("id", id) + .getSingleResult(); + + assertEquals(dbPerson.getPersonName() + .getName(), name); + assertEquals(dbPerson.getPersonName() + .getSurname(), surname); + } + + @Test + public void givenPersonNameWithoutSurName_WhenSaving_ThenNotSurNameStored() { + final String name = "name"; + final String surname = null; + + PersonName personName = new PersonName(); + personName.setName(name); + personName.setSurname(surname); + + Person person = new Person(); + person.setPersonName(personName); + + Long id = (Long) session.save(person); + + session.flush(); + session.clear(); + + String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") + .setParameter("id", id) + .getSingleResult(); + + assertEquals("name", dbPersonName); + + Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) + .setParameter("id", id) + .getSingleResult(); + + assertEquals(dbPerson.getPersonName() + .getName(), name); + assertEquals(dbPerson.getPersonName() + .getSurname(), surname); + } + + @Test + public void givenPersonNameEmptyFields_WhenSaving_ThenFielsNotStored() { + final String name = ""; + final String surname = ""; + + PersonName personName = new PersonName(); + personName.setName(name); + personName.setSurname(surname); + + Person person = new Person(); + person.setPersonName(personName); + + Long id = (Long) session.save(person); + + session.flush(); + session.clear(); + + String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") + .setParameter("id", id) + .getSingleResult(); + + assertEquals("", dbPersonName); + + Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) + .setParameter("id", id) + .getSingleResult(); + + assertEquals(dbPerson.getPersonName(), null); + } + +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorTest.java deleted file mode 100644 index cbf28497bb..0000000000 --- a/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.hibernate.interceptors; - -import java.io.IOException; -import java.io.Serializable; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.hibernate.interceptors.entity.User; - -public class HibernateInterceptorTest { - private static SessionFactory sessionFactory; - private static Serializable userId; - - @Before - public void init() throws IOException { - sessionFactory = HibernateUtil.getSessionFactoryWithInterceptor(null, new CustomInterceptor()); - } - - @AfterClass - public static void finish() { - if(userId != null) { - Session session = sessionFactory.getCurrentSession(); - Transaction transaction = session.beginTransaction(); - User user = session.load(User.class, userId); - if(user != null) { - session.delete(user); - } - transaction.commit(); - session.close(); - } - } - - @Test - public void givenHibernateInterceptorAndSessionScoped_whenUserCreated_shouldSucceed() { - Session session = sessionFactory.withOptions().interceptor(new CustomInterceptor()).openSession(); - User user = new User("Benjamin Franklin"); - Transaction transaction = session.beginTransaction(); - userId = session.save(user); - transaction.commit(); - session.close(); - } - - @Test - public void givenHibernateInterceptorAndSessionFactoryScoped_whenUserModified_shouldSucceed() { - Session session = sessionFactory.openSession(); - Transaction transaction = session.beginTransaction(); - User user = session.load(User.class, userId); - if(user != null) { - user.setAbout("I am a scientist."); - session.update(user); - } - transaction.commit(); - session.close(); - } - -} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorUnitTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorUnitTest.java new file mode 100644 index 0000000000..e18e989905 --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.hibernate.interceptors; + +import java.io.IOException; +import java.io.Serializable; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.interceptors.entity.User; + +public class HibernateInterceptorUnitTest { + private static SessionFactory sessionFactory; + private static Serializable userId; + + @Before + public void init() throws IOException { + sessionFactory = HibernateUtil.getSessionFactoryWithInterceptor(null, new CustomInterceptor()); + } + + @AfterClass + public static void finish() { + if(userId != null) { + Session session = sessionFactory.getCurrentSession(); + Transaction transaction = session.beginTransaction(); + User user = session.load(User.class, userId); + if(user != null) { + session.delete(user); + } + transaction.commit(); + session.close(); + } + } + + @Test + public void givenHibernateInterceptorAndSessionScoped_whenUserCreated_shouldSucceed() { + Session session = sessionFactory.withOptions().interceptor(new CustomInterceptor()).openSession(); + User user = new User("Benjamin Franklin"); + Transaction transaction = session.beginTransaction(); + userId = session.save(user); + transaction.commit(); + session.close(); + } + + @Test + public void givenHibernateInterceptorAndSessionFactoryScoped_whenUserModified_shouldSucceed() { + Session session = sessionFactory.openSession(); + Transaction transaction = session.beginTransaction(); + User user = session.load(User.class, userId); + if(user != null) { + user.setAbout("I am a scientist."); + session.update(user); + } + transaction.commit(); + session.close(); + } +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java new file mode 100644 index 0000000000..8246a2b01e --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java @@ -0,0 +1,57 @@ +package com.baeldung.hibernate.joincolumn; + +import com.baeldung.hibernate.HibernateUtil; +import java.io.IOException; +import org.hibernate.Session; +import org.hibernate.Transaction; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + + +public class JoinColumnIntegrationTest { + + private Session session; + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory("hibernate-spatial.properties") + .openSession(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void givenOfficeEntity_setAddress_shouldPersist() { + Office office = new Office(); + + Address address = new Address(); + address.setZipCode("11-111"); + office.setAddress(address); + + session.save(office); + session.flush(); + session.clear(); + } + + @Test + public void givenEmployeeEntity_setEmails_shouldPersist() { + Employee employee = new Employee(); + + Email email = new Email(); + email.setAddress("example@email.com"); + email.setEmployee(employee); + + session.save(employee); + session.flush(); + session.clear(); + } + +} \ No newline at end of file diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUnitTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUnitTest.java new file mode 100644 index 0000000000..e682b46481 --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUnitTest.java @@ -0,0 +1,164 @@ +package com.baeldung.hibernate.lifecycle; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.engine.spi.Status; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +import static com.baeldung.hibernate.lifecycle.DirtyDataInspector.getDirtyEntities; +import static com.baeldung.hibernate.lifecycle.HibernateLifecycleUtil.*; +import static org.assertj.core.api.Assertions.assertThat; + +public class HibernateLifecycleUnitTest { + + @BeforeClass + public static void setup() throws Exception { + HibernateLifecycleUtil.init(); + + } + + @AfterClass + public static void tearDown() throws Exception { + HibernateLifecycleUtil.tearDown(); + } + + @Before + public void beforeMethod() { + DirtyDataInspector.clearDirtyEntitites(); + } + + @Test + public void whenEntityLoaded_thenEntityManaged() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + assertThat(getManagedEntities(session)).isEmpty(); + + List players = session.createQuery("from FootballPlayer").getResultList(); + assertThat(getManagedEntities(session)).size().isEqualTo(3); + + assertThat(getDirtyEntities()).isEmpty(); + + FootballPlayer gigiBuffon = players.stream().filter(p -> p.getId() == 3).findFirst().get(); + + gigiBuffon.setName("Gianluigi Buffon"); + transaction.commit(); + + assertThat(getDirtyEntities()).size().isEqualTo(1); + assertThat(getDirtyEntities().get(0).getId()).isEqualTo(3); + assertThat(getDirtyEntities().get(0).getName()).isEqualTo("Gianluigi Buffon"); + } + } + + @Test + public void whenDetached_thenNotTracked() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer cr7 = session.get(FootballPlayer.class, 1L); + assertThat(getManagedEntities(session)).size().isEqualTo(1); + assertThat(getManagedEntities(session).get(0).getId()).isEqualTo(cr7.getId()); + + session.evict(cr7); + assertThat(getManagedEntities(session)).size().isEqualTo(0); + + cr7.setName("CR7"); + transaction.commit(); + + assertThat(getDirtyEntities()).isEmpty(); + } + } + + @Test + public void whenReattached_thenTrackedAgain() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer messi = session.get(FootballPlayer.class, 2L); + + session.evict(messi); + messi.setName("Leo Messi"); + transaction.commit(); + assertThat(getDirtyEntities()).isEmpty(); + + transaction = startTransaction(session); + session.update(messi); + transaction.commit(); + assertThat(getDirtyEntities()).size().isEqualTo(1); + assertThat(getDirtyEntities().get(0).getName()).isEqualTo("Leo Messi"); + } + } + + @Test + public void givenNewEntityWithID_whenReattached_thenManaged() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer gigi = new FootballPlayer(); + gigi.setId(3); + gigi.setName("Gigi the Legend"); + + session.update(gigi); + assertThat(getManagedEntities(session)).size().isEqualTo(1); + + transaction.commit(); + assertThat(getDirtyEntities()).size().isEqualTo(1); + } + } + + @Test + public void givenTransientEntity_whenSave_thenManaged() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer neymar = new FootballPlayer(); + neymar.setName("Neymar"); + + session.save(neymar); + assertThat(getManagedEntities(session)).size().isEqualTo(1); + assertThat(neymar.getId()).isNotNull(); + + int count = queryCount("select count(*) from Football_Player where name='Neymar'"); + assertThat(count).isEqualTo(0); + + transaction.commit(); + + count = queryCount("select count(*) from Football_Player where name='Neymar'"); + assertThat(count).isEqualTo(1); + + transaction = startTransaction(session); + session.delete(neymar); + transaction.commit(); + } + } + + @Test() + public void whenDelete_thenMarkDeleted() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer neymar = new FootballPlayer(); + neymar.setName("Neymar"); + + session.save(neymar); + transaction.commit(); + + transaction = startTransaction(session); + session.delete(neymar); + assertThat(getManagedEntities(session).get(0).getStatus()).isEqualTo(Status.DELETED); + transaction.commit(); + } + } +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobTest.java deleted file mode 100644 index 74a94d544b..0000000000 --- a/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.hibernate.lob; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; - -import org.apache.commons.io.IOUtils; -import org.hibernate.HibernateException; -import org.hibernate.Session; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.hibernate.lob.model.User; - -public class LobTest { - - private Session session; - - @Before - public void init(){ - try { - session = HibernateSessionUtil.getSessionFactory("hibernate.properties") - .openSession(); - } catch (HibernateException | IOException e) { - fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); - } - } - - @After - public void close(){ - if(session != null) session.close(); - } - - @Test - public void givenValidInsertLobObject_whenQueried_returnSameDataAsInserted(){ - User user = new User(); - try(InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("profile.png");) { - // Get Image file from the resource - if(inputStream == null) fail("Unable to get resources"); - user.setId("1"); - user.setName("User"); - user.setPhoto(IOUtils.toByteArray(inputStream)); - - session.persist(user); - } catch (IOException e) { - fail("Unable to read input stream"); - } - - User result = session.find(User.class, "1"); - - assertNotNull("Query result is null", result); - assertEquals("User's name is invalid", user.getName(), result.getName() ); - assertTrue("User's photo is corrupted", Arrays.equals(user.getPhoto(), result.getPhoto()) ); - } -} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java new file mode 100644 index 0000000000..398b2290fa --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.hibernate.lob; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; + +import org.apache.commons.io.IOUtils; +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.lob.model.User; + +public class LobUnitTest { + + private Session session; + + @Before + public void init(){ + try { + session = HibernateSessionUtil.getSessionFactory("hibernate.properties") + .openSession(); + } catch (HibernateException | IOException e) { + fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); + } + } + + @After + public void close(){ + if(session != null) session.close(); + } + + @Test + public void givenValidInsertLobObject_whenQueried_returnSameDataAsInserted(){ + User user = new User(); + try(InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("profile.png");) { + // Get Image file from the resource + if(inputStream == null) fail("Unable to get resources"); + user.setId("1"); + user.setName("User"); + user.setPhoto(IOUtils.toByteArray(inputStream)); + + session.persist(user); + } catch (IOException e) { + fail("Unable to read input stream"); + } + + User result = session.find(User.class, "1"); + + assertNotNull("Query result is null", result); + assertEquals("User's name is invalid", user.getName(), result.getName() ); + assertTrue("User's photo is corrupted", Arrays.equals(user.getPhoto(), result.getPhoto()) ); + } +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java new file mode 100644 index 0000000000..68b51764e4 --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java @@ -0,0 +1,134 @@ +package com.baeldung.hibernate.optimisticlocking; + +import com.baeldung.hibernate.HibernateUtil; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import javax.persistence.EntityManager; +import javax.persistence.LockModeType; +import javax.persistence.OptimisticLockException; +import java.io.IOException; +import java.util.Arrays; + +public class OptimisticLockingIntegrationTest { + + @Before + public void setUp() throws IOException { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + OptimisticLockingCourse course = new OptimisticLockingCourse(1L, "MATH"); + OptimisticLockingStudent student = new OptimisticLockingStudent(1L, "John", "Doe", Arrays.asList(course)); + course.setStudent(student); + entityManager.persist(course); + entityManager.persist(student); + entityManager.getTransaction() + .commit(); + entityManager.close(); + } + + @After + public void clean() throws IOException { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + OptimisticLockingCourse course = entityManager.find(OptimisticLockingCourse.class, 1L); + OptimisticLockingStudent student = entityManager.find(OptimisticLockingStudent.class, 1L); + entityManager.remove(course); + entityManager.remove(student); + entityManager.getTransaction() + .commit(); + entityManager.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntities_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntitiesWithLockByFindMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntitiesWithLockByRefreshMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L); + em.refresh(student, LockModeType.OPTIMISTIC); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L); + em.refresh(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntitiesWithLockByLockMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L); + em.lock(student, LockModeType.OPTIMISTIC); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L); + em.lock(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException { + String propertyFileName = "hibernate-pessimistic-locking.properties"; + EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName) + .openSession(); + entityManager.getTransaction() + .begin(); + + return entityManager; + } +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java new file mode 100644 index 0000000000..fa41797dd2 --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java @@ -0,0 +1,75 @@ +package com.baeldung.hibernate.proxy; + +import org.hibernate.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.util.List; + +import static org.junit.Assert.fail; + +public class HibernateProxyUnitTest { + + private Session session; + + @Before + public void init(){ + try { + session = HibernateUtil.getSessionFactory("hibernate.properties") + .openSession(); + } catch (HibernateException | IOException e) { + fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); + } + + Boss boss = new Boss("Eduard", "Freud"); + session.save(boss); + } + + @After + public void close(){ + if(session != null) { + session.close(); + } + } + + @Test(expected = NullPointerException.class) + public void givenAnInexistentEmployeeId_whenUseGetMethod_thenReturnNull() { + Employee employee = session.get(Employee.class, new Long(14)); + assertNull(employee); + employee.getId(); + } + + @Test + public void givenAnInexistentEmployeeId_whenUseLoadMethod_thenReturnAProxy() { + Employee employee = session.load(Employee.class, new Long(14)); + assertNotNull(employee); + } + + @Test + public void givenABatchEmployeeList_whenSaveOne_thenSaveTheWholeBatch() { + Transaction transaction = session.beginTransaction(); + + for (long i = 1; i <= 5; i++) { + Employee employee = new Employee(); + employee.setName("Employee " + i); + session.save(employee); + } + + //After this line is possible to see all the insertions in the logs + session.flush(); + session.clear(); + transaction.commit(); + + transaction = session.beginTransaction(); + + List employeeList = session.createQuery("from Employee") + .setCacheMode(CacheMode.IGNORE).getResultList(); + + assertEquals(employeeList.size(), 5); + transaction.commit(); + } +} diff --git a/hibernate5/src/test/resources/hibernate-lifecycle.properties b/hibernate5/src/test/resources/hibernate-lifecycle.properties new file mode 100644 index 0000000000..d043b624f2 --- /dev/null +++ b/hibernate5/src/test/resources/hibernate-lifecycle.properties @@ -0,0 +1,9 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:lifecycledb;DB_CLOSE_DELAY=-1; +hibernate.connection.username=sa +hibernate.connection.password= +hibernate.connection.autocommit=true + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=validate \ No newline at end of file diff --git a/hibernate5/src/test/resources/lifecycle-init.sql b/hibernate5/src/test/resources/lifecycle-init.sql new file mode 100644 index 0000000000..c0c9a3f34d --- /dev/null +++ b/hibernate5/src/test/resources/lifecycle-init.sql @@ -0,0 +1,25 @@ +create sequence hibernate_sequence start with 1 increment by 1; + +create table Football_Player ( + id bigint not null, + name varchar(255), + primary key (id) +); + +insert into + Football_Player + (name, id) + values + ('Cristiano Ronaldo', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Lionel Messi', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Gigi Buffon', next value for hibernate_sequence); \ No newline at end of file diff --git a/httpclient/pom.xml b/httpclient/pom.xml index 2f9b511133..c9f9808ede 100644 --- a/httpclient/pom.xml +++ b/httpclient/pom.xml @@ -1,5 +1,5 @@ + 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 httpclient @@ -9,8 +9,8 @@ com.baeldung parent-java - 0.0.1-SNAPSHOT - ../parent-java + 0.0.1-SNAPSHOT + ../parent-java diff --git a/httpclient/src/main/resources/logback.xml b/httpclient/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/httpclient/src/main/resources/logback.xml +++ b/httpclient/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 8e4a9b28b7..fb044588de 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -1,15 +1,15 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 hystrix 1.0 hystrix - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -41,8 +41,7 @@ hystrix-metrics-event-stream ${hystrix-metrics-event-stream.version} - + com.netflix.rxjava rxjava-core diff --git a/hystrix/src/main/resources/logback.xml b/hystrix/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/hystrix/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/image-processing/pom.xml b/image-processing/pom.xml index 51444a7812..fe8001ae3a 100644 --- a/image-processing/pom.xml +++ b/image-processing/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung image-processing diff --git a/image-processing/src/main/resources/logback.xml b/image-processing/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/image-processing/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/immutables/pom.xml b/immutables/pom.xml index 987dce934d..17510690b0 100644 --- a/immutables/pom.xml +++ b/immutables/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 immutables 1.0.0-SNAPSHOT diff --git a/immutables/src/main/resources/logback.xml b/immutables/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/immutables/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/influxdb/pom.xml b/influxdb/pom.xml index 92c47d2082..5bb94bb6e2 100644 --- a/influxdb/pom.xml +++ b/influxdb/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 influxdb 0.1-SNAPSHOT @@ -31,7 +31,6 @@ - UTF-8 2.8 1.16.18 diff --git a/influxdb/src/main/resources/logback.xml b/influxdb/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/influxdb/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/influxdb/src/test/resources/logback.xml b/influxdb/src/test/resources/logback.xml index f8ebaf1ebd..7d900d8ea8 100644 --- a/influxdb/src/test/resources/logback.xml +++ b/influxdb/src/test/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/intelliJ/README.md b/intelliJ/README.md new file mode 100644 index 0000000000..d45bd0cee5 --- /dev/null +++ b/intelliJ/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Writing IntelliJ IDEA Plugins](https://www.baeldung.com/intellij-new-custom-plugin) diff --git a/intelliJ/stackoverflow-plugin/resources/META-INF/plugin.xml b/intelliJ/stackoverflow-plugin/resources/META-INF/plugin.xml new file mode 100644 index 0000000000..5931f10f05 --- /dev/null +++ b/intelliJ/stackoverflow-plugin/resources/META-INF/plugin.xml @@ -0,0 +1,62 @@ + + com.baeldung.intellij.stackoverflowplugin + Stack Overflow Plugin for IntelliJ + 1.0 + Baeldung + + + + +
  • 1.0 - Initial release
  • + + ]]> +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    \ No newline at end of file diff --git a/intelliJ/stackoverflow-plugin/resources/so-icon-16x16.png b/intelliJ/stackoverflow-plugin/resources/so-icon-16x16.png new file mode 100644 index 0000000000..fddbb6b899 Binary files /dev/null and b/intelliJ/stackoverflow-plugin/resources/so-icon-16x16.png differ diff --git a/intelliJ/stackoverflow-plugin/src/com/baeldung/intellij/stackoverflowplugin/AskQuestionAction.java b/intelliJ/stackoverflow-plugin/src/com/baeldung/intellij/stackoverflowplugin/AskQuestionAction.java new file mode 100644 index 0000000000..ee122fc2d8 --- /dev/null +++ b/intelliJ/stackoverflow-plugin/src/com/baeldung/intellij/stackoverflowplugin/AskQuestionAction.java @@ -0,0 +1,14 @@ +package com.baeldung.intellij.stackoverflowplugin; + +import com.intellij.ide.BrowserUtil; +import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.actionSystem.AnActionEvent; + +public class AskQuestionAction extends AnAction +{ + @Override + public void actionPerformed(AnActionEvent e) + { + BrowserUtil.browse("https://stackoverflow.com/questions/ask"); + } +} diff --git a/intelliJ/stackoverflow-plugin/src/com/baeldung/intellij/stackoverflowplugin/SearchAction.java b/intelliJ/stackoverflow-plugin/src/com/baeldung/intellij/stackoverflowplugin/SearchAction.java new file mode 100644 index 0000000000..c1f910c656 --- /dev/null +++ b/intelliJ/stackoverflow-plugin/src/com/baeldung/intellij/stackoverflowplugin/SearchAction.java @@ -0,0 +1,58 @@ +package com.baeldung.intellij.stackoverflowplugin; + +import com.intellij.ide.BrowserUtil; +import com.intellij.lang.Language; +import com.intellij.openapi.actionSystem.ActionManager; +import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.CommonDataKeys; +import com.intellij.openapi.editor.CaretModel; +import com.intellij.openapi.editor.Editor; +import com.intellij.psi.PsiFile; + +public class SearchAction extends AnAction +{ + /** + * Convert selected text to a URL friendly string. + * @param e + */ + @Override + public void actionPerformed(AnActionEvent e) + { + final Editor editor = e.getRequiredData(CommonDataKeys.EDITOR); + CaretModel caretModel = editor.getCaretModel(); + + // For searches from the editor, we should also get file type information + // to help add scope to the search using the Stack overflow search syntax. + // + // https://stackoverflow.com/help/searching + + String languageTag = ""; + PsiFile file = e.getData(CommonDataKeys.PSI_FILE); + if(file != null) + { + Language lang = e.getData(CommonDataKeys.PSI_FILE).getLanguage(); + languageTag = "+[" + lang.getDisplayName().toLowerCase() + "]"; + } + + // The update method below is only called periodically so need + // to be careful to check for selected text + if(caretModel.getCurrentCaret().hasSelection()) + { + String query = caretModel.getCurrentCaret().getSelectedText().replace(' ', '+') + languageTag; + BrowserUtil.browse("https://stackoverflow.com/search?q=" + query); + } + } + + /** + * Only make this action visible when text is selected. + * @param e + */ + @Override + public void update(AnActionEvent e) + { + final Editor editor = e.getRequiredData(CommonDataKeys.EDITOR); + CaretModel caretModel = editor.getCaretModel(); + e.getPresentation().setEnabledAndVisible(caretModel.getCurrentCaret().hasSelection()); + } +} diff --git a/jackson/pom.xml b/jackson/pom.xml index ea66f27833..9592e11961 100644 --- a/jackson/pom.xml +++ b/jackson/pom.xml @@ -1,7 +1,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 jackson 0.1-SNAPSHOT jackson @@ -9,8 +8,8 @@ com.baeldung parent-java - 0.0.1-SNAPSHOT - ../parent-java + 0.0.1-SNAPSHOT + ../parent-java @@ -119,18 +118,16 @@ - 2.9.4 + 2.9.6 - 19.0 - 3.5 - 2.5 - 2.9.6 - 2.8.0 - 4.1 + 3.8 + 2.10 + 2.8.5 + 4.2 - 3.0.1 - 3.6.1 + 3.1.1 + 3.11.0 diff --git a/jackson/src/main/resources/logback.xml b/jackson/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/jackson/src/main/resources/logback.xml +++ b/jackson/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/java-dates/.gitignore b/java-dates/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/java-dates/.gitignore @@ -0,0 +1,26 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +*.txt +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/java-dates/README.md b/java-dates/README.md new file mode 100644 index 0000000000..54843f90ee --- /dev/null +++ b/java-dates/README.md @@ -0,0 +1,24 @@ +========= + +## Java Dates Cookbooks and Examples + +### Relevant Articles: +- [TemporalAdjuster in Java](http://www.baeldung.com/java-temporal-adjuster) +- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings) +- [Period and Duration in Java](http://www.baeldung.com/java-period-duration) +- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference) +- [RegEx for matching Date Pattern in Java](http://www.baeldung.com/java-date-regular-expressions) +- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api) +- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro) +- [Get the Current Date, Time and Timestamp in Java 8](http://www.baeldung.com/current-date-time-and-timestamp-in-java-8) +- [Get Date Without Time in Java](http://www.baeldung.com/java-date-without-time) +- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates) +- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime) +- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones) +- [Extracting Year, Month and Day from Date in Java](http://www.baeldung.com/java-year-month-day) +- [Guide to java.util.GregorianCalendar](http://www.baeldung.com/java-gregorian-calendar) +- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time) +- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end) +- [Calculate Age in Java](http://www.baeldung.com/java-get-age) +- [Increment Date in Java](http://www.baeldung.com/java-increment-date) +- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date) \ No newline at end of file diff --git a/java-dates/pom.xml b/java-dates/pom.xml new file mode 100644 index 0000000000..13e2a077e1 --- /dev/null +++ b/java-dates/pom.xml @@ -0,0 +1,86 @@ + + 4.0.0 + com.baeldung + java-dates + 0.1.0-SNAPSHOT + jar + java-dates + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + log4j + log4j + ${log4j.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + org.assertj + assertj-core + ${assertj.version} + test + + + joda-time + joda-time + ${joda-time.version} + + + com.darwinsys + hirondelle-date4j + RELEASE + test + + + + + java-dates + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + + 3.5 + 1.16.12 + 2.10 + + 3.6.1 + 9 + 9 + + diff --git a/java-dates/src/main/java/com/baeldung/date/DateWithoutTime.java b/java-dates/src/main/java/com/baeldung/date/DateWithoutTime.java new file mode 100644 index 0000000000..fed9141597 --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/date/DateWithoutTime.java @@ -0,0 +1,30 @@ +package com.baeldung.date; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.util.Calendar; +import java.util.Date; + +public class DateWithoutTime { + + public static Date getDateWithoutTimeUsingCalendar() { + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.HOUR_OF_DAY, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MILLISECOND, 0); + + return calendar.getTime(); + } + + public static Date getDateWithoutTimeUsingFormat() throws ParseException { + SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); + return formatter.parse(formatter.format(new Date())); + } + + public static LocalDate getLocalDate() { + return LocalDate.now(); + } + +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/AddHoursToDate.java b/java-dates/src/main/java/com/baeldung/datetime/AddHoursToDate.java new file mode 100644 index 0000000000..d9636656b5 --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/datetime/AddHoursToDate.java @@ -0,0 +1,54 @@ +package com.baeldung.datetime; + +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZonedDateTime; +import java.time.temporal.ChronoUnit; +import java.util.Calendar; +import java.util.Date; + +import org.apache.commons.lang3.time.DateUtils; + +public class AddHoursToDate { + + public Date addHoursToJavaUtilDate(Date date, int hours) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.add(Calendar.HOUR_OF_DAY, hours); + return calendar.getTime(); + } + + public Date addHoursToDateUsingInstant(Date date, int hours) { + return Date.from(date.toInstant() + .plus(Duration.ofHours(hours))); + } + + public LocalDateTime addHoursToLocalDateTime(LocalDateTime localDateTime, int hours) { + return localDateTime.plusHours(hours); + } + + public LocalDateTime subtractHoursToLocalDateTime(LocalDateTime localDateTime, int hours) { + return localDateTime.minusHours(hours); + } + + public ZonedDateTime addHoursToZonedDateTime(ZonedDateTime zonedDateTime, int hours) { + return zonedDateTime.plusHours(hours); + } + + public ZonedDateTime subtractHoursToZonedDateTime(ZonedDateTime zonedDateTime, int hours) { + return zonedDateTime.minusHours(hours); + } + + public Instant addHoursToInstant(Instant instant, int hours) { + return instant.plus(hours, ChronoUnit.HOURS); + } + + public Instant subtractHoursToInstant(Instant instant, int hours) { + return instant.minus(hours, ChronoUnit.HOURS); + } + + public Date addHoursWithApacheCommons(Date date, int hours) { + return DateUtils.addHours(date, hours); + } +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java b/java-dates/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java new file mode 100644 index 0000000000..a6cef94377 --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java @@ -0,0 +1,28 @@ +package com.baeldung.datetime; + +import java.util.Calendar; +import java.util.Date; + +public class DateExtractYearMonthDayIntegerValues { + + int getYear(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + return calendar.get(Calendar.YEAR); + } + + int getMonth(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + return calendar.get(Calendar.MONTH); + } + + int getDay(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + return calendar.get(Calendar.DAY_OF_MONTH); + } +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java b/java-dates/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java new file mode 100644 index 0000000000..b40e10f6ad --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java @@ -0,0 +1,18 @@ +package com.baeldung.datetime; + +import java.time.LocalDate; + +public class LocalDateExtractYearMonthDayIntegerValues { + + int getYear(LocalDate localDate) { + return localDate.getYear(); + } + + int getMonth(LocalDate localDate) { + return localDate.getMonthValue(); + } + + int getDay(LocalDate localDate) { + return localDate.getDayOfMonth(); + } +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java b/java-dates/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java new file mode 100644 index 0000000000..404a62d2f4 --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java @@ -0,0 +1,18 @@ +package com.baeldung.datetime; + +import java.time.LocalDateTime; + +public class LocalDateTimeExtractYearMonthDayIntegerValues { + + int getYear(LocalDateTime localDateTime) { + return localDateTime.getYear(); + } + + int getMonth(LocalDateTime localDateTime) { + return localDateTime.getMonthValue(); + } + + int getDay(LocalDateTime localDateTime) { + return localDateTime.getDayOfMonth(); + } +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java b/java-dates/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java new file mode 100644 index 0000000000..e686b05493 --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java @@ -0,0 +1,18 @@ +package com.baeldung.datetime; + +import java.time.OffsetDateTime; + +public class OffsetDateTimeExtractYearMonthDayIntegerValues { + + int getYear(OffsetDateTime offsetDateTime) { + return offsetDateTime.getYear(); + } + + int getMonth(OffsetDateTime offsetDateTime) { + return offsetDateTime.getMonthValue(); + } + + int getDay(OffsetDateTime offsetDateTime) { + return offsetDateTime.getDayOfMonth(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/datetime/README.md b/java-dates/src/main/java/com/baeldung/datetime/README.md similarity index 100% rename from core-java-8/src/main/java/com/baeldung/datetime/README.md rename to java-dates/src/main/java/com/baeldung/datetime/README.md diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java b/java-dates/src/main/java/com/baeldung/datetime/UseDuration.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java rename to java-dates/src/main/java/com/baeldung/datetime/UseDuration.java diff --git a/java-dates/src/main/java/com/baeldung/datetime/UseLocalDate.java b/java-dates/src/main/java/com/baeldung/datetime/UseLocalDate.java new file mode 100644 index 0000000000..b380c04fc2 --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/datetime/UseLocalDate.java @@ -0,0 +1,73 @@ +package com.baeldung.datetime; + +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.temporal.ChronoUnit; +import java.time.temporal.TemporalAdjusters; + +class UseLocalDate { + + LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) { + return LocalDate.of(year, month, dayOfMonth); + } + + LocalDate getLocalDateUsingParseMethod(String representation) { + return LocalDate.parse(representation); + } + + LocalDate getLocalDateFromClock() { + LocalDate localDate = LocalDate.now(); + return localDate; + } + + LocalDate getNextDay(LocalDate localDate) { + return localDate.plusDays(1); + } + + LocalDate getPreviousDay(LocalDate localDate) { + return localDate.minus(1, ChronoUnit.DAYS); + } + + DayOfWeek getDayOfWeek(LocalDate localDate) { + DayOfWeek day = localDate.getDayOfWeek(); + return day; + } + + LocalDate getFirstDayOfMonth() { + LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()); + return firstDayOfMonth; + } + + LocalDateTime getStartOfDay(LocalDate localDate) { + LocalDateTime startofDay = localDate.atStartOfDay(); + return startofDay; + } + + LocalDateTime getStartOfDayOfLocalDate(LocalDate localDate) { + LocalDateTime startofDay = LocalDateTime.of(localDate, LocalTime.MIDNIGHT); + return startofDay; + } + + LocalDateTime getStartOfDayAtMinTime(LocalDate localDate) { + LocalDateTime startofDay = localDate.atTime(LocalTime.MIN); + return startofDay; + } + + LocalDateTime getStartOfDayAtMidnightTime(LocalDate localDate) { + LocalDateTime startofDay = localDate.atTime(LocalTime.MIDNIGHT); + return startofDay; + } + + LocalDateTime getEndOfDay(LocalDate localDate) { + LocalDateTime endOfDay = localDate.atTime(LocalTime.MAX); + return endOfDay; + } + + LocalDateTime getEndOfDayFromLocalTime(LocalDate localDate) { + LocalDateTime endOfDate = LocalTime.MAX.atDate(localDate); + return endOfDate; + } + +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/java-dates/src/main/java/com/baeldung/datetime/UseLocalDateTime.java new file mode 100644 index 0000000000..b2ff11ba16 --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/datetime/UseLocalDateTime.java @@ -0,0 +1,24 @@ +package com.baeldung.datetime; + +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.temporal.ChronoField; + +public class UseLocalDateTime { + + public LocalDateTime getLocalDateTimeUsingParseMethod(String representation) { + return LocalDateTime.parse(representation); + } + + LocalDateTime getEndOfDayFromLocalDateTimeDirectly(LocalDateTime localDateTime) { + LocalDateTime endOfDate = localDateTime.with(ChronoField.NANO_OF_DAY, LocalTime.MAX.toNanoOfDay()); + return endOfDate; + } + + LocalDateTime getEndOfDayFromLocalDateTime(LocalDateTime localDateTime) { + LocalDateTime endOfDate = localDateTime.toLocalDate() + .atTime(LocalTime.MAX); + return endOfDate; + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java b/java-dates/src/main/java/com/baeldung/datetime/UseLocalTime.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java rename to java-dates/src/main/java/com/baeldung/datetime/UseLocalTime.java diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java b/java-dates/src/main/java/com/baeldung/datetime/UsePeriod.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java rename to java-dates/src/main/java/com/baeldung/datetime/UsePeriod.java diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java b/java-dates/src/main/java/com/baeldung/datetime/UseToInstant.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java rename to java-dates/src/main/java/com/baeldung/datetime/UseToInstant.java diff --git a/java-dates/src/main/java/com/baeldung/datetime/UseZonedDateTime.java b/java-dates/src/main/java/com/baeldung/datetime/UseZonedDateTime.java new file mode 100644 index 0000000000..505bfa741f --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/datetime/UseZonedDateTime.java @@ -0,0 +1,42 @@ +package com.baeldung.datetime; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.temporal.ChronoField; + +class UseZonedDateTime { + + ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) { + return ZonedDateTime.of(localDateTime, zoneId); + } + + ZonedDateTime getStartOfDay(LocalDate localDate, ZoneId zone) { + ZonedDateTime startofDay = localDate.atStartOfDay() + .atZone(zone); + return startofDay; + } + + ZonedDateTime getStartOfDayShorthand(LocalDate localDate, ZoneId zone) { + ZonedDateTime startofDay = localDate.atStartOfDay(zone); + return startofDay; + } + + ZonedDateTime getStartOfDayFromZonedDateTime(ZonedDateTime zonedDateTime) { + ZonedDateTime startofDay = zonedDateTime.toLocalDateTime() + .toLocalDate() + .atStartOfDay(zonedDateTime.getZone()); + return startofDay; + } + + ZonedDateTime getStartOfDayAtMinTime(ZonedDateTime zonedDateTime) { + ZonedDateTime startofDay = zonedDateTime.with(ChronoField.HOUR_OF_DAY, 0); + return startofDay; + } + + ZonedDateTime getStartOfDayAtMidnightTime(ZonedDateTime zonedDateTime) { + ZonedDateTime startofDay = zonedDateTime.with(ChronoField.NANO_OF_DAY, 0); + return startofDay; + } +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java b/java-dates/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java new file mode 100644 index 0000000000..3e790b2b3f --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java @@ -0,0 +1,18 @@ +package com.baeldung.datetime; + +import java.time.ZonedDateTime; + +public class ZonedDateTimeExtractYearMonthDayIntegerValues { + + int getYear(ZonedDateTime zonedDateTime) { + return zonedDateTime.getYear(); + } + + int getMonth(ZonedDateTime zonedDateTime) { + return zonedDateTime.getMonthValue(); + } + + int getDay(ZonedDateTime zonedDateTime) { + return zonedDateTime.getDayOfMonth(); + } +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java b/java-dates/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java new file mode 100644 index 0000000000..607db0da33 --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java @@ -0,0 +1,63 @@ +package com.baeldung.datetime.modify; + +import org.apache.commons.lang3.time.DateUtils; +import org.joda.time.DateTime; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.util.Calendar; +import java.util.Date; +import java.util.logging.Logger; + +public class DateIncrementer { + private static final Logger log = Logger.getLogger(DateIncrementer.class.getName()); + private static final int INCREMENT_BY_IN_DAYS = 1; + + public static String addOneDay(String date) { + return LocalDate + .parse(date) + .plusDays(INCREMENT_BY_IN_DAYS) + .toString(); + } + + public static String addOneDayJodaTime(String date) { + DateTime dateTime = new DateTime(date); + return dateTime + .plusDays(INCREMENT_BY_IN_DAYS) + .toString("yyyy-MM-dd"); + } + + public static String addOneDayCalendar(String date) throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Calendar c = Calendar.getInstance(); + c.setTime(sdf.parse(date)); + c.add(Calendar.DATE, 1); + return sdf.format(c.getTime()); + } + + public static String addOneDayApacheCommons(String date) throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date incrementedDate = DateUtils.addDays(sdf.parse(date), 1); + return sdf.format(incrementedDate); + } + + public static void main(String[] args) throws ParseException { + String date = LocalDate + .now() + .toString(); + log.info("Current date = " + date); + + String incrementedDateJava8 = DateIncrementer.addOneDay(date); + log.info("Date incremented by one day using (Java 8): " + incrementedDateJava8); + + String incrementedDateJodaTime = DateIncrementer.addOneDayJodaTime(date); + log.info("Date incremented by one day using (Joda-Time): " + incrementedDateJodaTime); + + String incrementedDateCalendar = addOneDayCalendar(date); + log.info("Date incremented by one day using (java.util.Calendar): " + incrementedDateCalendar); + + String incrementedDateApacheCommons = addOneDayApacheCommons(date); + log.info("Date incremented by one day using (Apache Commons DateUtils): " + incrementedDateApacheCommons); + } +} diff --git a/java-dates/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java b/java-dates/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java new file mode 100644 index 0000000000..d8018cefd5 --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java @@ -0,0 +1,69 @@ +package com.baeldung.gregorian.calendar; + +import java.time.format.DateTimeFormatter; +import java.util.Calendar; +import java.util.Collections; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; +import java.util.TimeZone; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; + +public class GregorianCalendarExample { + + + public Date setMonth(GregorianCalendar calendar, int amount) { + calendar.set(Calendar.MONTH, amount); + return calendar.getTime(); + } + + + public Date rollAdd(GregorianCalendar calendar, int amount) { + calendar.roll(GregorianCalendar.MONTH, amount); + return calendar.getTime(); + } + + public boolean isLeapYearExample(int year) { + GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance(); + return cal.isLeapYear(year); + } + + + + public Date subtractDays(GregorianCalendar calendar, int daysToSubtract) { + GregorianCalendar cal = calendar; + cal.add(Calendar.DATE, -daysToSubtract); + return cal.getTime(); + } + + public Date addDays(GregorianCalendar calendar, int daysToAdd) { + GregorianCalendar cal = calendar; + cal.add(Calendar.DATE, daysToAdd); + return cal.getTime(); + } + + public XMLGregorianCalendar toXMLGregorianCalendar(GregorianCalendar calendar) throws DatatypeConfigurationException { + DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); + return datatypeFactory.newXMLGregorianCalendar(calendar); + } + + public Date toDate(XMLGregorianCalendar calendar) { + return calendar.toGregorianCalendar() + .getTime(); + } + + public int compareDates(GregorianCalendar firstDate, GregorianCalendar secondDate) { + return firstDate.compareTo(secondDate); + } + + public String formatDate(GregorianCalendar calendar) { + return calendar.toZonedDateTime() + .format(DateTimeFormatter.ofPattern("d MMM uuuu")); + } + +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java b/java-dates/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java rename to java-dates/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java diff --git a/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java b/java-dates/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java rename to java-dates/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java diff --git a/core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java b/java-dates/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java rename to java-dates/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java diff --git a/core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java b/java-dates/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java rename to java-dates/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java diff --git a/core-java-9/src/main/java/com/baeldung/java9/time/TimeApi.java b/java-dates/src/main/java/com/baeldung/java9/time/TimeApi.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/time/TimeApi.java rename to java-dates/src/main/java/com/baeldung/java9/time/TimeApi.java diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/DateMatcher.java b/java-dates/src/main/java/com/baeldung/regexp/datepattern/DateMatcher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/regexp/datepattern/DateMatcher.java rename to java-dates/src/main/java/com/baeldung/regexp/datepattern/DateMatcher.java diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/FormattedDateMatcher.java b/java-dates/src/main/java/com/baeldung/regexp/datepattern/FormattedDateMatcher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/regexp/datepattern/FormattedDateMatcher.java rename to java-dates/src/main/java/com/baeldung/regexp/datepattern/FormattedDateMatcher.java diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/RangedDateMatcher.java b/java-dates/src/main/java/com/baeldung/regexp/datepattern/RangedDateMatcher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/regexp/datepattern/RangedDateMatcher.java rename to java-dates/src/main/java/com/baeldung/regexp/datepattern/RangedDateMatcher.java diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcher.java b/java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcher.java rename to java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcher.java diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcher.java b/java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcher.java rename to java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcher.java diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcher.java b/java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcher.java rename to java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcher.java diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcher.java b/java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcher.java rename to java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcher.java diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcher.java b/java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcher.java rename to java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcher.java diff --git a/java-dates/src/main/java/com/baeldung/regexp/datepattern/optmization/OptimizedMatcher.java b/java-dates/src/main/java/com/baeldung/regexp/datepattern/optmization/OptimizedMatcher.java new file mode 100644 index 0000000000..ccae942dcc --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/regexp/datepattern/optmization/OptimizedMatcher.java @@ -0,0 +1,6 @@ +package com.baeldung.regexp.datepattern.optmization; + +public class OptimizedMatcher { + + +} diff --git a/core-java-8/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java b/java-dates/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java rename to java-dates/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java diff --git a/core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplay.java b/java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplay.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplay.java rename to java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplay.java diff --git a/core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayApp.java b/java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayApp.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayApp.java rename to java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayApp.java diff --git a/core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7.java b/java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7.java similarity index 100% rename from core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7.java rename to java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7.java diff --git a/core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7App.java b/java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7App.java similarity index 100% rename from core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7App.java rename to java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7App.java diff --git a/java-dates/src/main/resources/logback.xml b/java-dates/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-dates/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/date/DateDiffUnitTest.java b/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/date/DateDiffUnitTest.java rename to java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java new file mode 100644 index 0000000000..63a4395a38 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.date; + +import org.junit.Assert; +import org.junit.Test; + +import java.text.ParseException; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.Calendar; +import java.util.Date; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +public class DateWithoutTimeUnitTest { + + private static final long MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000; + + @Test + public void whenGettingDateWithoutTimeUsingCalendar_thenReturnDateWithoutTime() { + Date dateWithoutTime = DateWithoutTime.getDateWithoutTimeUsingCalendar(); + + // first check the time is set to 0 + Calendar calendar = Calendar.getInstance(); + calendar.setTime(dateWithoutTime); + + assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + assertEquals(0, calendar.get(Calendar.MINUTE)); + assertEquals(0, calendar.get(Calendar.SECOND)); + assertEquals(0, calendar.get(Calendar.MILLISECOND)); + + // we get the day of the date + int day = calendar.get(Calendar.DAY_OF_MONTH); + + // if we add the mills of one day minus 1 we should get the same day + calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY - 1); + assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH)); + + // if we add one full day in millis we should get a different day + calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY); + assertNotEquals(day, calendar.get(Calendar.DAY_OF_MONTH)); + } + + @Test + public void whenGettingDateWithoutTimeUsingFormat_thenReturnDateWithoutTime() throws ParseException { + Date dateWithoutTime = DateWithoutTime.getDateWithoutTimeUsingFormat(); + + // first check the time is set to 0 + Calendar calendar = Calendar.getInstance(); + calendar.setTime(dateWithoutTime); + + assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + assertEquals(0, calendar.get(Calendar.MINUTE)); + assertEquals(0, calendar.get(Calendar.SECOND)); + assertEquals(0, calendar.get(Calendar.MILLISECOND)); + + // we get the day of the date + int day = calendar.get(Calendar.DAY_OF_MONTH); + + // if we add the mills of one day minus 1 we should get the same day + calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY - 1); + assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH)); + + // if we add one full day in millis we should get a different day + calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY); + assertNotEquals(day, calendar.get(Calendar.DAY_OF_MONTH)); + } + + @Test + public void whenGettingLocalDate_thenReturnDateWithoutTime() { + // get the local date + LocalDate localDate = DateWithoutTime.getLocalDate(); + + // get the millis of our LocalDate + long millisLocalDate = localDate + .atStartOfDay() + .toInstant(OffsetDateTime + .now() + .getOffset()) + .toEpochMilli(); + + Calendar calendar = Calendar.getInstance(); + // if we add the millis of one day minus 1 we should get the same day + calendar.setTimeInMillis(millisLocalDate + MILLISECONDS_PER_DAY - 1); + assertEquals(localDate.getDayOfMonth(), calendar.get(Calendar.DAY_OF_MONTH)); + + // if we add one full day in millis we should get a different day + calendar.setTimeInMillis(millisLocalDate + MILLISECONDS_PER_DAY); + assertNotEquals(localDate.getDayOfMonth(), calendar.get(Calendar.DAY_OF_MONTH)); + } + +} diff --git a/java-dates/src/test/java/com/baeldung/date/StringToDateUnitTest.java b/java-dates/src/test/java/com/baeldung/date/StringToDateUnitTest.java new file mode 100644 index 0000000000..e07422a9c6 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/date/StringToDateUnitTest.java @@ -0,0 +1,141 @@ +package com.baeldung.date; + +import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Locale; + +import org.apache.commons.lang3.time.DateUtils; +import org.joda.time.DateTime; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +public class StringToDateUnitTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetCorrectLocalDate() { + LocalDate expectedLocalDate = LocalDate.of(2018, 05, 05); + + LocalDate date = LocalDate.parse("2018-05-05"); + + assertThat(date).isEqualTo(expectedLocalDate); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetCorrectLocalDateTime() { + LocalDateTime expectedLocalDateTime = LocalDateTime.of(2018, 05, 05, 11, 50, 55); + + LocalDateTime dateTime = LocalDateTime.parse("2018-05-05T11:50:55"); + + assertThat(dateTime).isEqualTo(expectedLocalDateTime); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetDateTimeParseException() { + thrown.expect(DateTimeParseException.class); + thrown.expectMessage("Text '2018-05-05' could not be parsed at index 10"); + + LocalDateTime.parse("2018-05-05"); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetCorrectZonedDateTime() { + LocalDateTime localDateTime = LocalDateTime.of(2015, 05, 05, 10, 15, 30); + ZonedDateTime expectedZonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("Europe/Paris")); + + ZonedDateTime zonedDateTime = ZonedDateTime.parse("2015-05-05T10:15:30+01:00[Europe/Paris]"); + + assertThat(zonedDateTime).isEqualTo(expectedZonedDateTime); + } + + @Test + public void givenDateString_whenConvertedToDateUsingFormatter_thenWeGetCorrectLocalDate() { + LocalDate expectedLocalDate = LocalDate.of(1959, 7, 9); + + String dateInString = "19590709"; + LocalDate date = LocalDate.parse(dateInString, DateTimeFormatter.BASIC_ISO_DATE); + + assertThat(date).isEqualTo(expectedLocalDate); + } + + @Test + public void givenDateString_whenConvertedToDateUsingCustomFormatter_thenWeGetCorrectLocalDate() { + LocalDate expectedLocalDate = LocalDate.of(1980, 05, 05); + + String dateInString = "Mon, 05 May 1980"; + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, d MMM yyyy", Locale.ENGLISH); + LocalDate dateTime = LocalDate.parse(dateInString, formatter); + + assertThat(dateTime).isEqualTo(expectedLocalDate); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetCorrectDate() throws ParseException { + SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH); + + String dateInString = "7-Jun-2013"; + Date date = formatter.parse(dateInString); + + assertDateIsCorrect(date); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetParseException() throws ParseException { + SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH); + + thrown.expect(ParseException.class); + thrown.expectMessage("Unparseable date: \"07/06/2013\""); + + String dateInString = "07/06/2013"; + formatter.parse(dateInString); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetCorrectJodaDateTime() { + org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss"); + + String dateInString = "07/06/2013 10:11:59"; + DateTime dateTime = DateTime.parse(dateInString, formatter); + + assertEquals("Day of Month should be 7: ", 7, dateTime.getDayOfMonth()); + assertEquals("Month should be: ", 6, dateTime.getMonthOfYear()); + assertEquals("Year should be: ", 2013, dateTime.getYear()); + + assertEquals("Hour of day should be: ", 10, dateTime.getHourOfDay()); + assertEquals("Minutes of hour should be: ", 11, dateTime.getMinuteOfHour()); + assertEquals("Seconds of minute should be: ", 59, dateTime.getSecondOfMinute()); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetCorrectDateTime() throws ParseException { + String dateInString = "07/06-2013"; + Date date = DateUtils.parseDate(dateInString, new String[] { "yyyy-MM-dd HH:mm:ss", "dd/MM-yyyy" }); + + assertDateIsCorrect(date); + } + + private void assertDateIsCorrect(Date date) { + Calendar calendar = new GregorianCalendar(Locale.ENGLISH); + calendar.setTime(date); + + assertEquals("Day of Month should be 7: ", 7, calendar.get(Calendar.DAY_OF_MONTH)); + assertEquals("Month should be: ", 5, calendar.get(Calendar.MONTH)); + assertEquals("Year should be: ", 2013, calendar.get(Calendar.YEAR)); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/dateapi/ConversionExample.java b/java-dates/src/test/java/com/baeldung/dateapi/ConversionExample.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/dateapi/ConversionExample.java rename to java-dates/src/test/java/com/baeldung/dateapi/ConversionExample.java diff --git a/core-java-8/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java b/java-dates/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java rename to java-dates/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java b/java-dates/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java rename to java-dates/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java rename to java-dates/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/datetime/AddHoursToDateUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/AddHoursToDateUnitTest.java new file mode 100644 index 0000000000..aa34367f30 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/AddHoursToDateUnitTest.java @@ -0,0 +1,116 @@ +package com.baeldung.datetime; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.Month; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +import org.junit.Test; + +public class AddHoursToDateUnitTest { + + private final AddHoursToDate addHoursToDateObj = new AddHoursToDate(); + + @Test + public void givenJavaUtilDate_whenPositiveHours_thenAddHours() { + Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime(); + Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 7, 0).getTime(); + + assertThat(addHoursToDateObj.addHoursToJavaUtilDate(actualDate, 2)).isEqualTo(expectedDate); + } + + @Test + public void givenJavaUtilDate_whenNegativeHours_thenMinusHours() { + Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime(); + Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 3, 0).getTime(); + + assertThat(addHoursToDateObj.addHoursToJavaUtilDate(actualDate, -2)).isEqualTo(expectedDate); + } + + @Test + public void givenJavaUtilDate_whenUsingToInstantAndPostiveHours_thenAddHours() { + Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime(); + Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 7, 0).getTime(); + + assertThat(addHoursToDateObj.addHoursToDateUsingInstant(actualDate, 2)).isEqualTo(expectedDate); + } + + @Test + public void givenJavaUtilDate_whenUsingToInstantAndNegativeHours_thenAddHours() { + Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime(); + Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 3, 0).getTime(); + + assertThat(addHoursToDateObj.addHoursToDateUsingInstant(actualDate, -2)).isEqualTo(expectedDate); + } + + @Test + public void givenLocalDateTime_whenUsingAddHoursToLocalDateTime_thenAddHours() { + LocalDateTime actualDateTime = LocalDateTime.of(2018, Month.JUNE, 25, 5, 0); + LocalDateTime expectedDateTime = LocalDateTime.of(2018, Month.JUNE, 25, 7, 0); + + assertThat(addHoursToDateObj.addHoursToLocalDateTime(actualDateTime, 2)).isEqualTo(expectedDateTime); + } + + @Test + public void givenLocalDateTime_whenUsingMinusHoursToLocalDateTime_thenMinusHours() { + LocalDateTime actualDateTime = LocalDateTime.of(2018, Month.JUNE, 25, 5, 0); + LocalDateTime expectedDateTime = LocalDateTime.of(2018, Month.JUNE, 25, 3, 0); + + assertThat(addHoursToDateObj.subtractHoursToLocalDateTime(actualDateTime, 2)).isEqualTo(expectedDateTime); + } + + @Test + public void givenZonedDateTime_whenUsingAddHoursToZonedDateTime_thenAddHours() { + ZonedDateTime actualZonedDateTime = ZonedDateTime.of(LocalDateTime.of(2018, Month.JUNE, 25, 5, 0), ZoneId.systemDefault()); + ZonedDateTime expectedZonedDateTime = ZonedDateTime.of(LocalDateTime.of(2018, Month.JUNE, 25, 7, 0), ZoneId.systemDefault()); + + assertThat(addHoursToDateObj.addHoursToZonedDateTime(actualZonedDateTime, 2)).isEqualTo(expectedZonedDateTime); + } + + @Test + public void givenZonedDateTime_whenUsingMinusHoursToZonedDateTime_thenMinusHours() { + ZonedDateTime actualZonedDateTime = ZonedDateTime.of(LocalDateTime.of(2018, Month.JUNE, 25, 5, 0), ZoneId.systemDefault()); + ZonedDateTime expectedZonedDateTime = ZonedDateTime.of(LocalDateTime.of(2018, Month.JUNE, 25, 3, 0), ZoneId.systemDefault()); + + assertThat(addHoursToDateObj.subtractHoursToZonedDateTime(actualZonedDateTime, 2)).isEqualTo(expectedZonedDateTime); + } + + @Test + public void givenJavaUtilDate_whenUsingPositiveHrsAndAddHoursWithApacheCommons_thenAddHours() { + Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime(); + Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 7, 0).getTime(); + + assertThat(addHoursToDateObj.addHoursWithApacheCommons(actualDate, 2)).isEqualTo(expectedDate); + } + + @Test + public void givenJavaUtilDate_whenUsingNegativeHrsAndAddHoursWithApacheCommons_thenMinusHours() { + Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 7, 0).getTime(); + Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime(); + + assertThat(addHoursToDateObj.addHoursWithApacheCommons(actualDate, -2)).isEqualTo(expectedDate); + } + + @Test + public void givenInstant_whenUsingAddHoursToInstant_thenAddHours() { + Instant actualValue = Instant.parse("2018-06-25T05:12:35Z"); + Instant expectedValue = Instant.parse("2018-06-25T07:12:35Z"); + + assertThat(addHoursToDateObj.addHoursToInstant(actualValue, 2)).isEqualTo(expectedValue); + } + + @Test + public void givenInstant_whenUsingSubtractHoursToInstant_thenMinusHours() { + Instant actualValue = Instant.parse("2018-06-25T07:12:35Z"); + Instant expectedValue = Instant.parse("2018-06-25T05:12:35Z"); + + assertThat(addHoursToDateObj.subtractHoursToInstant(actualValue, 2)).isEqualTo(expectedValue); + } + +} diff --git a/java-dates/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java new file mode 100644 index 0000000000..3b1fcfa6c5 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java @@ -0,0 +1,45 @@ +package com.baeldung.datetime; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.junit.Before; +import org.junit.Test; + +public class DateExtractYearMonthDayIntegerValuesUnitTest { + + DateExtractYearMonthDayIntegerValues extractYearMonthDateIntegerValues = new DateExtractYearMonthDayIntegerValues(); + + Date date; + + @Before + public void setup() throws ParseException + { + date=new SimpleDateFormat("dd-MM-yyyy").parse("01-03-2018"); + } + + @Test + public void whenGetYear_thenCorrectYear() + { + int actualYear=extractYearMonthDateIntegerValues.getYear(date); + assertThat(actualYear,is(2018)); + } + + @Test + public void whenGetMonth_thenCorrectMonth() + { + int actualMonth=extractYearMonthDateIntegerValues.getMonth(date); + assertThat(actualMonth,is(02)); + } + + @Test + public void whenGetDay_thenCorrectDay() + { + int actualDayOfMonth=extractYearMonthDateIntegerValues.getDay(date); + assertThat(actualDayOfMonth,is(01)); + } +} diff --git a/java-dates/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java new file mode 100644 index 0000000000..05de6ed0b9 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.datetime; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.time.LocalDate; + +import org.junit.Test; + +public class LocalDateExtractYearMonthDayIntegerValuesUnitTest { + + LocalDateExtractYearMonthDayIntegerValues localDateExtractYearMonthDayIntegerValues=new LocalDateExtractYearMonthDayIntegerValues(); + + LocalDate localDate=LocalDate.parse("2007-12-03"); + + @Test + public void whenGetYear_thenCorrectYear() + { + int actualYear=localDateExtractYearMonthDayIntegerValues.getYear(localDate); + assertThat(actualYear,is(2007)); + } + + @Test + public void whenGetMonth_thenCorrectMonth() + { + int actualMonth=localDateExtractYearMonthDayIntegerValues.getMonth(localDate); + assertThat(actualMonth,is(12)); + } + + @Test + public void whenGetDay_thenCorrectDay() + { + int actualDayOfMonth=localDateExtractYearMonthDayIntegerValues.getDay(localDate); + assertThat(actualDayOfMonth,is(03)); + } +} diff --git a/java-dates/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java new file mode 100644 index 0000000000..70544ea970 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.datetime; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.time.LocalDateTime; + +import org.junit.Test; + +public class LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest { + + LocalDateTimeExtractYearMonthDayIntegerValues localDateTimeExtractYearMonthDayIntegerValues = new LocalDateTimeExtractYearMonthDayIntegerValues(); + + LocalDateTime localDateTime=LocalDateTime.parse("2007-12-03T10:15:30"); + + @Test + public void whenGetYear_thenCorrectYear() + { + int actualYear=localDateTimeExtractYearMonthDayIntegerValues.getYear(localDateTime); + assertThat(actualYear,is(2007)); + } + + @Test + public void whenGetMonth_thenCorrectMonth() + { + int actualMonth=localDateTimeExtractYearMonthDayIntegerValues.getMonth(localDateTime); + assertThat(actualMonth,is(12)); + } + + @Test + public void whenGetDay_thenCorrectDay() + { + int actualDayOfMonth=localDateTimeExtractYearMonthDayIntegerValues.getDay(localDateTime); + assertThat(actualDayOfMonth,is(03)); + } +} diff --git a/java-dates/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java new file mode 100644 index 0000000000..efb01c49a5 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.datetime; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.time.OffsetDateTime; + +import org.junit.Test; + +public class OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest { + + OffsetDateTimeExtractYearMonthDayIntegerValues offsetDateTimeExtractYearMonthDayIntegerValues = new OffsetDateTimeExtractYearMonthDayIntegerValues(); + + OffsetDateTime offsetDateTime=OffsetDateTime.parse("2007-12-03T10:15:30+01:00"); + + @Test + public void whenGetYear_thenCorrectYear() + { + int actualYear=offsetDateTimeExtractYearMonthDayIntegerValues.getYear(offsetDateTime); + assertThat(actualYear,is(2007)); + } + + @Test + public void whenGetMonth_thenCorrectMonth() + { + int actualMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getMonth(offsetDateTime); + assertThat(actualMonth,is(12)); + } + + @Test + public void whenGetDay_thenCorrectDay() + { + int actualDayOfMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getDay(offsetDateTime); + assertThat(actualDayOfMonth,is(03)); + } +} diff --git a/java-dates/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java new file mode 100644 index 0000000000..5709fc7209 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.datetime; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.Month; + +import org.junit.Test; + +public class UseLocalDateTimeUnitTest { + + UseLocalDateTime useLocalDateTime = new UseLocalDateTime(); + + @Test + public void givenString_whenUsingParse_thenLocalDateTime() { + assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30") + .toLocalDate()); + assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30") + .toLocalTime()); + } + + @Test + public void givenLocalDateTime_whenSettingEndOfDay_thenReturnLastMomentOfDay() { + LocalDateTime givenTimed = LocalDateTime.parse("2018-06-23T05:55:55"); + + LocalDateTime endOfDayFromGivenDirectly = useLocalDateTime.getEndOfDayFromLocalDateTimeDirectly(givenTimed); + LocalDateTime endOfDayFromGiven = useLocalDateTime.getEndOfDayFromLocalDateTime(givenTimed); + + assertThat(endOfDayFromGivenDirectly).isEqualTo(endOfDayFromGiven); + assertThat(endOfDayFromGivenDirectly.toLocalTime()).isEqualTo(LocalTime.MAX); + assertThat(endOfDayFromGivenDirectly.toString()).isEqualTo("2018-06-23T23:59:59.999999999"); + } +} diff --git a/java-dates/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java new file mode 100644 index 0000000000..bb9b60956d --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java @@ -0,0 +1,91 @@ +package com.baeldung.datetime; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; + +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; + +import org.junit.Test; + +public class UseLocalDateUnitTest { + + UseLocalDate useLocalDate = new UseLocalDate(); + + @Test + public void givenValues_whenUsingFactoryOf_thenLocalDate() { + assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10) + .toString()); + } + + @Test + public void givenString_whenUsingParse_thenLocalDate() { + assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10") + .toString()); + } + + @Test + public void whenUsingClock_thenLocalDate() { + assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock()); + } + + @Test + public void givenDate_whenUsingPlus_thenNextDay() { + assertEquals(LocalDate.now() + .plusDays(1), useLocalDate.getNextDay(LocalDate.now())); + } + + @Test + public void givenDate_whenUsingMinus_thenPreviousDay() { + assertEquals(LocalDate.now() + .minusDays(1), useLocalDate.getPreviousDay(LocalDate.now())); + } + + @Test + public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek() { + assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22"))); + } + + @Test + public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() { + assertEquals(1, useLocalDate.getFirstDayOfMonth() + .getDayOfMonth()); + } + + @Test + public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight() { + assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22"))); + } + + @Test + public void givenLocalDate_whenSettingStartOfDay_thenReturnMidnightInAllCases() { + LocalDate given = LocalDate.parse("2018-06-23"); + + LocalDateTime startOfDayWithMethod = useLocalDate.getStartOfDay(given); + LocalDateTime startOfDayOfLocalDate = useLocalDate.getStartOfDayOfLocalDate(given); + LocalDateTime startOfDayWithMin = useLocalDate.getStartOfDayAtMinTime(given); + LocalDateTime startOfDayWithMidnight = useLocalDate.getStartOfDayAtMidnightTime(given); + + assertThat(startOfDayWithMethod).isEqualTo(startOfDayWithMin) + .isEqualTo(startOfDayWithMidnight) + .isEqualTo(startOfDayOfLocalDate) + .isEqualTo(LocalDateTime.parse("2018-06-23T00:00:00")); + assertThat(startOfDayWithMin.toLocalTime()).isEqualTo(LocalTime.MIDNIGHT); + assertThat(startOfDayWithMin.toString()).isEqualTo("2018-06-23T00:00"); + } + + @Test + public void givenLocalDate_whenSettingEndOfDay_thenReturnLastMomentOfDay() { + LocalDate given = LocalDate.parse("2018-06-23"); + + LocalDateTime endOfDayWithMax = useLocalDate.getEndOfDay(given); + LocalDateTime endOfDayFromLocalTime = useLocalDate.getEndOfDayFromLocalTime(given); + + assertThat(endOfDayWithMax).isEqualTo(endOfDayFromLocalTime); + assertThat(endOfDayWithMax.toLocalTime()).isEqualTo(LocalTime.MAX); + assertThat(endOfDayWithMax.toString()).isEqualTo("2018-06-23T23:59:59.999999999"); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java rename to java-dates/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java rename to java-dates/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java new file mode 100644 index 0000000000..4423ac6ce0 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.datetime; + +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.junit.Assert; +import org.junit.Test; + +public class UseTimeZoneUnitTest { + + /* https://en.wikipedia.org/wiki/List_of_tz_database_time_zones */ + + String timeZone = "Asia/Singapore"; + + private static final String PATTERN = "E yyyy-MM-dd HH:mm:ss a"; + + @Test + public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJava7_ThenTimeZoneIsSetSuccessfully() { + Date nowUtc = new Date(); + TimeZone asiaSingapore = TimeZone.getTimeZone(timeZone); + + Calendar nowAsiaSingapore = Calendar.getInstance(asiaSingapore); + nowAsiaSingapore.setTime(nowUtc); + + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(PATTERN); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone)); + + System.out.println(String.format("Java7: Time now in '%s' is '%s'", nowAsiaSingapore.getTimeZone() + .getID(), simpleDateFormat.format(nowAsiaSingapore.getTime()))); + + Assert.assertEquals(nowUtc.toInstant().getEpochSecond(), nowAsiaSingapore.toInstant().getEpochSecond()); + Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getTimeZone()); + + } + + @Test + public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJava8_ThenTimeZoneIsSetSuccessfully() { + Instant nowUtc = Instant.now(); + ZoneId asiaSingapore = ZoneId.of(timeZone); + + ZonedDateTime nowAsiaSingapore = ZonedDateTime.ofInstant(nowUtc, asiaSingapore); + + System.out.println(String.format("Java8: Time now in '%s' is '%s'", nowAsiaSingapore.getZone(), + nowAsiaSingapore.format(DateTimeFormatter.ofPattern(PATTERN)))); + + Assert.assertEquals(nowUtc.getEpochSecond(), nowAsiaSingapore.toEpochSecond()); + Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getZone()); + } + + @Test + public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJodaTime_ThenTimeZoneIsSetSuccessfully() { + org.joda.time.Instant nowUtc = org.joda.time.Instant.now(); + DateTimeZone asiaSingapore = DateTimeZone.forID(timeZone); + + DateTime nowAsiaSingapore = nowUtc.toDateTime(asiaSingapore); + + System.out.println(String.format("Joda-time: Time now in '%s' is '%s'", nowAsiaSingapore.getZone(), + nowAsiaSingapore.toString(PATTERN))); + + Assert.assertEquals(nowUtc.toInstant().getMillis(), nowAsiaSingapore.toInstant().getMillis()); + Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getZone()); + } + +} diff --git a/java-dates/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java new file mode 100644 index 0000000000..f9b4008888 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java @@ -0,0 +1,45 @@ +package com.baeldung.datetime; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; + +import org.junit.Assert; +import org.junit.Test; + +public class UseZonedDateTimeUnitTest { + + UseZonedDateTime zonedDateTime = new UseZonedDateTime(); + + @Test + public void givenZoneId_thenZonedDateTime() { + ZoneId zoneId = ZoneId.of("Europe/Paris"); + ZonedDateTime zonedDatetime = zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId); + Assert.assertEquals(zoneId, ZoneId.from(zonedDatetime)); + } + + @Test + public void givenLocalDateOrZoned_whenSettingStartOfDay_thenReturnMidnightInAllCases() { + LocalDate given = LocalDate.parse("2018-06-23"); + ZoneId zone = ZoneId.of("Europe/Paris"); + ZonedDateTime zonedGiven = ZonedDateTime.of(given, LocalTime.NOON, zone); + + ZonedDateTime startOfOfDayWithMethod = zonedDateTime.getStartOfDay(given, zone); + ZonedDateTime startOfOfDayWithShorthandMethod = zonedDateTime.getStartOfDayShorthand(given, zone); + ZonedDateTime startOfOfDayFromZonedDateTime = zonedDateTime.getStartOfDayFromZonedDateTime(zonedGiven); + ZonedDateTime startOfOfDayAtMinTime = zonedDateTime.getStartOfDayAtMinTime(zonedGiven); + ZonedDateTime startOfOfDayAtMidnightTime = zonedDateTime.getStartOfDayAtMidnightTime(zonedGiven); + + assertThat(startOfOfDayWithMethod).isEqualTo(startOfOfDayWithShorthandMethod) + .isEqualTo(startOfOfDayFromZonedDateTime) + .isEqualTo(startOfOfDayAtMinTime) + .isEqualTo(startOfOfDayAtMidnightTime); + assertThat(startOfOfDayWithMethod.toLocalTime()).isEqualTo(LocalTime.MIDNIGHT); + assertThat(startOfOfDayWithMethod.toLocalTime() + .toString()).isEqualTo("00:00"); + } +} diff --git a/java-dates/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java new file mode 100644 index 0000000000..a9ed3d2b74 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.datetime; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.time.ZonedDateTime; + +import org.junit.Test; + +public class ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest { + + ZonedDateTimeExtractYearMonthDayIntegerValues zonedDateTimeExtractYearMonthDayIntegerValues = new ZonedDateTimeExtractYearMonthDayIntegerValues(); + + ZonedDateTime zonedDateTime=ZonedDateTime.parse("2007-12-03T10:15:30+01:00"); + + @Test + public void whenGetYear_thenCorrectYear() + { + int actualYear=zonedDateTimeExtractYearMonthDayIntegerValues.getYear(zonedDateTime); + assertThat(actualYear,is(2007)); + } + + @Test + public void whenGetMonth_thenCorrectMonth() + { + int actualMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getMonth(zonedDateTime); + assertThat(actualMonth,is(12)); + } + + @Test + public void whenGetDay_thenCorrectDay() + { + int actualDayOfMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getDay(zonedDateTime); + assertThat(actualDayOfMonth,is(03)); + } +} diff --git a/java-dates/src/test/java/com/baeldung/datetime/modify/DateIncrementerUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/modify/DateIncrementerUnitTest.java new file mode 100644 index 0000000000..e384bf4254 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/modify/DateIncrementerUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.datetime.modify; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class DateIncrementerUnitTest { + private final static String DATE_TO_INCREMENT = "2018-07-03"; + private final static String EXPECTED_DATE = "2018-07-04"; + + @Test + public void givenDate_whenUsingJava8_thenAddOneDay() throws Exception { + String incrementedDate = DateIncrementer.addOneDay(DATE_TO_INCREMENT); + assertEquals(EXPECTED_DATE, incrementedDate); + } + + @Test + public void givenDate_whenUsingJodaTime_thenAddOneDay() throws Exception { + String incrementedDate = DateIncrementer.addOneDayJodaTime(DATE_TO_INCREMENT); + assertEquals(EXPECTED_DATE, incrementedDate); + } + + @Test + public void givenDate_whenUsingCalendar_thenAddOneDay() throws Exception { + String incrementedDate = DateIncrementer.addOneDayCalendar(DATE_TO_INCREMENT); + assertEquals(EXPECTED_DATE, incrementedDate); + } + + @Test + public void givenDate_whenUsingApacheCommons_thenAddOneDay() throws Exception { + String incrementedDate = DateIncrementer.addOneDayApacheCommons(DATE_TO_INCREMENT); + assertEquals(EXPECTED_DATE, incrementedDate); + } +} diff --git a/java-dates/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java b/java-dates/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java new file mode 100644 index 0000000000..77b38419a9 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java @@ -0,0 +1,69 @@ +package com.baeldung.dst; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Ignore; +import org.junit.Test; + +public class DaylightSavingTimeExamplesUnitTest { + + @Test + public void givenItalianTimeZone_WhenDSTHappens_ThenCorrectlyShiftTimeZone() throws ParseException { + TimeZone.setDefault(TimeZone.getTimeZone("Europe/Rome")); + + TimeZone tz = TimeZone.getTimeZone("Europe/Rome"); + Calendar cal = Calendar.getInstance(tz, Locale.ITALIAN); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ITALIAN); + Date dateBeforeDST = df.parse("2018-03-25 01:55"); + prettyPrint(cal.getTimeZone()); + + cal.setTime(dateBeforeDST); + System.out.println("Before DST (00:55 UTC - 01:55 GMT+1) = " + dateBeforeDST); + + System.out.println("With this Calendar " + (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / (60 * 1000) + " minutes must be added to UTC (GMT TimeZone) to get a correct date for this TimeZone\n"); + assertThat(cal.get(Calendar.ZONE_OFFSET)).isEqualTo(3600000); + assertThat(cal.get(Calendar.DST_OFFSET)).isEqualTo(0); + + cal.add(Calendar.MINUTE, 10); + + Date dateAfterDST = cal.getTime(); + + System.out.println(" After DST (01:05 UTC - 03:05 GMT+2) = " + dateAfterDST); + System.out.println("With this Calendar " + (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / (60 * 1000) + " minutes must be added to UTC (GMT TimeZone) to get a correct date for this TimeZone\n"); + assertThat(cal.get(Calendar.DST_OFFSET)).isEqualTo(3600000); + assertThat(dateAfterDST).isEqualTo(df.parse("2018-03-25 03:05")); + + Long deltaBetweenDatesInMillis = dateAfterDST.getTime() - dateBeforeDST.getTime(); + Long tenMinutesInMillis = (1000L * 60 * 10); + assertThat(deltaBetweenDatesInMillis).isEqualTo(tenMinutesInMillis); + } + + private void prettyPrint(TimeZone tz) { + + //@formatter:off + System.out.println(String.format( + " Zone ID = %s (%s)\n" + + " RawOffset = %s minutes\n" + + " DST = %s minutes\n" + + " -----------------------------------------", + tz.getID(), tz.getDisplayName(), tz.getRawOffset()/60000, tz.getDSTSavings()/60000)); + //@formatter:on + } + + @Test + @Ignore + public void whenIterating_ThenPrintAllTimeZones() { + for (String id : TimeZone.getAvailableIDs()) { + TimeZone tz = TimeZone.getTimeZone(id); + prettyPrint(tz); + } + } +} diff --git a/java-dates/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java b/java-dates/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java new file mode 100644 index 0000000000..07ab859e09 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.dst; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.text.ParseException; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.temporal.ChronoUnit; +import java.util.TimeZone; + +import org.junit.Test; + +public class DaylightSavingTimeJavaTimeExamplesUnitTest { + + @Test + public void givenItalianTimeZone_WhenDSTHappens_ThenCorrectlyShiftTimeZone() throws ParseException { + ZoneId italianZoneId = ZoneId.of("Europe/Rome"); + + LocalDateTime localDateTimeBeforeDST = LocalDateTime.of(2018, 3, 25, 1, 55); + System.out.println(localDateTimeBeforeDST); + assertThat(localDateTimeBeforeDST.toString()).isEqualTo("2018-03-25T01:55"); + + ZonedDateTime zonedDateTimeBeforeDST = localDateTimeBeforeDST.atZone(italianZoneId); + prettyPrint(zonedDateTimeBeforeDST); + assertThat(zonedDateTimeBeforeDST.toString()).isEqualTo("2018-03-25T01:55+01:00[Europe/Rome]"); + + ZonedDateTime zonedDateTimeAfterDST = zonedDateTimeBeforeDST.plus(10, ChronoUnit.MINUTES); + prettyPrint(zonedDateTimeAfterDST); + assertThat(zonedDateTimeAfterDST.toString()).isEqualTo("2018-03-25T03:05+02:00[Europe/Rome]"); + + Long deltaBetweenDatesInMinutes = ChronoUnit.MINUTES.between(zonedDateTimeBeforeDST, zonedDateTimeAfterDST); + assertThat(deltaBetweenDatesInMinutes).isEqualTo(10); + + } + + private void prettyPrint(ZonedDateTime zdt) { + //@formatter:off + System.out.println(String.format( + " ZonedDateTime = %s\n" + + " Zone ID = %s (%s)\n" + + " RawOffset = %s minutes\n" + + " -----------------------------------------", + zdt, zdt.getZone(), zdt.getZone().getId(), zdt.getOffset().getTotalSeconds()/60)); + //@formatter:on + } + + @Test + public void whenCounting_ThenPrintDifferencesBetweenAPIs() { + System.out.println("Total java.time.ZoneId count : " + ZoneId.getAvailableZoneIds() + .size()); + System.out.println("Total java.util.TimeZone Id count : " + TimeZone.getAvailableIDs().length); + } + + +} diff --git a/java-dates/src/test/java/com/baeldung/gregorian/calendar/GregorianCalendarTester.java b/java-dates/src/test/java/com/baeldung/gregorian/calendar/GregorianCalendarTester.java new file mode 100644 index 0000000000..a1d084cf9a --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/gregorian/calendar/GregorianCalendarTester.java @@ -0,0 +1,228 @@ +package com.baeldung.gregorian.calendar; + +import static org.junit.Assert.*; + +import java.time.format.DateTimeFormatter; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Locale; +import java.util.TimeZone; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; + +import org.junit.Test; + +import com.baeldung.gregorian.calendar.GregorianCalendarExample; + +public class GregorianCalendarTester { + + @Test + public void test_Calendar_Return_Type_Valid() { + Calendar calendar = Calendar.getInstance(); + assert ("gregory".equals(calendar.getCalendarType())); + } + + @Test + public void test_Calendar_Return_Type_InValid() { + Calendar calendar = Calendar.getInstance(); + assertNotEquals("gregorys", calendar.getCalendarType()); + } + + @Test(expected = ClassCastException.class) + public void test_Class_Cast_Exception() { + TimeZone tz = TimeZone.getTimeZone("GMT+9:00"); + Locale loc = new Locale("ja", "JP", "JP"); + Calendar calendar = Calendar.getInstance(loc); + GregorianCalendar gc = (GregorianCalendar) calendar; + } + + @Test + public void test_Getting_Calendar_information() { + GregorianCalendar calendar = new GregorianCalendar(2018, 5, 28); + assertTrue(false == calendar.isLeapYear(calendar.YEAR)); + assertTrue(52 == calendar.getWeeksInWeekYear()); + assertTrue(2018 == calendar.getWeekYear()); + assertTrue(30 == calendar.getActualMaximum(calendar.DAY_OF_MONTH)); + assertTrue(1 == calendar.getActualMinimum(calendar.DAY_OF_MONTH)); + assertTrue(1 == calendar.getGreatestMinimum(calendar.DAY_OF_MONTH)); + assertTrue(28 == calendar.getLeastMaximum(calendar.DAY_OF_MONTH)); + assertTrue(31 == calendar.getMaximum(calendar.DAY_OF_MONTH)); + assertTrue(1 == calendar.getMinimum(calendar.DAY_OF_MONTH)); + assertTrue(52 == calendar.getWeeksInWeekYear()); + } + + @Test + public void test_Compare_Date_FirstDate_Greater_SecondDate() { + GregorianCalendar firstDate = new GregorianCalendar(2018, 6, 28); + GregorianCalendar secondDate = new GregorianCalendar(2018, 5, 28); + assertTrue(1 == firstDate.compareTo(secondDate)); + } + + + @Test + public void test_Compare_Date_FirstDate_Smaller_SecondDate() { + GregorianCalendar firstDate = new GregorianCalendar(2018, 5, 28); + GregorianCalendar secondDate = new GregorianCalendar(2018, 6, 28); + assertTrue(-1 == firstDate.compareTo(secondDate)); + } + + @Test + public void test_Compare_Date_Both_Dates_Equal() { + GregorianCalendar firstDate = new GregorianCalendar(2018, 6, 28); + GregorianCalendar secondDate = new GregorianCalendar(2018, 6, 28); + assertTrue(0 == firstDate.compareTo(secondDate)); + } + + @Test + public void test_date_format() { + GregorianCalendarExample calendarDemo = new GregorianCalendarExample(); + GregorianCalendar calendar = new GregorianCalendar(2018, 6, 28); + assertEquals("28 Jul 2018", calendarDemo.formatDate(calendar)); + } + + @Test + public void test_dateFormatdMMMuuuu() { + String expectedDate = new GregorianCalendar(2018, 6, 28).toZonedDateTime() + .format(DateTimeFormatter.ofPattern("d MMM uuuu")); + assertEquals("28 Jul 2018", expectedDate); + } + + @Test + public void test_addDays() { + GregorianCalendarExample calendarDemo = new GregorianCalendarExample(); + GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28); + GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28); + calendarExpected.add(Calendar.DATE, 1); + Date expectedDate = calendarExpected.getTime(); + assertEquals(expectedDate, calendarDemo.addDays(calendarActual, 1)); + } + + @Test + public void test_whenAddOneDay_thenMonthIsChanged() { + final int finalDay1 = 1; + final int finalMonthJul = 6; + GregorianCalendar calendarExpected = new GregorianCalendar(2018, 5, 30); + calendarExpected.add(Calendar.DATE, 1); + System.out.println(calendarExpected.getTime()); + assertEquals(calendarExpected.get(Calendar.DATE), finalDay1); + assertEquals(calendarExpected.get(Calendar.MONTH), finalMonthJul); + } + + @Test + public void test_whenSubtractOneDay_thenMonthIsChanged() { + final int finalDay31 = 31; + final int finalMonthMay = 4; + GregorianCalendar calendarExpected = new GregorianCalendar(2018, 5, 1); + calendarExpected.add(Calendar.DATE, -1); + assertEquals(calendarExpected.get(Calendar.DATE), finalDay31); + assertEquals(calendarExpected.get(Calendar.MONTH), finalMonthMay); + } + + @Test + public void test_subDays() { + GregorianCalendarExample calendarDemo = new GregorianCalendarExample(); + GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28); + GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28); + calendarExpected.add(Calendar.DATE, -1); + Date expectedDate = calendarExpected.getTime(); + assertEquals(expectedDate, calendarDemo.subtractDays(calendarActual, 1)); + } + + @Test + public void test_rollAdd() { + GregorianCalendarExample calendarDemo = new GregorianCalendarExample(); + GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28); + GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28); + calendarExpected.roll(Calendar.MONTH, 8); + Date expectedDate = calendarExpected.getTime(); + assertEquals(expectedDate, calendarDemo.rollAdd(calendarActual, 8)); + } + + @Test + public void test_whenRollUpOneMonth_thenYearIsUnchanged() { + final int rolledUpMonthJuly = 7, orginalYear2018 = 2018; + GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28); + calendarExpected.roll(Calendar.MONTH, 1); + assertEquals(calendarExpected.get(Calendar.MONTH), rolledUpMonthJuly); + assertEquals(calendarExpected.get(Calendar.YEAR), orginalYear2018); + } + + @Test + public void test_whenRollDownOneMonth_thenYearIsUnchanged() { + final int rolledDownMonthJune = 5, orginalYear2018 = 2018; + GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28); + calendarExpected.roll(Calendar.MONTH, -1); + assertEquals(calendarExpected.get(Calendar.MONTH), rolledDownMonthJune); + assertEquals(calendarExpected.get(Calendar.YEAR), orginalYear2018); + } + + @Test + public void test_rollSubtract() { + GregorianCalendarExample calendarDemo = new GregorianCalendarExample(); + GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28); + GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28); + calendarExpected.roll(Calendar.MONTH, -8); + Date expectedDate = calendarExpected.getTime(); + assertEquals(expectedDate, calendarDemo.rollAdd(calendarActual, -8)); + } + + @Test + public void test_setMonth() { + GregorianCalendarExample calendarDemo = new GregorianCalendarExample(); + GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28); + GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28); + calendarExpected.set(Calendar.MONTH, 3); + Date expectedDate = calendarExpected.getTime(); + assertEquals(expectedDate, calendarDemo.setMonth(calendarActual, 3)); + } + + @Test + public void test_setMonthApril() { + final int setMonthApril = 3, orginalYear2018 = 2018, originalDate28 = 28; + GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28); + calendarExpected.set(Calendar.MONTH, 3); + assertEquals(calendarExpected.get(Calendar.MONTH), setMonthApril); + assertEquals(calendarExpected.get(Calendar.YEAR), orginalYear2018); + assertEquals(calendarExpected.get(Calendar.DATE), originalDate28); + } + + @Test + public void test_toXMLGregorianCalendar() throws DatatypeConfigurationException { + GregorianCalendarExample calendarDemo = new GregorianCalendarExample(); + DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); + GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28); + GregorianCalendar calendarExpected = new GregorianCalendar(2018, 6, 28); + XMLGregorianCalendar expectedXMLGregorianCalendar = datatypeFactory + .newXMLGregorianCalendar(calendarExpected); + assertEquals(expectedXMLGregorianCalendar, + calendarDemo.toXMLGregorianCalendar(calendarActual)); + } + + @Test + public void test_isLeapYear_True() { + GregorianCalendarExample calendarDemo = new GregorianCalendarExample(); + assertEquals(true, calendarDemo.isLeapYearExample(2016)); + + } + + @Test + public void test_isLeapYear_False() { + GregorianCalendarExample calendarDemo = new GregorianCalendarExample(); + assertEquals(false, calendarDemo.isLeapYearExample(2018)); + + } + + @Test + public void test_toDate() throws DatatypeConfigurationException { + GregorianCalendar calendarActual = new GregorianCalendar(2018, 6, 28); + DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); + XMLGregorianCalendar expectedXMLGregorianCalendar = datatypeFactory + .newXMLGregorianCalendar(calendarActual); + expectedXMLGregorianCalendar.toGregorianCalendar().getTime(); + assertEquals(calendarActual.getTime(), + expectedXMLGregorianCalendar.toGregorianCalendar().getTime() ); + } +} diff --git a/java-dates/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterUnitTest.java b/java-dates/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterUnitTest.java new file mode 100644 index 0000000000..f7f07500f1 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterUnitTest.java @@ -0,0 +1,89 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDate; +import java.time.temporal.ChronoField; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +import com.baeldung.java9.datetime.DateToLocalDateConverter; + +/** + * JUnits for {@link DateToLocalDateConverter} class. + * + * @author abialas + * + */ +public class DateToLocalDateConverterUnitTest { + + @Test + public void shouldReturn10thNovember2010WhenConvertViaInstant() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10); + Date dateToConvert = calendar.getTime(); + + // when + LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaInstant(dateToConvert); + + // then + assertEquals(2010, localDate.get(ChronoField.YEAR)); + assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertViaMiliseconds() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10); + Date dateToConvert = calendar.getTime(); + + // when + LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaMilisecond(dateToConvert); + + // then + assertEquals(2010, localDate.get(ChronoField.YEAR)); + assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertViaSqlDate() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10); + Date dateToConvert = calendar.getTime(); + + // when + LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaSqlDate(dateToConvert); + + // then + assertEquals(2010, localDate.get(ChronoField.YEAR)); + assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertToLocalDate() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10); + Date dateToConvert = calendar.getTime(); + + // when + LocalDate localDateTime = DateToLocalDateConverter.convertToLocalDate(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + } + +} diff --git a/java-dates/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterUnitTest.java b/java-dates/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterUnitTest.java new file mode 100644 index 0000000000..9ad29ea673 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterUnitTest.java @@ -0,0 +1,97 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDateTime; +import java.time.temporal.ChronoField; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +import com.baeldung.java9.datetime.DateToLocalDateTimeConverter; + +/** + * JUnits for {@link DateToLocalDateTimeConverter} class. + * + * @author abialas + * + */ +public class DateToLocalDateTimeConverterUnitTest { + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10, 8, 20); + Date dateToConvert = calendar.getTime(); + + // when + LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaInstant(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); + assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); + } + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaMiliseconds() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10, 8, 20); + Date dateToConvert = calendar.getTime(); + + // when + LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaMilisecond(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); + assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); + } + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaSqlTimestamp() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10, 8, 20); + Date dateToConvert = calendar.getTime(); + + // when + LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaSqlTimestamp(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); + assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); + } + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertToLocalDateTime() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10, 8, 20); + Date dateToConvert = calendar.getTime(); + + // when + LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTime(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); + assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); + } + +} diff --git a/java-dates/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterUnitTest.java b/java-dates/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterUnitTest.java new file mode 100644 index 0000000000..e5a541c546 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterUnitTest.java @@ -0,0 +1,61 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDateTime; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +/** + * + * JUnits for {@link LocalDateTimeToDateConverter} class. + * + * @author abialas + * + */ +public class LocalDateTimeToDateConverterUnitTest { + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() { + // given + LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20); + + // when + Date date = LocalDateTimeToDateConverter.convertToDateViaInstant(dateToConvert); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + // then + assertEquals(2010, calendar.get(Calendar.YEAR)); + assertEquals(10, calendar.get(Calendar.MONTH)); + assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); + assertEquals(8, calendar.get(Calendar.HOUR)); + assertEquals(20, calendar.get(Calendar.MINUTE)); + assertEquals(0, calendar.get(Calendar.SECOND)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertViaSqlTimestamp() { + // given + LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20); + + // when + Date date = LocalDateTimeToDateConverter.convertToDateViaSqlTimestamp(dateToConvert); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + // then + assertEquals(2010, calendar.get(Calendar.YEAR)); + assertEquals(10, calendar.get(Calendar.MONTH)); + assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); + assertEquals(8, calendar.get(Calendar.HOUR)); + assertEquals(20, calendar.get(Calendar.MINUTE)); + assertEquals(0, calendar.get(Calendar.SECOND)); + } + +} diff --git a/java-dates/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterUnitTest.java b/java-dates/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterUnitTest.java new file mode 100644 index 0000000000..4e4dd20f2f --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterUnitTest.java @@ -0,0 +1,55 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDate; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +/** + * + * JUnits for {@link LocalDateToDateConverter} class. + * + * @author abialas + * + */ +public class LocalDateToDateConverterUnitTest { + + @Test + public void shouldReturn10thNovember2010WhenConvertViaInstant() { + // given + LocalDate dateToConvert = LocalDate.of(2010, 11, 10); + + // when + Date date = LocalDateToDateConverter.convertToDateViaInstant(dateToConvert); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + // then + assertEquals(2010, calendar.get(Calendar.YEAR)); + assertEquals(10, calendar.get(Calendar.MONTH)); + assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertViaSqlDate() { + // given + LocalDate dateToConvert = LocalDate.of(2010, 11, 10); + + // when + Date date = LocalDateToDateConverter.convertToDateViaSqlDate(dateToConvert); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + // then + assertEquals(2010, calendar.get(Calendar.YEAR)); + assertEquals(10, calendar.get(Calendar.MONTH)); + assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); + } + +} diff --git a/java-dates/src/test/java/com/baeldung/java9/time/TimeApiUnitTest.java b/java-dates/src/test/java/com/baeldung/java9/time/TimeApiUnitTest.java new file mode 100644 index 0000000000..8813870c2b --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/java9/time/TimeApiUnitTest.java @@ -0,0 +1,58 @@ +package com.baeldung.java9.time; + +import java.time.LocalDate; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; + +public class TimeApiUnitTest { + + @Test + public void givenGetDatesBetweenWithUsingJava7_WhenStartEndDate_thenDatesList() { + Date startDate = Calendar.getInstance().getTime(); + Calendar endCalendar = Calendar.getInstance(); + endCalendar.add(Calendar.DATE, 2); + Date endDate = endCalendar.getTime(); + + List dates = TimeApi.getDatesBetweenUsingJava7(startDate, endDate); + assertEquals(dates.size(), 2); + + Calendar calendar = Calendar.getInstance(); + Date date1 = calendar.getTime(); + assertEquals(dates.get(0).getDay(), date1.getDay()); + assertEquals(dates.get(0).getMonth(), date1.getMonth()); + assertEquals(dates.get(0).getYear(), date1.getYear()); + + calendar.add(Calendar.DATE, 1); + Date date2 = calendar.getTime(); + assertEquals(dates.get(1).getDay(), date2.getDay()); + assertEquals(dates.get(1).getMonth(), date2.getMonth()); + assertEquals(dates.get(1).getYear(), date2.getYear()); + } + + @Test + public void givenGetDatesBetweenWithUsingJava8_WhenStartEndDate_thenDatesList() { + LocalDate startDate = LocalDate.now(); + LocalDate endDate = LocalDate.now().plusDays(2); + + List dates = TimeApi.getDatesBetweenUsingJava8(startDate, endDate); + assertEquals(dates.size(), 2); + assertEquals(dates.get(0), LocalDate.now()); + assertEquals(dates.get(1), LocalDate.now().plusDays(1)); + } + + @Test + public void givenGetDatesBetweenWithUsingJava9_WhenStartEndDate_thenDatesList() { + LocalDate startDate = LocalDate.now(); + LocalDate endDate = LocalDate.now().plusDays(2); + + List dates = TimeApi.getDatesBetweenUsingJava9(startDate, endDate); + assertEquals(dates.size(), 2); + assertEquals(dates.get(0), LocalDate.now()); + assertEquals(dates.get(1), LocalDate.now().plusDays(1)); + } + +} diff --git a/java-dates/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java new file mode 100644 index 0000000000..c2340e9528 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java @@ -0,0 +1,186 @@ +package com.baeldung.jodatime; + +import org.joda.time.*; +import org.joda.time.format.DateTimeFormat; +import org.joda.time.format.DateTimeFormatter; +import org.junit.Test; + +import java.util.Date; +import java.util.TimeZone; + +import static org.junit.Assert.*; + +public class JodaTimeUnitTest { + + @Test + public void testDateTimeRepresentation() { + + DateTimeZone.setDefault(DateTimeZone.forID("Europe/Bucharest")); + + // representing current date and time + LocalDate currentDate = LocalDate.now(); + LocalTime currentTime = LocalTime.now(); + LocalDateTime currentLocalDateTime = LocalDateTime.now(); + + LocalDateTime currentDateTimeFromJavaDate = new LocalDateTime(new Date()); + Date currentJavaDate = currentDateTimeFromJavaDate.toDate(); + + // representing custom date and time + Date oneMinuteAgoDate = new Date(System.currentTimeMillis() - (60 * 1000)); + Instant oneMinutesAgoInstant = new Instant(oneMinuteAgoDate); + + DateTime customDateTimeFromInstant = new DateTime(oneMinutesAgoInstant); + DateTime customDateTimeFromJavaDate = new DateTime(oneMinuteAgoDate); + DateTime customDateTimeFromString = new DateTime("2018-05-05T10:11:12.123"); + DateTime customDateTimeFromParts = new DateTime(2018, 5, 5, 10, 11, 12, 123); + + // parsing + DateTime parsedDateTime = DateTime.parse("2018-05-05T10:11:12.123"); + assertEquals("2018-05-05T10:11:12.123+03:00", parsedDateTime.toString()); + + DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss"); + DateTime parsedDateTimeUsingFormatter = DateTime.parse("05/05/2018 10:11:12", dateTimeFormatter); + assertEquals("2018-05-05T10:11:12.000+03:00", parsedDateTimeUsingFormatter.toString()); + + // Instant + Instant instant = new Instant(); + Instant.now(); + + Instant instantFromString = new Instant("2018-05-05T10:11:12"); + Instant instantFromDate = new Instant(oneMinuteAgoDate); + Instant instantFromTimestamp = new Instant(System.currentTimeMillis() - (60 * 1000)); + Instant parsedInstant = Instant.parse("05/05/2018 10:11:12", dateTimeFormatter); + + Instant instantNow = Instant.now(); + Instant oneMinuteAgoInstant = new Instant(oneMinuteAgoDate); + + // epochMilli and epochSecond + long milliesFromEpochTime = System.currentTimeMillis(); + long secondsFromEpochTime = milliesFromEpochTime / 1000; + Instant instantFromEpochMilli = Instant.ofEpochMilli(milliesFromEpochTime); + Instant instantFromEpocSeconds = Instant.ofEpochSecond(secondsFromEpochTime); + + // convert Instants + DateTime dateTimeFromInstant = instant.toDateTime(); + Date javaDateFromInstant = instant.toDate(); + + int year = instant.get(DateTimeFieldType.year()); + int month = instant.get(DateTimeFieldType.monthOfYear()); + int day = instant.get(DateTimeFieldType.dayOfMonth()); + int hour = instant.get(DateTimeFieldType.hourOfDay()); + + // Duration, Period, Instant + long currentTimestamp = System.currentTimeMillis(); + long oneHourAgo = currentTimestamp - 24*60*1000; + + Duration duration = new Duration(oneHourAgo, currentTimestamp); + Instant.now().plus(duration); + + long durationInDays = duration.getStandardDays(); + long durationInHours = duration.getStandardHours(); + long durationInMinutes = duration.getStandardMinutes(); + long durationInSeconds = duration.getStandardSeconds(); + long durationInMilli = duration.getMillis(); + + // converting between classes + DateTimeUtils.setCurrentMillisFixed(currentTimestamp); + LocalDateTime currentDateAndTime = LocalDateTime.now(); + + assertEquals(new DateTime(currentTimestamp), currentDateAndTime.toDateTime()); + assertEquals(new LocalDate(currentTimestamp), currentDateAndTime.toLocalDate()); + assertEquals(new LocalTime(currentTimestamp), currentDateAndTime.toLocalTime()); + } + + @Test + public void testJodaInstant() { + + Date oneMinuteAgoDate = new Date(System.currentTimeMillis() - (60 * 1000)); + + Instant instantNow = Instant.now(); + Instant oneMinuteAgoInstant = new Instant(oneMinuteAgoDate); + + assertTrue(instantNow.compareTo(oneMinuteAgoInstant) > 0); + assertTrue(instantNow.isAfter(oneMinuteAgoInstant)); + assertTrue(oneMinuteAgoInstant.isBefore(instantNow)); + assertTrue(oneMinuteAgoInstant.isBeforeNow()); + assertFalse(oneMinuteAgoInstant.isEqual(instantNow)); + + LocalDateTime localDateTime = new LocalDateTime("2018-02-01"); + Period period = new Period().withMonths(1); + LocalDateTime datePlusPeriod = localDateTime.plus(period); + + Instant startInterval1 = new Instant("2018-05-05T09:00:00.000"); + Instant endInterval1 = new Instant("2018-05-05T11:00:00.000"); + Interval interval1 = new Interval(startInterval1, endInterval1); + + Instant startInterval2 = new Instant("2018-05-05T10:00:00.000"); + Instant endInterval2 = new Instant("2018-05-05T11:00:00.000"); + Interval interval2 = new Interval(startInterval2, endInterval2); + + Instant startInterval3 = new Instant("2018-05-05T11:00:00.000"); + Instant endInterval3 = new Instant("2018-05-05T13:00:00.000"); + Interval interval3 = new Interval(startInterval3, endInterval3); + + Interval overlappingInterval = interval1.overlap(interval2); + Interval notOverlappingInterval = interval1.overlap(interval3); + + assertTrue(overlappingInterval.isEqual(new Interval(new Instant("2018-05-05T10:00:00.000"), new Instant("2018-05-05T11:00:00.000")))); + assertNotNull(overlappingInterval); + + interval1.abuts(interval3); + assertTrue(interval1.abuts(new Interval(new Instant("2018-05-05T11:00:00.000"), new Instant("2018-05-05T13:00:00.000")))); + + interval1.gap(interval2); + } + + + @Test + public void testDateTimeOperations() { + + DateTimeUtils.setCurrentMillisFixed(1529612783288L); + DateTimeZone.setDefault(DateTimeZone.UTC); + + LocalDateTime currentLocalDateTime = LocalDateTime.now(); + assertEquals("2018-06-21T20:26:23.288", currentLocalDateTime.toString()); + + LocalDateTime nextDayDateTime = currentLocalDateTime.plusDays(1); + assertEquals("2018-06-22T20:26:23.288", nextDayDateTime.toString()); + + Period oneMonth = new Period().withMonths(1); + LocalDateTime nextMonthDateTime = currentLocalDateTime.plus(oneMonth); + assertEquals("2018-07-21T20:26:23.288", nextMonthDateTime.toString()); + + LocalDateTime previousDayLocalDateTime = currentLocalDateTime.minusDays(1); + assertEquals("2018-06-20T20:26:23.288", previousDayLocalDateTime.toString()); + + LocalDateTime currentDateAtHour10 = currentLocalDateTime + .withHourOfDay(0) + .withMinuteOfHour(0) + .withSecondOfMinute(0) + .withMillisOfSecond(0); + assertEquals("2018-06-21T00:00:00.000", currentDateAtHour10.toString()); + } + + @Test + public void testTimezones() { + + System.getProperty("user.timezone"); + DateTimeZone.getAvailableIDs(); + // DateTimeZone.setDefault(DateTimeZone.forID("Europe/Bucharest")); + + DateTimeUtils.setCurrentMillisFixed(1529612783288L); + + DateTime dateTimeInChicago = new DateTime(DateTimeZone.forID("America/Chicago")); + assertEquals("2018-06-21T15:26:23.288-05:00", dateTimeInChicago.toString()); + + DateTime dateTimeInBucharest = new DateTime(DateTimeZone.forID("Europe/Bucharest")); + assertEquals("2018-06-21T23:26:23.288+03:00", dateTimeInBucharest.toString()); + + LocalDateTime localDateTimeInChicago = new LocalDateTime(DateTimeZone.forID("America/Chicago")); + assertEquals("2018-06-21T15:26:23.288", localDateTimeInChicago.toString()); + + DateTime convertedDateTime = localDateTimeInChicago.toDateTime(DateTimeZone.forID("Europe/Bucharest")); + assertEquals("2018-06-21T15:26:23.288+03:00", convertedDateTime.toString()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/FormattedDateMatcherUnitTest.java b/java-dates/src/test/java/com/baeldung/regexp/datepattern/FormattedDateMatcherUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/regexp/datepattern/FormattedDateMatcherUnitTest.java rename to java-dates/src/test/java/com/baeldung/regexp/datepattern/FormattedDateMatcherUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/RangedDateMatcherUnitTest.java b/java-dates/src/test/java/com/baeldung/regexp/datepattern/RangedDateMatcherUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/regexp/datepattern/RangedDateMatcherUnitTest.java rename to java-dates/src/test/java/com/baeldung/regexp/datepattern/RangedDateMatcherUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcherUnitTest.java b/java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcherUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcherUnitTest.java rename to java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcherUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcherUnitTest.java b/java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcherUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcherUnitTest.java rename to java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcherUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcherUnitTest.java b/java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcherUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcherUnitTest.java rename to java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcherUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcherUnitTest.java b/java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcherUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcherUnitTest.java rename to java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcherUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcherUnitTest.java b/java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcherUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcherUnitTest.java rename to java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcherUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/testhelper/GregorianDateTestHelper.java b/java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/testhelper/GregorianDateTestHelper.java similarity index 100% rename from core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/testhelper/GregorianDateTestHelper.java rename to java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/testhelper/GregorianDateTestHelper.java diff --git a/java-dates/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java b/java-dates/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java new file mode 100644 index 0000000000..5ea0e840a2 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.temporaladjusters; + +import com.baeldung.temporaladjuster.CustomTemporalAdjuster; +import org.junit.Test; + +import java.time.LocalDate; +import java.time.Period; +import java.time.temporal.TemporalAdjuster; + +import static org.junit.Assert.assertEquals; + +public class CustomTemporalAdjusterUnitTest { + + private static final TemporalAdjuster NEXT_WORKING_DAY = new CustomTemporalAdjuster(); + + @Test + public void whenAdjustAndImplementInterface_thenNextWorkingDay() { + LocalDate localDate = LocalDate.of(2017, 07, 8); + CustomTemporalAdjuster temporalAdjuster = new CustomTemporalAdjuster(); + LocalDate nextWorkingDay = localDate.with(temporalAdjuster); + + assertEquals("2017-07-10", nextWorkingDay.toString()); + } + + @Test + public void whenAdjust_thenNextWorkingDay() { + LocalDate localDate = LocalDate.of(2017, 07, 8); + LocalDate date = localDate.with(NEXT_WORKING_DAY); + + assertEquals("2017-07-10", date.toString()); + } + + @Test + public void whenAdjust_thenFourteenDaysAfterDate() { + LocalDate localDate = LocalDate.of(2017, 07, 8); + TemporalAdjuster temporalAdjuster = (t) -> t.plus(Period.ofDays(14)); + LocalDate result = localDate.with(temporalAdjuster); + + String fourteenDaysAfterDate = "2017-07-22"; + + assertEquals(fourteenDaysAfterDate, result.toString()); + } +} \ No newline at end of file diff --git a/java-dates/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java b/java-dates/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java new file mode 100644 index 0000000000..175964dd21 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.temporaladjusters; + +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.time.temporal.TemporalAdjusters; + +import org.junit.Assert; +import org.junit.Test; + +public class TemporalAdjustersUnitTest { + + @Test + public void whenAdjust_thenNextSunday() { + LocalDate localDate = LocalDate.of(2017, 07, 8); + LocalDate nextSunday = localDate.with(TemporalAdjusters.next(DayOfWeek.SUNDAY)); + + String expected = "2017-07-09"; + + Assert.assertEquals(expected, nextSunday.toString()); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java rename to java-dates/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java diff --git a/out/production/main151/com/baeldung/.gitignore b/java-dates/src/test/resources/.gitignore similarity index 100% rename from out/production/main151/com/baeldung/.gitignore rename to java-dates/src/test/resources/.gitignore diff --git a/java-difference-date/pom.xml b/java-difference-date/pom.xml index ad66623581..8c87afc0a2 100644 --- a/java-difference-date/pom.xml +++ b/java-difference-date/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung java-difference-date @@ -26,16 +26,9 @@ hirondelle-date4j ${hirondelle-date4j.version}
    - - junit - junit - ${junit.version} - test - - 4.12 2.9.9 1.5.1 diff --git a/java-ee-8-security-api/README.md b/java-ee-8-security-api/README.md new file mode 100644 index 0000000000..1735419236 --- /dev/null +++ b/java-ee-8-security-api/README.md @@ -0,0 +1,3 @@ +### Relevant articles + + - [Java EE 8 Security API](http://www.baeldung.com/java-ee-8-security) diff --git a/java-ee-8-security-api/app-auth-basic-store-db/pom.xml b/java-ee-8-security-api/app-auth-basic-store-db/pom.xml new file mode 100644 index 0000000000..6ecc9f7e80 --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + + app-auth-basic-store-db + war + + + com.baeldung + java-ee-8-security-api + 1.0-SNAPSHOT + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy + package + + copy + + + + + + + com.h2database + h2 + ${h2-version} + jar + + ${project.build.directory}/liberty/wlp/usr/servers/defaultServer/lib/global + + + + + + + + + + 1.4.197 + + diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AdminServlet.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AdminServlet.java new file mode 100644 index 0000000000..32adbf1abb --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AdminServlet.java @@ -0,0 +1,22 @@ +package com.baeldung.javaee.security; + +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@WebServlet("/admin") +@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"admin_role"})) +public class AdminServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n"); + response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n"); + response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role")); + } +} \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AppConfig.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AppConfig.java new file mode 100644 index 0000000000..a16d944f5a --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AppConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition; +import javax.security.enterprise.authentication.mechanism.http.CustomFormAuthenticationMechanismDefinition; +import javax.security.enterprise.identitystore.DatabaseIdentityStoreDefinition; + +@BasicAuthenticationMechanismDefinition(realmName = "defaultRealm") +@DatabaseIdentityStoreDefinition( + dataSourceLookup = "java:comp/env/jdbc/securityDS", + callerQuery = "select password from users where username = ?", + groupsQuery = "select GROUPNAME from groups where username = ?" +) +@ApplicationScoped +public class AppConfig { +} diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/DatabaseSetupServlet.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/DatabaseSetupServlet.java new file mode 100644 index 0000000000..3658826e4d --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/DatabaseSetupServlet.java @@ -0,0 +1,59 @@ +package com.baeldung.javaee.security; + +import javax.annotation.Resource; +import javax.annotation.sql.DataSourceDefinition; +import javax.inject.Inject; +import javax.security.enterprise.identitystore.Pbkdf2PasswordHash; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +@DataSourceDefinition( + name = "java:comp/env/jdbc/securityDS", + className = "org.h2.jdbcx.JdbcDataSource", + url = "jdbc:h2:~/securityTest;MODE=Oracle" +) +@WebServlet(value = "/init", loadOnStartup = 0) +public class DatabaseSetupServlet extends HttpServlet { + + @Resource(lookup = "java:comp/env/jdbc/securityDS") + private DataSource dataSource; + + @Inject + private Pbkdf2PasswordHash passwordHash; + + @Override + public void init() throws ServletException { + super.init(); + initdb(); + } + + private void initdb() { + executeUpdate(dataSource, "DROP TABLE IF EXISTS USERS"); + executeUpdate(dataSource, "DROP TABLE IF EXISTS GROUPS"); + + executeUpdate(dataSource, "CREATE TABLE IF NOT EXISTS USERS(username VARCHAR(64) PRIMARY KEY, password VARCHAR(255))"); + executeUpdate(dataSource, "CREATE TABLE IF NOT EXISTS GROUPS(username VARCHAR(64), GROUPNAME VARCHAR(64))"); + + executeUpdate(dataSource, "INSERT INTO USERS VALUES('admin', '" + passwordHash.generate("passadmin".toCharArray()) + "')"); + executeUpdate(dataSource, "INSERT INTO USERS VALUES('user', '" + passwordHash.generate("passuser".toCharArray()) + "')"); + + executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('admin', 'admin_role')"); + executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('admin', 'user_role')"); + executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('user', 'user_role')"); + } + + private void executeUpdate(DataSource dataSource, String query) { + try (Connection connection = dataSource.getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(query)) { + statement.executeUpdate(); + } + } catch (SQLException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/UserServlet.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/UserServlet.java new file mode 100644 index 0000000000..548b5f6d85 --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/UserServlet.java @@ -0,0 +1,25 @@ +package com.baeldung.javaee.security; + +import javax.annotation.security.DeclareRoles; +import javax.inject.Inject; +import javax.security.enterprise.SecurityContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + + +@WebServlet("/user") +@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"user_role"})) +public class UserServlet extends HttpServlet { + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n"); + response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n"); + response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role")); + } +} diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/liberty/config/server.xml b/java-ee-8-security-api/app-auth-basic-store-db/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..c49adff459 --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/liberty/config/server.xml @@ -0,0 +1,9 @@ + + + + webProfile-8.0 + + + + diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/resources/logback.xml b/java-ee-8-security-api/app-auth-basic-store-db/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml new file mode 100644 index 0000000000..bf5315e993 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + + app-auth-custom-form-store-custom + war + + + com.baeldung + java-ee-8-security-api + 1.0-SNAPSHOT + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + + diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/AppConfig.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/AppConfig.java new file mode 100644 index 0000000000..bba9fa36ce --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/AppConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.faces.annotation.FacesConfig; +import javax.security.enterprise.authentication.mechanism.http.CustomFormAuthenticationMechanismDefinition; +import javax.security.enterprise.authentication.mechanism.http.LoginToContinue; + + +@CustomFormAuthenticationMechanismDefinition( + loginToContinue = @LoginToContinue( + loginPage = "/login.xhtml", + errorPage = "/login-error.html" + ) +) +@ApplicationScoped +public class AppConfig { +} diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authentication.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authentication.java new file mode 100644 index 0000000000..54219f9750 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authentication.java @@ -0,0 +1,46 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.security.enterprise.credential.UsernamePasswordCredential; +import javax.security.enterprise.identitystore.CredentialValidationResult; +import javax.security.enterprise.identitystore.IdentityStore; +import java.util.*; + +import static javax.security.enterprise.identitystore.CredentialValidationResult.INVALID_RESULT; + +@ApplicationScoped +public class InMemoryIdentityStore4Authentication implements IdentityStore { + + private Map users = new HashMap<>(); + + public InMemoryIdentityStore4Authentication() { + //Init users + // from a file or hardcoded + init(); + } + + private void init() { + //user1 + users.put("user", "pass0"); + //user2 + users.put("admin", "pass1"); + } + + @Override + public int priority() { + return 70; + } + + @Override + public Set validationTypes() { + return EnumSet.of(ValidationType.VALIDATE); + } + + public CredentialValidationResult validate(UsernamePasswordCredential credential) { + String password = users.get(credential.getCaller()); + if (password != null && password.equals(credential.getPasswordAsString())) { + return new CredentialValidationResult(credential.getCaller()); + } + return INVALID_RESULT; + } +} diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authorization.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authorization.java new file mode 100644 index 0000000000..f088ab80b9 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authorization.java @@ -0,0 +1,46 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.security.enterprise.identitystore.CredentialValidationResult; +import javax.security.enterprise.identitystore.IdentityStore; +import java.util.*; + +@ApplicationScoped +class InMemoryIdentityStore4Authorization implements IdentityStore { + + private Map> userRoles = new HashMap<>(); + + public InMemoryIdentityStore4Authorization() { + //Init users + // from a file or hardcoded + init(); + } + + private void init() { + //user1 + List roles = new ArrayList<>(); + roles.add("USER_ROLE"); + userRoles.put("user", roles); + //user2 + roles = new ArrayList<>(); + roles.add("USER_ROLE"); + roles.add("ADMIN_ROLE"); + userRoles.put("admin", roles); + } + + @Override + public int priority() { + return 80; + } + + @Override + public Set validationTypes() { + return EnumSet.of(ValidationType.PROVIDE_GROUPS); + } + + @Override + public Set getCallerGroups(CredentialValidationResult validationResult) { + List roles = userRoles.get(validationResult.getCallerPrincipal().getName()); + return new HashSet<>(roles); + } +} diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/LoginBean.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/LoginBean.java new file mode 100644 index 0000000000..f8ee83432a --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/LoginBean.java @@ -0,0 +1,81 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.RequestScoped; +import javax.faces.annotation.FacesConfig; +import javax.faces.application.FacesMessage; +import javax.faces.context.FacesContext; +import javax.inject.Inject; +import javax.inject.Named; +import javax.security.enterprise.AuthenticationStatus; +import javax.security.enterprise.SecurityContext; +import javax.security.enterprise.credential.Credential; +import javax.security.enterprise.credential.Password; +import javax.security.enterprise.credential.UsernamePasswordCredential; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.validation.constraints.NotNull; + +import static javax.faces.application.FacesMessage.SEVERITY_ERROR; +import static javax.security.enterprise.AuthenticationStatus.SEND_CONTINUE; +import static javax.security.enterprise.AuthenticationStatus.SEND_FAILURE; +import static javax.security.enterprise.authentication.mechanism.http.AuthenticationParameters.withParams; + +@FacesConfig +@Named +@RequestScoped +public class LoginBean { + + @Inject + private SecurityContext securityContext; + + @Inject + private FacesContext facesContext; + + @NotNull + private String username; + + @NotNull + private String password; + + public void login() { + Credential credential = new UsernamePasswordCredential(username, new Password(password)); + AuthenticationStatus status = securityContext.authenticate( + getHttpRequestFromFacesContext(), + getHttpResponseFromFacesContext(), + withParams().credential(credential)); + if (status.equals(SEND_CONTINUE)) { + facesContext.responseComplete(); + } else if (status.equals(SEND_FAILURE)) { + facesContext.addMessage(null, + new FacesMessage(SEVERITY_ERROR, "Authentication failed", null)); + } + } + + private HttpServletRequest getHttpRequestFromFacesContext() { + return (HttpServletRequest) facesContext + .getExternalContext() + .getRequest(); + } + + private HttpServletResponse getHttpResponseFromFacesContext() { + return (HttpServletResponse) facesContext + .getExternalContext() + .getResponse(); + } + + 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; + } +} diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/WelcomeServlet.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/WelcomeServlet.java new file mode 100644 index 0000000000..fb9c944140 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/WelcomeServlet.java @@ -0,0 +1,31 @@ +package com.baeldung.javaee.security; + +import javax.inject.Inject; +import javax.security.enterprise.SecurityContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@WebServlet("/welcome") +@ServletSecurity(@HttpConstraint(rolesAllowed = "USER_ROLE")) +public class WelcomeServlet extends HttpServlet { + + @Inject + private SecurityContext securityContext; + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + securityContext.hasAccessToWebResource("/protectedServlet", "GET"); + resp.getWriter().write("" + + "Authentication type :" + req.getAuthType() + "\n" + + "Caller Principal :" + securityContext.getCallerPrincipal() + "\n" + + "User in Role USER_ROLE :" + securityContext.isCallerInRole("USER_ROLE") + "\n" + + "User in Role ADMIN_ROLE :" + securityContext.isCallerInRole("ADMIN_ROLE") + "\n" + + ""); + } +} \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/liberty/config/server.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..c49adff459 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/liberty/config/server.xml @@ -0,0 +1,9 @@ + + + + webProfile-8.0 + + + + diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/resources/logback.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/beans.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 0000000000..2f4726a77e --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,7 @@ + + + diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/web.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..bd219bf983 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,27 @@ + + + + + javax.faces.validator.ENABLE_VALIDATE_WHOLE_BEAN + true + + + + javax.faces.ENABLE_CDI_RESOLVER_CHAIN + true + + + + Faces Servlet + javax.faces.webapp.FacesServlet + 1 + + + Faces Servlet + *.xhtml + + + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login-error.html b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login-error.html new file mode 100644 index 0000000000..c540797b54 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login-error.html @@ -0,0 +1,10 @@ + + + + + Title + + +Custom Form Authentication Error + + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login.xhtml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login.xhtml new file mode 100644 index 0000000000..48928b2513 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login.xhtml @@ -0,0 +1,32 @@ + + + + + + + +

    + Custom Form-based Authentication +

    + +
    +

    + Username + +

    +

    + Password + +

    +

    + +

    +
    + + + + diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/welcome.xhtml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/welcome.xhtml new file mode 100644 index 0000000000..d1a18db626 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/welcome.xhtml @@ -0,0 +1,19 @@ + + + + + + + +

    + Welcome !! +

    + + + + diff --git a/java-ee-8-security-api/app-auth-custom-no-store/pom.xml b/java-ee-8-security-api/app-auth-custom-no-store/pom.xml new file mode 100644 index 0000000000..c05c0f19be --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + + app-auth-custom-no-store + war + + + com.baeldung + java-ee-8-security-api + 1.0-SNAPSHOT + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy + package + + copy + + + + + + + com.h2database + h2 + ${h2-version} + jar + + ${project.build.directory}/liberty/wlp/usr/servers/defaultServer/lib/global + + + + + + + + + + 1.4.197 + + diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AdminServlet.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AdminServlet.java new file mode 100644 index 0000000000..bef9e20038 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AdminServlet.java @@ -0,0 +1,28 @@ +package com.baeldung.javaee.security; + +import javax.inject.Inject; +import javax.security.enterprise.SecurityContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.security.Principal; + +@WebServlet("/admin") +@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"admin_role"})) +public class AdminServlet extends HttpServlet { + + @Inject + SecurityContext securityContext; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.getWriter().append("getCallerPrincipal :" + securityContext.getCallerPrincipal() + "\n"); + response.getWriter().append("CustomPrincipal :" + securityContext.getPrincipalsByType(CustomPrincipal.class) + "\n"); + response.getWriter().append("Principal :" + securityContext.getPrincipalsByType(Principal.class) + "\n"); + } +} \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AppConfig.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AppConfig.java new file mode 100644 index 0000000000..e93360db4d --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AppConfig.java @@ -0,0 +1,7 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; + +@ApplicationScoped +public class AppConfig { +} diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomAuthentication.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomAuthentication.java new file mode 100644 index 0000000000..9accf3c752 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomAuthentication.java @@ -0,0 +1,36 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.security.enterprise.AuthenticationException; +import javax.security.enterprise.AuthenticationStatus; +import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism; +import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.HashSet; + +@ApplicationScoped +public class CustomAuthentication implements HttpAuthenticationMechanism { + + @Override + public AuthenticationStatus validateRequest(HttpServletRequest httpServletRequest, + HttpServletResponse httpServletResponse, + HttpMessageContext httpMessageContext) throws AuthenticationException { + String username = httpServletRequest.getParameter("username"); + String password = httpServletRequest.getParameter("password"); + //Mocking UserDetail, but in real life, we can find it from a database. + UserDetail userDetail = findByUserNameAndPassword(username, password); + if (userDetail != null) { + return httpMessageContext.notifyContainerAboutLogin( + new CustomPrincipal(userDetail), + new HashSet<>(userDetail.getRoles())); + } + return httpMessageContext.responseUnauthorized(); + } + + private UserDetail findByUserNameAndPassword(String username, String password) { + UserDetail userDetail = new UserDetail("uid_10", username, password); + userDetail.addRole("admin_role"); + return userDetail; + } +} diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomPrincipal.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomPrincipal.java new file mode 100644 index 0000000000..5bd636ea62 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomPrincipal.java @@ -0,0 +1,22 @@ +package com.baeldung.javaee.security; + +import java.security.Principal; + +public class CustomPrincipal implements Principal { + + private UserDetail userDetail; + + public CustomPrincipal(UserDetail userDetail) { + this.userDetail = userDetail; + } + + @Override + public String getName() { + return userDetail.getLogin(); + } + + @Override + public String toString() { + return this.getClass().getSimpleName() + ":" + getName(); + } +} diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/UserDetail.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/UserDetail.java new file mode 100644 index 0000000000..68e1df33c8 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/UserDetail.java @@ -0,0 +1,38 @@ +package com.baeldung.javaee.security; + +import java.util.ArrayList; +import java.util.List; + +public class UserDetail { + private String uid; + private String login; + private String password; + private List roles = new ArrayList<>(); + //... + + UserDetail(String uid, String login, String password) { + this.uid = uid; + this.login = login; + this.password = password; + } + + public String getUid() { + return uid; + } + + public String getLogin() { + return login; + } + + public String getPassword() { + return password; + } + + public List getRoles() { + return roles; + } + + public void addRole(String role) { + roles.add(role); + } +} \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/liberty/config/server.xml b/java-ee-8-security-api/app-auth-custom-no-store/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..c49adff459 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/liberty/config/server.xml @@ -0,0 +1,9 @@ + + + + webProfile-8.0 + + + + diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/resources/logback.xml b/java-ee-8-security-api/app-auth-custom-no-store/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login-error.html b/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login-error.html new file mode 100644 index 0000000000..bd7263e0fb --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login-error.html @@ -0,0 +1,10 @@ + + + + + Title + + +Authentication Error + + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login.html b/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login.html new file mode 100644 index 0000000000..3336eb5513 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login.html @@ -0,0 +1,25 @@ + + + + + Title + + +

    + Form-based Authentication +

    +
    +

    + Username + +

    +

    + Password + +

    +

    + +

    +
    + + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml b/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml new file mode 100644 index 0000000000..570b36add5 --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + app-auth-form-store-ldap + war + + + com.baeldung + java-ee-8-security-api + 1.0-SNAPSHOT + + + + + com.unboundid + unboundid-ldapsdk + 4.0.4 + + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + + diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AdminServlet.java b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AdminServlet.java new file mode 100644 index 0000000000..32adbf1abb --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AdminServlet.java @@ -0,0 +1,22 @@ +package com.baeldung.javaee.security; + +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@WebServlet("/admin") +@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"admin_role"})) +public class AdminServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n"); + response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n"); + response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role")); + } +} \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AppConfig.java b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AppConfig.java new file mode 100644 index 0000000000..6fd9672e8a --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AppConfig.java @@ -0,0 +1,22 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition; +import javax.security.enterprise.authentication.mechanism.http.LoginToContinue; +import javax.security.enterprise.identitystore.LdapIdentityStoreDefinition; + +@FormAuthenticationMechanismDefinition( + loginToContinue = @LoginToContinue( + loginPage = "/login.html", + errorPage = "/login-error.html" + ) +) +@LdapIdentityStoreDefinition( + url = "ldap://localhost:10389", + callerBaseDn = "ou=caller,dc=baeldung,dc=com", + groupSearchBase = "ou=group,dc=baeldung,dc=com", + groupSearchFilter = "(&(member=%s)(objectClass=groupOfNames))" +) +@ApplicationScoped +public class AppConfig { +} diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/LdapSetupServlet.java b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/LdapSetupServlet.java new file mode 100644 index 0000000000..e55fe0d2a7 --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/LdapSetupServlet.java @@ -0,0 +1,45 @@ +package com.baeldung.javaee.security; + +import com.unboundid.ldap.listener.InMemoryDirectoryServer; +import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig; +import com.unboundid.ldap.listener.InMemoryListenerConfig; +import com.unboundid.ldap.sdk.LDAPException; +import com.unboundid.ldif.LDIFReader; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; + +@WebServlet(value = "/init-ldap", loadOnStartup = 1) +public class LdapSetupServlet extends HttpServlet { + + private InMemoryDirectoryServer inMemoryDirectoryServer; + + @Override + public void init() throws ServletException { + super.init(); + initLdap(); + System.out.println("@@@START_"); + } + + private void initLdap() { + try { + InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig("dc=baeldung,dc=com"); + config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("default", 10389)); + config.setSchema(null); + inMemoryDirectoryServer = new InMemoryDirectoryServer(config); + inMemoryDirectoryServer.importFromLDIF(true, + new LDIFReader(this.getClass().getResourceAsStream("/users.ldif"))); + inMemoryDirectoryServer.startListening(); + } catch (LDAPException e) { + e.printStackTrace(); + } + } + + @Override + public void destroy() { + super.destroy(); + inMemoryDirectoryServer.shutDown(true); + System.out.println("@@@END"); + } +} diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/UserServlet.java b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/UserServlet.java new file mode 100644 index 0000000000..9f14cd8817 --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/UserServlet.java @@ -0,0 +1,22 @@ +package com.baeldung.javaee.security; + +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + + +@WebServlet("/user") +@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"user_role"})) +public class UserServlet extends HttpServlet { + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n"); + response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n"); + response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role")); + } +} diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/liberty/config/server.xml b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..c49adff459 --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/liberty/config/server.xml @@ -0,0 +1,9 @@ + + + + webProfile-8.0 + + + + diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/resources/logback.xml b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/resources/users.ldif b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/resources/users.ldif new file mode 100644 index 0000000000..538249aab7 --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/resources/users.ldif @@ -0,0 +1,47 @@ +dn: dc=baeldung,dc=com +objectclass: top +objectclass: dcObject +objectclass: organization +dc: baeldung +o: baeldung + +dn: ou=caller,dc=baeldung,dc=com +objectclass: top +objectclass: organizationalUnit +ou: caller + +dn: ou=group,dc=baeldung,dc=com +objectclass: top +objectclass: organizationalUnit +ou: group + +dn: uid=admin,ou=caller,dc=baeldung,dc=com +objectclass: top +objectclass: uidObject +objectclass: person +uid: admin +cn: Administrator +sn: Admin +userPassword: passadmin + +dn: uid=user,ou=caller,dc=baeldung,dc=com +objectclass: top +objectclass: uidObject +objectclass: person +uid: user +cn: User +sn: User +userPassword: passuser + +dn: cn=admin_role,ou=group,dc=baeldung,dc=com +objectclass: top +objectclass: groupOfNames +cn: admin_role +member: uid=admin,ou=caller,dc=baeldung,dc=com + +dn: cn=user_role,ou=group,dc=baeldung,dc=com +objectclass: top +objectclass: groupOfNames +cn: user_role +member: uid=admin,ou=caller,dc=baeldung,dc=com +member: uid=user,ou=caller,dc=baeldung,dc=com diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login-error.html b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login-error.html new file mode 100644 index 0000000000..bd7263e0fb --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login-error.html @@ -0,0 +1,10 @@ + + + + + Title + + +Authentication Error + + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login.html b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login.html new file mode 100644 index 0000000000..3336eb5513 --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login.html @@ -0,0 +1,25 @@ + + + + + Title + + +

    + Form-based Authentication +

    +
    +

    + Username + +

    +

    + Password + +

    +

    + +

    +
    + + \ No newline at end of file diff --git a/java-ee-8-security-api/pom.xml b/java-ee-8-security-api/pom.xml new file mode 100644 index 0000000000..5490cd40f7 --- /dev/null +++ b/java-ee-8-security-api/pom.xml @@ -0,0 +1,78 @@ + + + 4.0.0 + com.baeldung + java-ee-8-security-api + 1.0-SNAPSHOT + pom + + + + + javax + javaee-web-api + ${javaee-version} + provided + + + + + + + + maven-war-plugin + ${maven-war-plugin.version} + + false + pom.xml + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + ${liberty-maven-plugin.version} + + + + https://public.dhe.ibm.com/ibmdl/export/pub/software/openliberty/runtime/nightly/2018-05-25_1422/openliberty-all-20180525-1300.zip + + + true + project + src/main/liberty/config/server.xml + true + + ${defaultHttpPort} + ${defaultHttpsPort} + + + + + + + + 1.8 + 1.8 + UTF-8 + + 9080 + 9443 + + 8.0 + 2.3 + 18.0.0.1 + 1.4.197 + + 3.2.2 + + + + app-auth-basic-store-db + app-auth-form-store-ldap + app-auth-custom-form-store-custom + app-auth-custom-no-store + + + diff --git a/java-lite/pom.xml b/java-lite/pom.xml index 7c0ed1c780..5111cd2e7f 100644 --- a/java-lite/pom.xml +++ b/java-lite/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung java-lite @@ -41,11 +41,6 @@ test - - junit - junit - ${junit.version} - diff --git a/java-lite/src/main/resources/logback.xml b/java-lite/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-lite/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/java-lite/src/test/java/app/models/ProductTest.java b/java-lite/src/test/java/app/models/ProductTest.java deleted file mode 100644 index 5e5c6e8845..0000000000 --- a/java-lite/src/test/java/app/models/ProductTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package app.models; - -import org.javalite.activejdbc.Base; -import org.junit.Assert; -import org.junit.Test; - -public class ProductTest { - - //@Test - public void givenSavedProduct_WhenFindFirst_ThenSavedProductIsReturned() { - //Open DB connection - Base.open("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/dbname", "user", "password"); - - //Create a product and save it - Product toSaveProduct = new Product(); - toSaveProduct.set("name", "Bread"); - toSaveProduct.saveIt(); - - //Find product - Product savedProduct = Product.findFirst("name = ?", "Bread"); - - Assert.assertEquals(toSaveProduct.get("name"), savedProduct.get("name")); - } - -} \ No newline at end of file diff --git a/java-lite/src/test/java/app/models/ProductUnitTest.java b/java-lite/src/test/java/app/models/ProductUnitTest.java new file mode 100644 index 0000000000..416df67d0e --- /dev/null +++ b/java-lite/src/test/java/app/models/ProductUnitTest.java @@ -0,0 +1,25 @@ +package app.models; + +import org.javalite.activejdbc.Base; +import org.junit.Assert; +import org.junit.Test; + +public class ProductUnitTest { + + //@Test + public void givenSavedProduct_WhenFindFirst_ThenSavedProductIsReturned() { + //Open DB connection + Base.open("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/dbname", "user", "password"); + + //Create a product and save it + Product toSaveProduct = new Product(); + toSaveProduct.set("name", "Bread"); + toSaveProduct.saveIt(); + + //Find product + Product savedProduct = Product.findFirst("name = ?", "Bread"); + + Assert.assertEquals(toSaveProduct.get("name"), savedProduct.get("name")); + } + +} \ No newline at end of file diff --git a/java-numbers/.gitignore b/java-numbers/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/java-numbers/.gitignore @@ -0,0 +1,26 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +*.txt +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/java-numbers/README.md b/java-numbers/README.md new file mode 100644 index 0000000000..6d6a279cc9 --- /dev/null +++ b/java-numbers/README.md @@ -0,0 +1,14 @@ +========= + +## Java Number Cookbooks and Examples + +### Relevant Articles: +- [Number of Digits in an Integer in Java](http://www.baeldung.com/java-number-of-digits-in-int) +- [NaN in Java](http://www.baeldung.com/java-not-a-number) +- [How to Round a Number to N Decimal Places in Java](http://www.baeldung.com/java-round-decimal-number) +- [Check If a Number Is Prime in Java](http://www.baeldung.com/java-prime-numbers) +- [Using Math.pow in Java](http://www.baeldung.com/java-math-pow) +- [Generating Prime Numbers in Java](http://www.baeldung.com/java-generate-prime-numbers) +- [BigDecimal and BigInteger in Java](http://www.baeldung.com/java-bigdecimal-biginteger) +- [Find All Pairs of Numbers in an Array That Add Up to a Given Sum](http://www.baeldung.com/java-algorithm-number-pairs-sum) +- [Java – Random Long, Float, Integer and Double](http://www.baeldung.com/java-generate-random-long-float-integer-double) diff --git a/java-numbers/pom.xml b/java-numbers/pom.xml new file mode 100644 index 0000000000..bb63c8cfe1 --- /dev/null +++ b/java-numbers/pom.xml @@ -0,0 +1,146 @@ + + 4.0.0 + java-numbers + 0.1.0-SNAPSHOT + jar + java-numbers + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + log4j + log4j + ${log4j.version} + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator-annprocess.version} + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.decimal4j + decimal4j + ${decimal4j.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + java-numbers + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + + true + + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven-javadoc-plugin.version} + + 1.8 + 1.8 + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + + + 3.6.1 + 1.0.3 + 3.5 + + 3.6.1 + + 1.7.21 + 1.1.7 + 1.19 + 1.19 + + 2.21.0 + 3.0.0-M1 + 3.0.2 + + diff --git a/algorithms/src/main/java/com/baeldung/algorithms/primechecker/BigIntegerPrimeChecker.java b/java-numbers/src/main/java/com/baeldung/algorithms/primechecker/BigIntegerPrimeChecker.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/primechecker/BigIntegerPrimeChecker.java rename to java-numbers/src/main/java/com/baeldung/algorithms/primechecker/BigIntegerPrimeChecker.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java b/java-numbers/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java similarity index 83% rename from algorithms/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java rename to java-numbers/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java index 47ffb3e224..68382c26ea 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java +++ b/java-numbers/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java @@ -1,16 +1,14 @@ package com.baeldung.algorithms.primechecker; import java.util.stream.IntStream; -import java.util.stream.LongStream; -public class BruteForcePrimeChecker implements PrimeChecker{ +public class BruteForcePrimeChecker implements PrimeChecker { @Override public boolean isPrime(Integer number) { - + return number > 2 ? IntStream.range(2, number) .noneMatch(n -> (number % n == 0)) : false; } - -} +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java b/java-numbers/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java similarity index 88% rename from algorithms/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java rename to java-numbers/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java index 06ae4acc7f..3dc372ad22 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java +++ b/java-numbers/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java @@ -1,9 +1,8 @@ package com.baeldung.algorithms.primechecker; import java.util.stream.IntStream; -import java.util.stream.LongStream; -public class OptimisedPrimeChecker implements PrimeChecker{ +public class OptimisedPrimeChecker implements PrimeChecker { @Override public boolean isPrime(Integer number) { @@ -11,5 +10,4 @@ public class OptimisedPrimeChecker implements PrimeChecker{ .noneMatch(n -> (number % n == 0)) : false; } - } diff --git a/algorithms/src/main/java/com/baeldung/algorithms/primechecker/PrimeChecker.java b/java-numbers/src/main/java/com/baeldung/algorithms/primechecker/PrimeChecker.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/primechecker/PrimeChecker.java rename to java-numbers/src/main/java/com/baeldung/algorithms/primechecker/PrimeChecker.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/primechecker/PrimesPrimeChecker.java b/java-numbers/src/main/java/com/baeldung/algorithms/primechecker/PrimesPrimeChecker.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/primechecker/PrimesPrimeChecker.java rename to java-numbers/src/main/java/com/baeldung/algorithms/primechecker/PrimesPrimeChecker.java diff --git a/java-numbers/src/main/java/com/baeldung/maths/BigDecimalDemo.java b/java-numbers/src/main/java/com/baeldung/maths/BigDecimalDemo.java new file mode 100644 index 0000000000..7de0197769 --- /dev/null +++ b/java-numbers/src/main/java/com/baeldung/maths/BigDecimalDemo.java @@ -0,0 +1,29 @@ +package com.baeldung.maths; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +public class BigDecimalDemo { + + /** Calculate total amount to be paid for an item rounded to cents.. + * @param quantity + * @param unitPrice + * @param discountRate + * @param taxRate + * @return + */ + public static BigDecimal calculateTotalAmount(BigDecimal quantity, + BigDecimal unitPrice, BigDecimal discountRate, BigDecimal taxRate) { + BigDecimal amount = quantity.multiply(unitPrice); + BigDecimal discount = amount.multiply(discountRate); + BigDecimal discountedAmount = amount.subtract(discount); + BigDecimal tax = discountedAmount.multiply(taxRate); + BigDecimal total = discountedAmount.add(tax); + + // round to 2 decimal places using HALF_EVEN + BigDecimal roundedTotal = total.setScale(2, RoundingMode.HALF_EVEN); + + return roundedTotal; + } + +} diff --git a/core-java/src/main/java/com/baeldung/maths/FloatingPointArithmetic.java b/java-numbers/src/main/java/com/baeldung/maths/FloatingPointArithmetic.java similarity index 100% rename from core-java/src/main/java/com/baeldung/maths/FloatingPointArithmetic.java rename to java-numbers/src/main/java/com/baeldung/maths/FloatingPointArithmetic.java diff --git a/core-java/src/main/java/com/baeldung/maths/Round.java b/java-numbers/src/main/java/com/baeldung/maths/Round.java similarity index 100% rename from core-java/src/main/java/com/baeldung/maths/Round.java rename to java-numbers/src/main/java/com/baeldung/maths/Round.java diff --git a/core-java/src/main/java/com/baeldung/nan/NaNExample.java b/java-numbers/src/main/java/com/baeldung/nan/NaNExample.java similarity index 100% rename from core-java/src/main/java/com/baeldung/nan/NaNExample.java rename to java-numbers/src/main/java/com/baeldung/nan/NaNExample.java diff --git a/core-java/src/main/java/com/baeldung/numberofdigits/Benchmarking.java b/java-numbers/src/main/java/com/baeldung/numberofdigits/Benchmarking.java similarity index 100% rename from core-java/src/main/java/com/baeldung/numberofdigits/Benchmarking.java rename to java-numbers/src/main/java/com/baeldung/numberofdigits/Benchmarking.java diff --git a/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigits.java b/java-numbers/src/main/java/com/baeldung/numberofdigits/NumberOfDigits.java similarity index 100% rename from core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigits.java rename to java-numbers/src/main/java/com/baeldung/numberofdigits/NumberOfDigits.java diff --git a/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigitsDriver.java b/java-numbers/src/main/java/com/baeldung/numberofdigits/NumberOfDigitsDriver.java similarity index 91% rename from core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigitsDriver.java rename to java-numbers/src/main/java/com/baeldung/numberofdigits/NumberOfDigitsDriver.java index c3cc567eaa..4f98992e98 100755 --- a/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigitsDriver.java +++ b/java-numbers/src/main/java/com/baeldung/numberofdigits/NumberOfDigitsDriver.java @@ -4,32 +4,32 @@ import org.apache.log4j.Logger; public class NumberOfDigitsDriver { private static NumberOfDigits numberOfDigits; - + private static Logger LOG = Logger.getLogger(NumberOfDigitsDriver.class); - + 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); } -} +} \ No newline at end of file diff --git a/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairs.java b/java-numbers/src/main/java/com/baeldung/pairsaddupnumber/DifferentPairs.java similarity index 93% rename from algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairs.java rename to java-numbers/src/main/java/com/baeldung/pairsaddupnumber/DifferentPairs.java index e86e1d5a22..b316957652 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairs.java +++ b/java-numbers/src/main/java/com/baeldung/pairsaddupnumber/DifferentPairs.java @@ -1,4 +1,4 @@ -package com.baeldung.algorithms.pairsaddupnumber; +package com.baeldung.pairsaddupnumber; import java.util.ArrayList; @@ -23,7 +23,7 @@ public class DifferentPairs { public static List findPairsWithForLoop(int[] input, int sum) { final List allDifferentPairs = new ArrayList<>(); // Aux. hash map - final Map pairs = new HashMap(); + final Map pairs = new HashMap<>(); for (int i : input) { if (pairs.containsKey(i)) { if (pairs.get(i) != null) { @@ -51,7 +51,7 @@ public class DifferentPairs { public static List findPairsWithStreamApi(int[] input, int sum) { final List allDifferentPairs = new ArrayList<>(); // Aux. hash map - final Map pairs = new HashMap(); + final Map pairs = new HashMap<>(); IntStream.range(0, input.length).forEach(i -> { if (pairs.containsKey(input[i])) { if (pairs.get(input[i]) != null) { diff --git a/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairs.java b/java-numbers/src/main/java/com/baeldung/pairsaddupnumber/ExistingPairs.java similarity index 97% rename from algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairs.java rename to java-numbers/src/main/java/com/baeldung/pairsaddupnumber/ExistingPairs.java index 6b10c73bcf..82c2a54ae6 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairs.java +++ b/java-numbers/src/main/java/com/baeldung/pairsaddupnumber/ExistingPairs.java @@ -1,4 +1,4 @@ -package com.baeldung.algorithms.pairsaddupnumber; +package com.baeldung.pairsaddupnumber; import java.util.ArrayList; diff --git a/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/FindPairs.java b/java-numbers/src/main/java/com/baeldung/pairsaddupnumber/FindPairs.java similarity index 98% rename from algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/FindPairs.java rename to java-numbers/src/main/java/com/baeldung/pairsaddupnumber/FindPairs.java index 4b309332ae..b990222b7e 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/FindPairs.java +++ b/java-numbers/src/main/java/com/baeldung/pairsaddupnumber/FindPairs.java @@ -1,4 +1,4 @@ -package com.baeldung.algorithms.pairsaddupnumber; +package com.baeldung.pairsaddupnumber; import java.util.ArrayList; import java.util.List; diff --git a/core-java/src/main/java/com/baeldung/pow/PowerExample.java b/java-numbers/src/main/java/com/baeldung/pow/PowerExample.java similarity index 100% rename from core-java/src/main/java/com/baeldung/pow/PowerExample.java rename to java-numbers/src/main/java/com/baeldung/pow/PowerExample.java diff --git a/core-java-8/src/main/java/com/baeldung/prime/PrimeGenerator.java b/java-numbers/src/main/java/com/baeldung/prime/PrimeGenerator.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/prime/PrimeGenerator.java rename to java-numbers/src/main/java/com/baeldung/prime/PrimeGenerator.java diff --git a/java-numbers/src/main/resources/log4j.properties b/java-numbers/src/main/resources/log4j.properties new file mode 100644 index 0000000000..621cf01735 --- /dev/null +++ b/java-numbers/src/main/resources/log4j.properties @@ -0,0 +1,6 @@ +log4j.rootLogger=DEBUG, A1 + +log4j.appender.A1=org.apache.log4j.ConsoleAppender + +log4j.appender.A1.layout=org.apache.log4j.PatternLayout +log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n \ No newline at end of file diff --git a/java-numbers/src/main/resources/logback.xml b/java-numbers/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-numbers/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/algorithms/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java b/java-numbers/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java similarity index 85% rename from algorithms/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java rename to java-numbers/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java index 9203131397..9f8ba8defd 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java +++ b/java-numbers/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java @@ -8,16 +8,16 @@ import static org.junit.Assert.assertTrue; public class PrimeCheckerUnitTest { private final BigIntegerPrimeChecker primeChecker = new BigIntegerPrimeChecker(); - + @Test - public void whenCheckIsPrime_thenTrue(){ + public void whenCheckIsPrime_thenTrue() { assertTrue(primeChecker.isPrime(13l)); assertTrue(primeChecker.isPrime(1009L)); assertTrue(primeChecker.isPrime(74207281L)); } - + @Test - public void whenCheckIsPrime_thenFalse(){ + public void whenCheckIsPrime_thenFalse() { assertTrue(!primeChecker.isPrime(50L)); assertTrue(!primeChecker.isPrime(1001L)); assertTrue(!primeChecker.isPrime(74207282L)); @@ -26,28 +26,27 @@ public class PrimeCheckerUnitTest { private final BruteForcePrimeChecker bfPrimeChecker = new BruteForcePrimeChecker(); @Test - public void whenBFCheckIsPrime_thenTrue(){ + public void whenBFCheckIsPrime_thenTrue() { assertTrue(bfPrimeChecker.isPrime(13)); assertTrue(bfPrimeChecker.isPrime(1009)); } @Test - public void whenBFCheckIsPrime_thenFalse(){ + public void whenBFCheckIsPrime_thenFalse() { assertFalse(bfPrimeChecker.isPrime(50)); assertFalse(bfPrimeChecker.isPrime(1001)); } - private final OptimisedPrimeChecker optimisedPrimeChecker = new OptimisedPrimeChecker(); @Test - public void whenOptCheckIsPrime_thenTrue(){ + public void whenOptCheckIsPrime_thenTrue() { assertTrue(optimisedPrimeChecker.isPrime(13)); assertTrue(optimisedPrimeChecker.isPrime(1009)); } @Test - public void whenOptCheckIsPrime_thenFalse(){ + public void whenOptCheckIsPrime_thenFalse() { assertFalse(optimisedPrimeChecker.isPrime(50)); assertFalse(optimisedPrimeChecker.isPrime(1001)); } @@ -65,5 +64,5 @@ public class PrimeCheckerUnitTest { assertFalse(primesPrimeChecker.isPrime(50)); assertFalse(primesPrimeChecker.isPrime(1001)); } - + } diff --git a/java-numbers/src/test/java/com/baeldung/maths/BigDecimalDemoUnitTest.java b/java-numbers/src/test/java/com/baeldung/maths/BigDecimalDemoUnitTest.java new file mode 100644 index 0000000000..2bf9872bec --- /dev/null +++ b/java-numbers/src/test/java/com/baeldung/maths/BigDecimalDemoUnitTest.java @@ -0,0 +1,120 @@ +package com.baeldung.maths; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.MathContext; +import java.math.RoundingMode; +import java.util.Random; + +import org.junit.jupiter.api.Test; + +public class BigDecimalDemoUnitTest { + + @Test + public void whenBigDecimalCreated_thenValueMatches() { + BigDecimal bdFromString = new BigDecimal("0.1"); + BigDecimal bdFromCharArray = new BigDecimal( + new char[] { '3', '.', '1', '6', '1', '5' }); + BigDecimal bdlFromInt = new BigDecimal(42); + BigDecimal bdFromLong = new BigDecimal(123412345678901L); + BigInteger bigInteger = BigInteger.probablePrime(100, new Random()); + BigDecimal bdFromBigInteger = new BigDecimal(bigInteger); + + assertEquals("0.1", bdFromString.toString()); + assertEquals("3.1615", bdFromCharArray.toString()); + assertEquals("42", bdlFromInt.toString()); + assertEquals("123412345678901", bdFromLong.toString()); + assertEquals(bigInteger.toString(), bdFromBigInteger.toString()); + } + + @Test + public void whenBigDecimalCreatedFromDouble_thenValueMayNotMatch() { + BigDecimal bdFromDouble = new BigDecimal(0.1d); + assertNotEquals("0.1", bdFromDouble.toString()); + } + + @Test + public void whenBigDecimalCreatedUsingValueOf_thenValueMatches() { + BigDecimal bdFromLong1 = BigDecimal.valueOf(123412345678901L); + BigDecimal bdFromLong2 = BigDecimal.valueOf(123412345678901L, 2); + BigDecimal bdFromDouble = BigDecimal.valueOf(0.1d); + + assertEquals("123412345678901", bdFromLong1.toString()); + assertEquals("1234123456789.01", bdFromLong2.toString()); + assertEquals("0.1", bdFromDouble.toString()); + } + + @Test + public void whenEqualsCalled_thenSizeAndScaleMatched() { + BigDecimal bd1 = new BigDecimal("1.0"); + BigDecimal bd2 = new BigDecimal("1.00"); + + assertFalse(bd1.equals(bd2)); + } + + @Test + public void whenComparingBigDecimals_thenExpectedResult() { + BigDecimal bd1 = new BigDecimal("1.0"); + BigDecimal bd2 = new BigDecimal("1.00"); + BigDecimal bd3 = new BigDecimal("2.0"); + + assertTrue(bd1.compareTo(bd3) < 0); + assertTrue(bd3.compareTo(bd1) > 0); + assertTrue(bd1.compareTo(bd2) == 0); + assertTrue(bd1.compareTo(bd3) <= 0); + assertTrue(bd1.compareTo(bd2) >= 0); + assertTrue(bd1.compareTo(bd3) != 0); + } + + @Test + public void whenPerformingArithmetic_thenExpectedResult() { + BigDecimal bd1 = new BigDecimal("4.0"); + BigDecimal bd2 = new BigDecimal("2.0"); + + BigDecimal sum = bd1.add(bd2); + BigDecimal difference = bd1.subtract(bd2); + BigDecimal quotient = bd1.divide(bd2); + BigDecimal product = bd1.multiply(bd2); + + assertTrue(sum.compareTo(new BigDecimal("6.0")) == 0); + assertTrue(difference.compareTo(new BigDecimal("2.0")) == 0); + assertTrue(quotient.compareTo(new BigDecimal("2.0")) == 0); + assertTrue(product.compareTo(new BigDecimal("8.0")) == 0); + } + + @Test + public void whenGettingAttributes_thenExpectedResult() { + BigDecimal bd = new BigDecimal("-12345.6789"); + + assertEquals(9, bd.precision()); + assertEquals(4, bd.scale()); + assertEquals(-1, bd.signum()); + } + + @Test + public void whenRoundingDecimal_thenExpectedResult() { + BigDecimal bd = new BigDecimal("2.5"); + // Round to 1 digit using HALF_EVEN + BigDecimal rounded = bd + .round(new MathContext(1, RoundingMode.HALF_EVEN)); + + assertEquals("2", rounded.toString()); + } + + @Test + public void givenPurchaseTxn_whenCalculatingTotalAmount_thenExpectedResult() { + BigDecimal quantity = new BigDecimal("4.5"); + BigDecimal unitPrice = new BigDecimal("2.69"); + BigDecimal discountRate = new BigDecimal("0.10"); + BigDecimal taxRate = new BigDecimal("0.0725"); + + BigDecimal amountToBePaid = BigDecimalDemo + .calculateTotalAmount(quantity, unitPrice, discountRate, taxRate); + assertEquals("11.68", amountToBePaid.toString()); + } +} diff --git a/java-numbers/src/test/java/com/baeldung/maths/BigDecimalImplUnitTest.java b/java-numbers/src/test/java/com/baeldung/maths/BigDecimalImplUnitTest.java new file mode 100644 index 0000000000..786e5af312 --- /dev/null +++ b/java-numbers/src/test/java/com/baeldung/maths/BigDecimalImplUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.maths; + +import org.junit.Assert; +import org.junit.Test; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +public class BigDecimalImplUnitTest { + + @Test + public void givenBigDecimalNumbers_whenAddedTogether_thenGetExpectedResult() { + BigDecimal serviceTax = new BigDecimal("56.0084578639"); + serviceTax = serviceTax.setScale(2, RoundingMode.CEILING); + + BigDecimal entertainmentTax = new BigDecimal("23.00689"); + entertainmentTax = entertainmentTax.setScale(2, RoundingMode.FLOOR); + + BigDecimal totalTax = serviceTax.add(entertainmentTax); + BigDecimal result = BigDecimal.valueOf(79.01); + + Assert.assertEquals(result, totalTax); + + } +} diff --git a/java-numbers/src/test/java/com/baeldung/maths/BigIntegerDemoUnitTest.java b/java-numbers/src/test/java/com/baeldung/maths/BigIntegerDemoUnitTest.java new file mode 100644 index 0000000000..3537ccb3a3 --- /dev/null +++ b/java-numbers/src/test/java/com/baeldung/maths/BigIntegerDemoUnitTest.java @@ -0,0 +1,128 @@ +package com.baeldung.maths; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.math.BigInteger; +import java.util.Random; + +import org.junit.jupiter.api.Test; + +public class BigIntegerDemoUnitTest { + + @Test + public void whenBigIntegerCreatedFromConstructor_thenExpectedResult() { + BigInteger biFromString = new BigInteger("1234567890987654321"); + BigInteger biFromByteArray = new BigInteger( + new byte[] { 64, 64, 64, 64, 64, 64 }); + BigInteger biFromSignMagnitude = new BigInteger(-1, + new byte[] { 64, 64, 64, 64, 64, 64 }); + + assertEquals("1234567890987654321", biFromString.toString()); + assertEquals("70644700037184", biFromByteArray.toString()); + assertEquals("-70644700037184", biFromSignMagnitude.toString()); + } + + @Test + public void whenLongConvertedToBigInteger_thenValueMatches() { + BigInteger bi = BigInteger.valueOf(2305843009213693951L); + + assertEquals("2305843009213693951", bi.toString()); + } + + @Test + public void givenBigIntegers_whentCompared_thenExpectedResult() { + BigInteger i = new BigInteger("123456789012345678901234567890"); + BigInteger j = new BigInteger("123456789012345678901234567891"); + BigInteger k = new BigInteger("123456789012345678901234567892"); + + assertTrue(i.compareTo(i) == 0); + assertTrue(j.compareTo(i) > 0); + assertTrue(j.compareTo(k) < 0); + } + + @Test + public void givenBigIntegers_whenPerformingArithmetic_thenExpectedResult() { + BigInteger i = new BigInteger("4"); + BigInteger j = new BigInteger("2"); + + BigInteger sum = i.add(j); + BigInteger difference = i.subtract(j); + BigInteger quotient = i.divide(j); + BigInteger product = i.multiply(j); + + assertEquals(new BigInteger("6"), sum); + assertEquals(new BigInteger("2"), difference); + assertEquals(new BigInteger("2"), quotient); + assertEquals(new BigInteger("8"), product); + } + + @Test + public void givenBigIntegers_whenPerformingBitOperations_thenExpectedResult() { + BigInteger i = new BigInteger("17"); + BigInteger j = new BigInteger("7"); + + BigInteger and = i.and(j); + BigInteger or = i.or(j); + BigInteger not = j.not(); + BigInteger xor = i.xor(j); + BigInteger andNot = i.andNot(j); + BigInteger shiftLeft = i.shiftLeft(1); + BigInteger shiftRight = i.shiftRight(1); + + assertEquals(new BigInteger("1"), and); + assertEquals(new BigInteger("23"), or); + assertEquals(new BigInteger("-8"), not); + assertEquals(new BigInteger("22"), xor); + assertEquals(new BigInteger("16"), andNot); + assertEquals(new BigInteger("34"), shiftLeft); + assertEquals(new BigInteger("8"), shiftRight); + } + + @Test + public void givenBigIntegers_whenPerformingBitManipulations_thenExpectedResult() { + BigInteger i = new BigInteger("1018"); + + int bitCount = i.bitCount(); + int bitLength = i.bitLength(); + int getLowestSetBit = i.getLowestSetBit(); + boolean testBit3 = i.testBit(3); + BigInteger setBit12 = i.setBit(12); + BigInteger flipBit0 = i.flipBit(0); + BigInteger clearBit3 = i.clearBit(3); + + assertEquals(8, bitCount); + assertEquals(10, bitLength); + assertEquals(1, getLowestSetBit); + assertEquals(true, testBit3); + assertEquals(new BigInteger("5114"), setBit12); + assertEquals(new BigInteger("1019"), flipBit0); + assertEquals(new BigInteger("1010"), clearBit3); + } + + @Test + public void givenBigIntegers_whenModularCalculation_thenExpectedResult() { + BigInteger i = new BigInteger("31"); + BigInteger j = new BigInteger("24"); + BigInteger k = new BigInteger("16"); + + BigInteger gcd = j.gcd(k); + BigInteger multiplyAndmod = j.multiply(k) + .mod(i); + BigInteger modInverse = j.modInverse(i); + BigInteger modPow = j.modPow(k, i); + + assertEquals(new BigInteger("8"), gcd); + assertEquals(new BigInteger("12"), multiplyAndmod); + assertEquals(new BigInteger("22"), modInverse); + assertEquals(new BigInteger("7"), modPow); + } + + @Test + public void givenBigIntegers_whenPrimeOperations_thenExpectedResult() { + BigInteger i = BigInteger.probablePrime(100, new Random()); + + boolean isProbablePrime = i.isProbablePrime(1000); + assertEquals(true, isProbablePrime); + } +} diff --git a/java-numbers/src/test/java/com/baeldung/maths/BigIntegerImplUnitTest.java b/java-numbers/src/test/java/com/baeldung/maths/BigIntegerImplUnitTest.java new file mode 100644 index 0000000000..4c45f69090 --- /dev/null +++ b/java-numbers/src/test/java/com/baeldung/maths/BigIntegerImplUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.maths; + +import org.junit.Assert; +import org.junit.Test; + +import java.math.BigInteger; + +public class BigIntegerImplUnitTest { + + @Test + public void givenBigIntegerNumbers_whenAddedTogether_thenGetExpectedResult() { + BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476"); + BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476"); + + BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda); + BigInteger result = new BigInteger("14110718640342675608722521633212952"); + + Assert.assertEquals(result, totalStars); + } + +} diff --git a/java-numbers/src/test/java/com/baeldung/maths/FloatingPointArithmeticUnitTest.java b/java-numbers/src/test/java/com/baeldung/maths/FloatingPointArithmeticUnitTest.java new file mode 100644 index 0000000000..6812a8f588 --- /dev/null +++ b/java-numbers/src/test/java/com/baeldung/maths/FloatingPointArithmeticUnitTest.java @@ -0,0 +1,45 @@ +package com.baeldung.maths; + +import java.math.BigDecimal; + +import org.junit.Assert; +import org.junit.Test; + +public class FloatingPointArithmeticUnitTest { + + @Test + public void givenDecimalNumbers_whenAddedTogether_thenGetExpectedResult() { + double a = 13.22; + double b = 4.88; + double c = 21.45; + double result = 39.55; + + double abc = a + b + c; + double acb = a + c + b; + + Assert.assertEquals(result, abc, 0); + Assert.assertNotEquals(result, acb, 0); + + double ab = 18.1; + double ac = 34.67; + + double ab_c = ab + c; + double ac_b = ac + b; + + Assert.assertEquals(result, ab_c, 0); + Assert.assertNotEquals(result, ac_b, 0); + + BigDecimal d = new BigDecimal(String.valueOf(a)); + BigDecimal e = new BigDecimal(String.valueOf(b)); + BigDecimal f = new BigDecimal(String.valueOf(c)); + BigDecimal sum = new BigDecimal("39.55"); + + BigDecimal def = d.add(e).add(f); + BigDecimal dfe = d.add(f).add(e); + + Assert.assertEquals(0, def.compareTo(sum)); + Assert.assertEquals(0, dfe.compareTo(sum)); + + Assert.assertNotEquals(0, sum.compareTo(new BigDecimal(String.valueOf(acb)))); + } +} diff --git a/java-numbers/src/test/java/com/baeldung/maths/RoundUnitTest.java b/java-numbers/src/test/java/com/baeldung/maths/RoundUnitTest.java new file mode 100644 index 0000000000..7e3f5d6c63 --- /dev/null +++ b/java-numbers/src/test/java/com/baeldung/maths/RoundUnitTest.java @@ -0,0 +1,71 @@ +package com.baeldung.maths; + +import org.apache.commons.math3.util.Precision; +import org.decimal4j.util.DoubleRounder; +import org.junit.Assert; +import org.junit.Test; + +public class RoundUnitTest { + private double value = 2.03456d; + private int places = 2; + private double delta = 0.0d; + private double expected = 2.03d; + + @Test + 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; + 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 ! + Assert.assertEquals(expected, Precision.round(value, places), delta); + Assert.assertEquals(expected, DoubleRounder.round(value, places), delta); + } +} diff --git a/core-java/src/test/java/com/baeldung/numberofdigits/NumberOfDigitsIntegrationTest.java b/java-numbers/src/test/java/com/baeldung/numberofdigits/NumberOfDigitsIntegrationTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/numberofdigits/NumberOfDigitsIntegrationTest.java rename to java-numbers/src/test/java/com/baeldung/numberofdigits/NumberOfDigitsIntegrationTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairsUnitTest.java b/java-numbers/src/test/java/com/baeldung/pairsaddupnumber/DifferentPairsUnitTest.java similarity index 95% rename from algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairsUnitTest.java rename to java-numbers/src/test/java/com/baeldung/pairsaddupnumber/DifferentPairsUnitTest.java index 48fcfb871c..4f7c9b5a29 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairsUnitTest.java +++ b/java-numbers/src/test/java/com/baeldung/pairsaddupnumber/DifferentPairsUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.algorithms.pairsaddupnumber; +package com.baeldung.pairsaddupnumber; import org.junit.Test; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairsUnitTest.java b/java-numbers/src/test/java/com/baeldung/pairsaddupnumber/ExistingPairsUnitTest.java similarity index 94% rename from algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairsUnitTest.java rename to java-numbers/src/test/java/com/baeldung/pairsaddupnumber/ExistingPairsUnitTest.java index ac6d6cc885..593db5b894 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairsUnitTest.java +++ b/java-numbers/src/test/java/com/baeldung/pairsaddupnumber/ExistingPairsUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.algorithms.pairsaddupnumber; +package com.baeldung.pairsaddupnumber; import org.junit.Test; import java.util.List; diff --git a/java-numbers/src/test/java/com/baeldung/prime/PrimeGeneratorUnitTest.java b/java-numbers/src/test/java/com/baeldung/prime/PrimeGeneratorUnitTest.java new file mode 100644 index 0000000000..210bde076b --- /dev/null +++ b/java-numbers/src/test/java/com/baeldung/prime/PrimeGeneratorUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.prime; + +import java.util.Arrays; +import java.util.List; +import org.junit.Test; + +import static com.baeldung.prime.PrimeGenerator.*; +import static org.junit.Assert.*; + +public class PrimeGeneratorUnitTest { + @Test + public void whenBruteForced_returnsSuccessfully() { + final List primeNumbers = primeNumbersBruteForce(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } + + @Test + public void whenOptimized_returnsSuccessfully() { + final List primeNumbers = primeNumbersTill(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } + + @Test + public void whenSieveOfEratosthenes_returnsSuccessfully() { + final List primeNumbers = sieveOfEratosthenes(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } +} diff --git a/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java b/java-numbers/src/test/java/com/baeldung/random/JavaRandomUnitTest.java similarity index 99% rename from core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java rename to java-numbers/src/test/java/com/baeldung/random/JavaRandomUnitTest.java index f17531e744..2273dfda13 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java +++ b/java-numbers/src/test/java/com/baeldung/random/JavaRandomUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java; +package com.baeldung.random; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.math3.random.RandomDataGenerator; diff --git a/java-rmi/pom.xml b/java-rmi/pom.xml index 1543e24fbd..33931baedf 100644 --- a/java-rmi/pom.xml +++ b/java-rmi/pom.xml @@ -12,8 +12,4 @@ 1.0.0-SNAPSHOT
    - - UTF-8 - -
    diff --git a/java-rmi/src/main/resources/logback.xml b/java-rmi/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-rmi/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/java-spi/README.md b/java-spi/README.md new file mode 100644 index 0000000000..d2658c42fe --- /dev/null +++ b/java-spi/README.md @@ -0,0 +1,4 @@ + +### Relevant Articles: + +- [Java Service Provider Interface](http://www.baeldung.com/java-spi) diff --git a/java-spi/exchange-rate-api/pom.xml b/java-spi/exchange-rate-api/pom.xml index 2de650d1af..b626916b56 100644 --- a/java-spi/exchange-rate-api/pom.xml +++ b/java-spi/exchange-rate-api/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 exchange-rate-api jar @@ -10,7 +10,4 @@ 1.0.0-SNAPSHOT - - - diff --git a/java-spi/exchange-rate-api/src/main/resources/logback.xml b/java-spi/exchange-rate-api/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-spi/exchange-rate-api/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/java-spi/exchange-rate-app/pom.xml b/java-spi/exchange-rate-app/pom.xml index b223cf7d95..a42a30ceda 100644 --- a/java-spi/exchange-rate-app/pom.xml +++ b/java-spi/exchange-rate-app/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 exchange-rate-app jar @@ -14,8 +14,12 @@ com.baeldung exchange-rate-api - 1.0.0-SNAPSHOT + ${exchange-rate-api.version} + + 1.0.0-SNAPSHOT + + diff --git a/java-spi/exchange-rate-app/src/main/resources/logback.xml b/java-spi/exchange-rate-app/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-spi/exchange-rate-app/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/java-spi/exchange-rate-impl/pom.xml b/java-spi/exchange-rate-impl/pom.xml index 435f40619e..41c874c659 100644 --- a/java-spi/exchange-rate-impl/pom.xml +++ b/java-spi/exchange-rate-impl/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 exchange-rate-impl jar @@ -10,12 +10,40 @@ 1.0.0-SNAPSHOT + + + com.baeldung + exchange-rate-api + ${exchange-rate-api.version} + + + com.squareup.okhttp3 + okhttp + ${okhttp.version} + + + javax.json.bind + javax.json.bind-api + ${javax.json.bind-api.version} + + + org.eclipse + yasson + ${yasson.version} + + + org.glassfish + javax.json + ${javax.json.version} + + + org.apache.maven.plugins maven-dependency-plugin - 3.1.0 + ${maven-dependency-plugin.version} copy-dependencies @@ -31,32 +59,14 @@ - - - com.baeldung - exchange-rate-api - 1.0.0-SNAPSHOT - - - com.squareup.okhttp3 - okhttp - 3.10.0 - - - javax.json.bind - javax.json.bind-api - 1.0 - - - org.eclipse - yasson - 1.0.1 - - - org.glassfish - javax.json - 1.1.2 - - + + + 1.0.0-SNAPSHOT + 3.10.0 + 1.0 + 1.0.1 + 1.1.2 + 3.1.0 + diff --git a/java-spi/exchange-rate-impl/src/main/resources/logback.xml b/java-spi/exchange-rate-impl/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-spi/exchange-rate-impl/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/java-spi/pom.xml b/java-spi/pom.xml index 4b9500ffcd..9ac87bf960 100644 --- a/java-spi/pom.xml +++ b/java-spi/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 java-spi pom diff --git a/java-streams/.gitignore b/java-streams/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/java-streams/.gitignore @@ -0,0 +1,26 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +*.txt +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/java-streams/README.md b/java-streams/README.md new file mode 100644 index 0000000000..548d4b6a33 --- /dev/null +++ b/java-streams/README.md @@ -0,0 +1,15 @@ +========= + +## Java Streams Cookbooks and Examples + +### Relevant Articles: +- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams) +- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction) +- [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams) +- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany) +- [How to Get the Last Element of a Stream in Java?](http://www.baeldung.com/java-stream-last-element) +- [â€Stream has already been operated upon or closed†Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception) +- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream) +- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices) +- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams) +- [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering) diff --git a/java-streams/pom.xml b/java-streams/pom.xml new file mode 100644 index 0000000000..023a5f695b --- /dev/null +++ b/java-streams/pom.xml @@ -0,0 +1,115 @@ + + 4.0.0 + java-streams + 0.1.0-SNAPSHOT + jar + java-streams + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + provided + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + log4j + log4j + ${log4j.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + org.assertj + assertj-core + ${assertj.version} + test + + + com.codepoetics + protonpack + ${protonpack.version} + + + io.vavr + vavr + ${vavr.version} + + + one.util + streamex + ${streamex.version} + + + org.aspectj + aspectjrt + ${asspectj.version} + + + org.aspectj + aspectjweaver + ${asspectj.version} + + + + + java-streams + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + -parameters + + + + + + + + 1.21 + 3.5 + 1.16.12 + 0.9.0 + 1.13 + 0.6.5 + 2.10 + + 3.6.1 + 1.8.9 + + diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java b/java-streams/src/main/java/com/baeldung/java_8_features/Detail.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java rename to java-streams/src/main/java/com/baeldung/java_8_features/Detail.java diff --git a/core-java-8/src/main/java/com/baeldung/stream/InfiniteStreams.java b/java-streams/src/main/java/com/baeldung/stream/InfiniteStreams.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/stream/InfiniteStreams.java rename to java-streams/src/main/java/com/baeldung/stream/InfiniteStreams.java diff --git a/core-java-8/src/main/java/com/baeldung/stream/PrimitiveStreams.java b/java-streams/src/main/java/com/baeldung/stream/PrimitiveStreams.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/stream/PrimitiveStreams.java rename to java-streams/src/main/java/com/baeldung/stream/PrimitiveStreams.java diff --git a/core-java-8/src/main/java/com/baeldung/stream/Product.java b/java-streams/src/main/java/com/baeldung/stream/Product.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/stream/Product.java rename to java-streams/src/main/java/com/baeldung/stream/Product.java diff --git a/core-java-8/src/main/java/com/baeldung/stream/StreamApi.java b/java-streams/src/main/java/com/baeldung/stream/StreamApi.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/stream/StreamApi.java rename to java-streams/src/main/java/com/baeldung/stream/StreamApi.java diff --git a/core-java-8/src/main/java/com/baeldung/stream/StreamIndices.java b/java-streams/src/main/java/com/baeldung/stream/StreamIndices.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/stream/StreamIndices.java rename to java-streams/src/main/java/com/baeldung/stream/StreamIndices.java diff --git a/java-streams/src/main/resources/logback.xml b/java-streams/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-streams/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java b/java-streams/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java rename to java-streams/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstUnitTest.java b/java-streams/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstUnitTest.java rename to java-streams/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java b/java-streams/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java rename to java-streams/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java b/java-streams/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java rename to java-streams/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java rename to java-streams/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java similarity index 87% rename from core-java-8/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java rename to java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java index 2c88dc5ec7..67954f0bba 100644 --- a/core-java-8/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java +++ b/java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java @@ -1,15 +1,14 @@ package com.baeldung.stream; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.Test; public class PrimitiveStreamsUnitTest { @@ -17,7 +16,7 @@ public class PrimitiveStreamsUnitTest { @Test public void givenAnArrayOfIntegersWhenMinIsCalledThenCorrectMinIsReturned() { - int[] integers = new int[] {20, 98, 12, 7, 35}; + int[] integers = new int[] { 20, 98, 12, 7, 35 }; int min = streams.min(integers); // returns 7 assertEquals(7, min); @@ -66,19 +65,14 @@ public class PrimitiveStreamsUnitTest { @Test public void givenAnArrayWhenSumIsCalledThenTheCorrectSumIsReturned() { - int sum = Stream.of(33,45) - .mapToInt(i -> i) - .sum(); + int sum = Stream.of(33, 45).mapToInt(i -> i).sum(); assertEquals(78, sum); } @Test public void givenAnIntStreamThenGetTheEvenIntegers() { - List evenInts = IntStream.rangeClosed(1, 10) - .filter(i -> i % 2 == 0) - .boxed() - .collect(Collectors.toList()); + List evenInts = IntStream.rangeClosed(1, 10).filter(i -> i % 2 == 0).boxed().collect(Collectors.toList()); List expected = IntStream.of(2, 4, 6, 8, 10).boxed().collect(Collectors.toList()); diff --git a/core-java-8/src/test/java/com/baeldung/stream/StreamAddUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/StreamAddUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/stream/StreamAddUnitTest.java rename to java-streams/src/test/java/com/baeldung/stream/StreamAddUnitTest.java diff --git a/java-streams/src/test/java/com/baeldung/stream/StreamApiUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/StreamApiUnitTest.java new file mode 100644 index 0000000000..71569a1c82 --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/stream/StreamApiUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.stream; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class StreamApiUnitTest { + + @Test + public void givenList_whenGetLastElementUsingReduce_thenReturnLastElement() { + List valueList = new ArrayList<>(); + valueList.add("Joe"); + valueList.add("John"); + valueList.add("Sean"); + + String last = StreamApi.getLastElementUsingReduce(valueList); + + assertEquals("Sean", last); + } + + @Test + public void givenInfiniteStream_whenGetInfiniteStreamLastElementUsingReduce_thenReturnLastElement() { + int last = StreamApi.getInfiniteStreamLastElementUsingReduce(); + assertEquals(19, last); + } + + @Test + public void givenListAndCount_whenGetLastElementUsingSkip_thenReturnLastElement() { + List valueList = new ArrayList<>(); + valueList.add("Joe"); + valueList.add("John"); + valueList.add("Sean"); + + String last = StreamApi.getLastElementUsingSkip(valueList); + + assertEquals("Sean", last); + } + +} diff --git a/java-streams/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java new file mode 100644 index 0000000000..36a609f536 --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.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 StreamIndicesUnitTest { + + @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/java-streams/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java new file mode 100644 index 0000000000..bd540201d2 --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java @@ -0,0 +1,65 @@ +package com.baeldung.stream; + +import static java.util.stream.Collectors.collectingAndThen; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toSet; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.IntStream; + +import org.junit.Test; + +import com.baeldung.stream.mycollectors.MyImmutableListCollector; +import com.google.common.collect.ImmutableList; + +public class StreamToImmutableUnitTest { + + @Test + public void whenUsingCollectingToImmutableSet_thenSuccess() { + List givenList = Arrays.asList("a", "b", "c"); + List result = givenList.stream() + .collect(collectingAndThen(toSet(), ImmutableList::copyOf)); + + System.out.println(result.getClass()); + } + + @Test + public void whenUsingCollectingToUnmodifiableList_thenSuccess() { + List givenList = new ArrayList<>(Arrays.asList("a", "b", "c")); + List result = givenList.stream() + .collect(collectingAndThen(toList(), Collections::unmodifiableList)); + + System.out.println(result.getClass()); + } + + @Test + public void whenCollectToImmutableList_thenSuccess() { + List list = IntStream.range(0, 9) + .boxed() + .collect(ImmutableList.toImmutableList()); + + System.out.println(list.getClass()); + } + + @Test + public void whenCollectToMyImmutableListCollector_thenSuccess() { + List givenList = Arrays.asList("a", "b", "c", "d"); + List result = givenList.stream() + .collect(MyImmutableListCollector.toImmutableList()); + + System.out.println(result.getClass()); + } + + @Test + public void whenPassingSupplier_thenSuccess() { + List givenList = Arrays.asList("a", "b", "c", "d"); + List result = givenList.stream() + .collect(MyImmutableListCollector.toImmutableList(LinkedList::new)); + + System.out.println(result.getClass()); + } +} diff --git a/java-streams/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java new file mode 100644 index 0000000000..a496e18b2d --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.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 SupplierStreamUnitTest { + + @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-8/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java b/java-streams/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java rename to java-streams/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java diff --git a/java-streams/src/test/java/com/baeldung/streamordering/BenchmarkManualTest.java b/java-streams/src/test/java/com/baeldung/streamordering/BenchmarkManualTest.java new file mode 100644 index 0000000000..656a6d95f9 --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/streamordering/BenchmarkManualTest.java @@ -0,0 +1,96 @@ +package com.baeldung.streamordering; + +import org.junit.Test; +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; +import org.openjdk.jmh.runner.options.TimeValue; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + + +public class BenchmarkManualTest +{ + + public void + launchBenchmark() throws Exception { + + Options opt = new OptionsBuilder() + // Specify which benchmarks to run. + // You can be more specific if you'd like to run only one benchmark per test. + .include(this.getClass().getName() + ".*") + // Set the following options as needed + .mode (Mode.AverageTime) + .timeUnit(TimeUnit.MICROSECONDS) + .warmupTime(TimeValue.seconds(1)) + .warmupIterations(2) + .measurementTime(TimeValue.seconds(1)) + .measurementIterations(2) + .threads(2) + .forks(1) + .shouldFailOnError(true) + .shouldDoGC(true) + //.jvmArgs("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining") + //.addProfiler(WinPerfAsmProfiler.class) + .build(); + + new Runner(opt).run(); + + + } + + @Benchmark + public void givenOrderedStreamInput_whenStreamFiltered_showOpsPerMS(){ + IntStream.range(1, 100_000_000).parallel().filter(i -> i % 10 == 0).toArray(); + } + + @Benchmark + public void givenUnorderedStreamInput_whenStreamFiltered_showOpsPerMS(){ + IntStream.range(1,100_000_000).unordered().parallel().filter(i -> i % 10 == 0).toArray(); + } + + @Benchmark + public void givenUnorderedStreamInput_whenStreamDistinct_showOpsPerMS(){ + IntStream.range(1, 1_000_000).unordered().parallel().distinct().toArray(); + } + + @Benchmark + public void givenOrderedStreamInput_whenStreamDistinct_showOpsPerMS() { + //section 5.1. + IntStream.range(1, 1_000_000).parallel().distinct().toArray(); + } + + + // The JMH samples are the best documentation for how to use it + // http://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/ + @State(Scope.Thread) + public static class BenchmarkState + { + List list; + + @Setup(Level.Trial) public void + initialize() { + + Random rand = new Random(); + + list = new ArrayList<>(); + for (int i = 0; i < 1000; i++) + list.add (rand.nextInt()); + } + } + + @Benchmark public void + benchmark1 (BenchmarkState state, Blackhole bh) { + + List list = state.list; + + for (int i = 0; i < 1000; i++) + bh.consume (list.get (i)); + } +} diff --git a/java-streams/src/test/java/com/baeldung/streamordering/StreamsOrderingUnitTest.java b/java-streams/src/test/java/com/baeldung/streamordering/StreamsOrderingUnitTest.java new file mode 100644 index 0000000000..43a233d353 --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/streamordering/StreamsOrderingUnitTest.java @@ -0,0 +1,149 @@ +package com.baeldung.streamordering; + +import org.junit.Before; +import org.junit.Test; + +import java.util.*; +import java.util.function.Function; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.junit.Assert.assertEquals; + +public class StreamsOrderingUnitTest { + + Logger logger = Logger.getLogger( StreamsOrderingUnitTest.class.getName()); + + @Before + public void setUp() throws Exception { + logger.setLevel(Level.ALL); + } + + @Test + public void givenTwoCollections_whenStreamed_thenCheckOutputDifferent(){ + + List list = Arrays.asList("B", "A", "C", "D", "F"); + Set set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F")); + + Object[] listOutput = list.stream().toArray(); + Object[] setOutput = set.stream().toArray(); + + assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput)); + assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput)); + + } + + @Test + public void givenTwoCollections_whenStreamedInParallel_thenCheckOutputDifferent(){ + + List list = Arrays.asList("B", "A", "C", "D", "F"); + Set set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F")); + + Object[] listOutput = list.stream().parallel().toArray(); + Object[] setOutput = set.stream().parallel().toArray(); + + assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput)); + assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput)); + + } + + + + @Test + public void givenOrderedInput_whenUnorderedAndOrderedCompared_thenCheckUnorderedOutputChanges(){ + Set set = new TreeSet<>( + Arrays.asList(-9, -5, -4, -2, 1, 2, 4, 5, 7, 9, 12, 13, 16, 29, 23, 34, 57, 68, 90, 102, 230)); + + Object[] orderedArray = set.stream() + .parallel() + .limit(5) + .toArray(); + Object[] unorderedArray = set.stream() + .unordered() + .parallel() + .limit(5) + .toArray(); + + logger.info(Arrays.toString(orderedArray)); + logger.info(Arrays.toString(unorderedArray)); + } + + + @Test + public void givenUnsortedStreamInput_whenStreamSorted_thenCheckOrderChanged(){ + + List list = Arrays.asList(-3,10,-4,1,3); + + Object[] listOutput = list.stream().toArray(); + Object[] listOutputSorted = list.stream().sorted().toArray(); + + assertEquals("[-3, 10, -4, 1, 3]", Arrays.toString(listOutput)); + assertEquals("[-4, -3, 1, 3, 10]", Arrays.toString(listOutputSorted)); + + } + + @Test + public void givenUnsortedStreamInput_whenStreamDistinct_thenShowTimeTaken(){ + long start, end; + start = System.currentTimeMillis(); + IntStream.range(1,1_000_000).unordered().parallel().distinct().toArray(); + end = System.currentTimeMillis(); + System.out.println(String.format("Time taken when unordered: %d ms", (end - start))); + } + + + @Test + public void givenSameCollection_whenStreamTerminated_thenCheckEachVsEachOrdered(){ + + List list = Arrays.asList("B", "A", "C", "D", "F"); + + list.stream().parallel().forEach(e -> logger.log(Level.INFO, e)); + list.stream().parallel().forEachOrdered(e -> logger.log(Level.INFO, e)); + + } + + @Test + public void givenSameCollection_whenStreamCollected_thenCheckOutput(){ + + List list = Arrays.asList("B", "A", "C", "D", "F"); + + List collectionList = list.stream().parallel().collect(Collectors.toList()); + Set collectionSet = list.stream().parallel().collect(Collectors.toCollection(TreeSet::new)); + + assertEquals("[B, A, C, D, F]", collectionList.toString()); + assertEquals("[A, B, C, D, F]", collectionSet.toString()); + + } + + + @Test + public void givenListIterationOrder_whenStreamCollectedToMap_thenCeckOrderChanged() { + List list = Arrays.asList("A", "BB", "CCC"); + + Map hashMap = list.stream().collect(Collectors.toMap(Function.identity(), String::length)); + + Object[] keySet = hashMap.keySet().toArray(); + + assertEquals("[BB, A, CCC]", Arrays.toString(keySet)); + + } + + @Test + public void givenListIteration_whenStreamCollectedtoHashMap_thenCheckOrderMaintained() { + List list = Arrays.asList("A", "BB", "CCC", "CCC"); + + Map linkedHashMap = list.stream().collect(Collectors.toMap( + Function.identity(), + String::length, + (u, v) -> u, + LinkedHashMap::new + )); + + Object[] keySet = linkedHashMap.keySet().toArray(); + + assertEquals("[A, BB, CCC]", Arrays.toString(keySet)); + } + +} diff --git a/out/production/main330/com/baeldung/.gitignore b/java-streams/src/test/resources/.gitignore similarity index 100% rename from out/production/main330/com/baeldung/.gitignore rename to java-streams/src/test/resources/.gitignore diff --git a/java-strings/README.md b/java-strings/README.md new file mode 100644 index 0000000000..233d986d98 --- /dev/null +++ b/java-strings/README.md @@ -0,0 +1,29 @@ +========= + +## Java Strings Cookbooks and Examples + +### Relevant Articles: +- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings) +- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream) +- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner) +- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string) +- [Java – Generate Random String](http://www.baeldung.com/java-random-string) +- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) +- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) +- [How to Convert String to different data types in Java](http://www.baeldung.com/java-string-conversions) +- [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum) +- [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer) +- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars) +- [Split a String in Java](http://www.baeldung.com/java-split-string) +- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string) +- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string) +- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer) +- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool) +- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome) +- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings) +- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number) +- [Why Use char[] Array Over a String for Storing Passwords in Java?](http://www.baeldung.com/java-storing-passwords) +- [Convert a String to Title Case](http://www.baeldung.com/java-string-title-case) +- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string) +- [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex) +- [Convert java.util.Date to String](https://www.baeldung.com/java-util-date-to-string) diff --git a/java-strings/pom.xml b/java-strings/pom.xml new file mode 100644 index 0000000000..2afe18f07a --- /dev/null +++ b/java-strings/pom.xml @@ -0,0 +1,97 @@ + + 4.0.0 + com.baeldung + java-strings + 0.1.0-SNAPSHOT + jar + java-strings + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + commons-io + commons-io + ${commons-io.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + log4j + log4j + ${log4j.version} + + + commons-codec + commons-codec + ${commons-codec.version} + + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + com.ibm.icu + icu4j + ${icu4j.version} + + + + com.vdurmont + emoji-java + 4.0.0 + + + + + + java-strings + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + -parameters + + + + + + + + 3.5 + 1.10 + + 3.6.1 + 1.19 + 61.1 + + + \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/java-strings/src/main/java/com/baeldung/datetime/UseLocalDateTime.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java rename to java-strings/src/main/java/com/baeldung/datetime/UseLocalDateTime.java diff --git a/java-strings/src/main/java/com/baeldung/enums/PizzaStatusEnum.java b/java-strings/src/main/java/com/baeldung/enums/PizzaStatusEnum.java new file mode 100644 index 0000000000..a84829c38d --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/enums/PizzaStatusEnum.java @@ -0,0 +1,44 @@ +package com.baeldung.enums; + +public enum PizzaStatusEnum { + ORDERED(5) { + @Override + public boolean isOrdered() { + return true; + } + }, + READY(2) { + @Override + public boolean isReady() { + return true; + } + }, + DELIVERED(0) { + @Override + public boolean isDelivered() { + return true; + } + }; + + private int timeToDelivery; + + public boolean isOrdered() { + return false; + } + + public boolean isReady() { + return false; + } + + public boolean isDelivered() { + return false; + } + + public int getTimeToDelivery() { + return timeToDelivery; + } + + PizzaStatusEnum(int timeToDelivery) { + this.timeToDelivery = timeToDelivery; + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java b/java-strings/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java rename to java-strings/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java diff --git a/core-java-8/src/main/java/com/baeldung/string/JoinerSplitter.java b/java-strings/src/main/java/com/baeldung/string/JoinerSplitter.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/string/JoinerSplitter.java rename to java-strings/src/main/java/com/baeldung/string/JoinerSplitter.java diff --git a/core-java/src/main/java/com/baeldung/string/Palindrome.java b/java-strings/src/main/java/com/baeldung/string/Palindrome.java similarity index 100% rename from core-java/src/main/java/com/baeldung/string/Palindrome.java rename to java-strings/src/main/java/com/baeldung/string/Palindrome.java diff --git a/core-java/src/main/java/com/baeldung/string/StringBufferStringBuilder.java b/java-strings/src/main/java/com/baeldung/string/StringBufferStringBuilder.java similarity index 96% rename from core-java/src/main/java/com/baeldung/string/StringBufferStringBuilder.java rename to java-strings/src/main/java/com/baeldung/string/StringBufferStringBuilder.java index 74f489d57f..72af4a9aee 100644 --- a/core-java/src/main/java/com/baeldung/string/StringBufferStringBuilder.java +++ b/java-strings/src/main/java/com/baeldung/string/StringBufferStringBuilder.java @@ -1,46 +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; - } +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/core-java/src/main/java/com/baeldung/string/StringHelper.java b/java-strings/src/main/java/com/baeldung/string/StringHelper.java similarity index 100% rename from core-java/src/main/java/com/baeldung/string/StringHelper.java rename to java-strings/src/main/java/com/baeldung/string/StringHelper.java diff --git a/java-strings/src/main/java/com/baeldung/string/TitleCaseConverter.java b/java-strings/src/main/java/com/baeldung/string/TitleCaseConverter.java new file mode 100644 index 0000000000..81043f6dac --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/TitleCaseConverter.java @@ -0,0 +1,69 @@ +package com.baeldung.string; + +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.text.WordUtils; + +import com.ibm.icu.lang.UCharacter; +import com.ibm.icu.text.BreakIterator; + +public class TitleCaseConverter { + + private static final String WORD_SEPARATOR = " "; + + public static String convertToTitleCaseIteratingChars(String text) { + if (text == null || text.isEmpty()) { + return text; + } + + StringBuilder converted = new StringBuilder(); + + boolean convertNext = true; + for (char ch : text.toCharArray()) { + if (Character.isSpaceChar(ch)) { + convertNext = true; + } else if (convertNext) { + ch = Character.toTitleCase(ch); + convertNext = false; + } else { + ch = Character.toLowerCase(ch); + } + converted.append(ch); + } + + return converted.toString(); + } + + public static String convertToTitleCaseSplitting(String text) { + if (text == null || text.isEmpty()) { + return text; + } + + return Arrays + .stream(text.split(WORD_SEPARATOR)) + .map(word -> word.isEmpty() + ? word + : Character.toTitleCase(word.charAt(0)) + word + .substring(1) + .toLowerCase()) + .collect(Collectors.joining(WORD_SEPARATOR)); + } + + public static String convertToTitleCaseIcu4j(String text) { + if (text == null || text.isEmpty()) { + return text; + } + + return UCharacter.toTitleCase(text, BreakIterator.getTitleInstance()); + } + + public static String convertToTileCaseWordUtilsFull(String text) { + return WordUtils.capitalizeFully(text); + } + + public static String convertToTileCaseWordUtils(String text) { + return WordUtils.capitalize(text); + } + +} diff --git a/java-strings/src/main/java/com/baeldung/string/sorting/AnagramValidator.java b/java-strings/src/main/java/com/baeldung/string/sorting/AnagramValidator.java new file mode 100644 index 0000000000..c4f684383d --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/sorting/AnagramValidator.java @@ -0,0 +1,29 @@ +package com.baeldung.string.sorting; + +import java.util.Arrays; + +public class AnagramValidator { + + public static boolean isValid(String text, String anagram) { + text = prepare(text); + anagram = prepare(anagram); + + String sortedText = sort(text); + String sortedAnagram = sort(anagram); + + return sortedText.equals(sortedAnagram); + } + + private static String sort(String text) { + char[] chars = prepare(text).toCharArray(); + + Arrays.sort(chars); + return new String(chars); + } + + private static String prepare(String text) { + return text.toLowerCase() + .trim() + .replaceAll("\\s+", ""); + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/stringisnumeric/Benchmarking.java b/java-strings/src/main/java/com/baeldung/stringisnumeric/Benchmarking.java similarity index 100% rename from core-java/src/main/java/com/baeldung/stringisnumeric/Benchmarking.java rename to java-strings/src/main/java/com/baeldung/stringisnumeric/Benchmarking.java diff --git a/core-java/src/main/java/com/baeldung/stringisnumeric/IsNumeric.java b/java-strings/src/main/java/com/baeldung/stringisnumeric/IsNumeric.java similarity index 100% rename from core-java/src/main/java/com/baeldung/stringisnumeric/IsNumeric.java rename to java-strings/src/main/java/com/baeldung/stringisnumeric/IsNumeric.java diff --git a/core-java/src/main/java/com/baeldung/stringisnumeric/IsNumericDriver.java b/java-strings/src/main/java/com/baeldung/stringisnumeric/IsNumericDriver.java similarity index 100% rename from core-java/src/main/java/com/baeldung/stringisnumeric/IsNumericDriver.java rename to java-strings/src/main/java/com/baeldung/stringisnumeric/IsNumericDriver.java diff --git a/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java b/java-strings/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java similarity index 100% rename from core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java rename to java-strings/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java diff --git a/core-java/src/main/resources/data.csv b/java-strings/src/main/resources/data.csv similarity index 100% rename from core-java/src/main/resources/data.csv rename to java-strings/src/main/resources/data.csv diff --git a/java-strings/src/main/resources/logback.xml b/java-strings/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-strings/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java b/java-strings/src/test/java/com/baeldung/CharArrayToStringUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java rename to java-strings/src/test/java/com/baeldung/CharArrayToStringUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/CharToStringUnitTest.java b/java-strings/src/test/java/com/baeldung/CharToStringUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/CharToStringUnitTest.java rename to java-strings/src/test/java/com/baeldung/CharToStringUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/StringToCharArrayUnitTest.java b/java-strings/src/test/java/com/baeldung/StringToCharArrayUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/StringToCharArrayUnitTest.java rename to java-strings/src/test/java/com/baeldung/StringToCharArrayUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java b/java-strings/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java rename to java-strings/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java b/java-strings/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java new file mode 100644 index 0000000000..d1cfe7df19 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung.chararraypassword; + +import org.junit.Test; + +import java.util.Arrays; + +import static org.assertj.core.api.Assertions.assertThat; + +public class PasswordStoreExamplesUnitTest { + + String stringPassword = "password"; + char[] charPassword = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; + + @Test + public void givenStringHashCode_WhenStringValueChanged_ThenHashCodesNotEqualAndValesNotEqual() { + String originalHashCode = Integer.toHexString(stringPassword.hashCode()); + + stringPassword = "********"; + String changedHashCode = Integer.toHexString(stringPassword.hashCode()); + + assertThat(originalHashCode).isNotEqualTo(changedHashCode); + assertThat(stringPassword).isNotEqualTo("password"); + } + + @Test + public void givenStringHashCode_WhenStringValueChangedAndStringValueReassigned_ThenHashCodesEqualAndValesEqual() { + String originalHashCode = Integer.toHexString(stringPassword.hashCode()); + + stringPassword = "********"; + stringPassword = "password"; + String reassignedHashCode = Integer.toHexString(stringPassword.hashCode()); + + assertThat(originalHashCode).isEqualTo(reassignedHashCode); + assertThat(stringPassword).isEqualTo("password"); + } + + @Test + public void givenStringHashCode_WhenStringValueReplaced_ThenHashCodesEqualAndValesEqual() { + String originalHashCode = Integer.toHexString(stringPassword.hashCode()); + + String newString = "********"; + stringPassword.replace(stringPassword, newString); + + String hashCodeAfterReplace = Integer.toHexString(stringPassword.hashCode()); + + assertThat(originalHashCode).isEqualTo(hashCodeAfterReplace); + assertThat(stringPassword).isEqualTo("password"); + } + + @Test + public void givenCharArrayHashCode_WhenArrayElementsValueChanged_ThenHashCodesEqualAndValesNotEqual() { + String originalHashCode = Integer.toHexString(charPassword.hashCode()); + + Arrays.fill(charPassword, '*'); + String changedHashCode = Integer.toHexString(charPassword.hashCode()); + + assertThat(originalHashCode).isEqualTo(changedHashCode); + assertThat(charPassword).isNotEqualTo(new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}); + } + + @Test + public void whenCallingToStringOfString_ThenValuesEqual() { + assertThat(stringPassword.toString()).isEqualTo("password"); + } + + @Test + public void whenCallingToStringOfCharArray_ThenValuesNotEqual() { + assertThat(charPassword.toString()).isNotEqualTo("password"); + } +} diff --git a/java-strings/src/test/java/com/baeldung/enums/PizzaUnitTest.java b/java-strings/src/test/java/com/baeldung/enums/PizzaUnitTest.java new file mode 100644 index 0000000000..3e52a89bad --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/enums/PizzaUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.enums; + +import static junit.framework.TestCase.assertTrue; + +import org.junit.Test; + +public class PizzaUnitTest { + + @Test + public void whenConvertedIntoEnum_thenGetsConvertedCorrectly() { + String pizzaEnumValue = "READY"; + PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue); + assertTrue(pizzaStatusEnum == PizzaStatusEnum.READY); + } + + @Test(expected = IllegalArgumentException.class) + public void whenConvertedIntoEnum_thenThrowsException() { + String pizzaEnumValue = "rEAdY"; + PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue); + } + + @Test(expected = IllegalArgumentException.class) + public void givenInvalidEnumValueContentWiseAsString_whenConvertedIntoEnum_thenThrowsException() { + String pizzaEnumValue = "invalid"; + PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue); + } +} \ No newline at end of file diff --git a/java-strings/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java b/java-strings/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java new file mode 100644 index 0000000000..eef21a98c9 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.fileToBase64StringConversion; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.util.Base64; + +import org.apache.commons.io.FileUtils; +import org.junit.Test; + +public class FileToBase64StringConversionUnitTest { + + private String inputFilePath = "test_image.jpg"; + private String outputFilePath = "test_image_copy.jpg"; + + @Test + public void fileToBase64StringConversion() throws IOException { + //load file from /src/test/resources + ClassLoader classLoader = getClass().getClassLoader(); + File inputFile = new File(classLoader + .getResource(inputFilePath) + .getFile()); + + byte[] fileContent = FileUtils.readFileToByteArray(inputFile); + String encodedString = Base64 + .getEncoder() + .encodeToString(fileContent); + + //create output file + File outputFile = new File(inputFile + .getParentFile() + .getAbsolutePath() + File.pathSeparator + outputFilePath); + + // decode the string and write to file + byte[] decodedBytes = Base64 + .getDecoder() + .decode(encodedString); + FileUtils.writeByteArrayToFile(outputFile, decodedBytes); + + assertTrue(FileUtils.contentEquals(inputFile, outputFile)); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/conversion/README.md b/java-strings/src/test/java/com/baeldung/java/conversion/README.md similarity index 100% rename from core-java/src/test/java/com/baeldung/java/conversion/README.md rename to java-strings/src/test/java/com/baeldung/java/conversion/README.md diff --git a/core-java/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java b/java-strings/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java rename to java-strings/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java b/java-strings/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java rename to java-strings/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java index aeb33fe875..e2dd0ac1db 100644 --- a/core-java/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java +++ b/java-strings/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java @@ -1,13 +1,14 @@ package com.baeldung.java.countingChars; -import com.google.common.base.CharMatcher; -import org.apache.commons.lang.StringUtils; -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.util.regex.Matcher; import java.util.regex.Pattern; -import static org.junit.Assert.assertEquals; +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; + +import com.google.common.base.CharMatcher; /*** diff --git a/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java b/java-strings/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java rename to java-strings/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java b/java-strings/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java rename to java-strings/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java rename to java-strings/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java b/java-strings/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java rename to java-strings/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/PalindromeUnitTest.java b/java-strings/src/test/java/com/baeldung/string/PalindromeUnitTest.java new file mode 100644 index 0000000000..49f2542f39 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/PalindromeUnitTest.java @@ -0,0 +1,97 @@ +package com.baeldung.string; + +import static org.junit.Assert.*; +import org.junit.Test; + +public class PalindromeUnitTest { + + private String[] words = { + "Anna", + "Civic", + "Kayak", + "Level", + "Madam", + }; + + private String[] sentences = { + "Sore was I ere I saw Eros", + "Euston saw I was not Sue", + "Too hot to hoot", + "No mists or frost Simon", + "Stella won no wallets" + }; + + private Palindrome palindrome = new Palindrome(); + + @Test + public void whenWord_shouldBePalindrome() { + for (String word : words) + assertTrue(palindrome.isPalindrome(word)); + } + + @Test + public void whenSentence_shouldBePalindrome() { + for (String sentence : sentences) + assertTrue(palindrome.isPalindrome(sentence)); + } + + @Test + public void whenReverseWord_shouldBePalindrome() { + for (String word : words) + assertTrue(palindrome.isPalindromeReverseTheString(word)); + } + + @Test + public void whenReverseSentence_shouldBePalindrome() { + for (String sentence : sentences) + assertTrue(palindrome.isPalindromeReverseTheString(sentence)); + } + + @Test + public void whenStringBuilderWord_shouldBePalindrome() { + for (String word : words) + assertTrue(palindrome.isPalindromeUsingStringBuilder(word)); + } + + @Test + public void whenStringBuilderSentence_shouldBePalindrome() { + for (String sentence : sentences) + assertTrue(palindrome.isPalindromeUsingStringBuilder(sentence)); + } + + @Test + public void whenStringBufferWord_shouldBePalindrome() { + for (String word : words) + assertTrue(palindrome.isPalindromeUsingStringBuffer(word)); + } + + @Test + public void whenStringBufferSentence_shouldBePalindrome() { + for (String sentence : sentences) + assertTrue(palindrome.isPalindromeUsingStringBuffer(sentence)); + } + + @Test + public void whenPalindromeRecursive_wordShouldBePalindrome() { + for (String word : words) + assertTrue(palindrome.isPalindromeRecursive(word)); + } + + @Test + public void whenPalindromeRecursive_sentenceShouldBePalindrome() { + for (String sentence : sentences) + assertTrue(palindrome.isPalindromeRecursive(sentence)); + } + + @Test + public void whenPalindromeStreams_wordShouldBePalindrome() { + for (String word : words) + assertTrue(palindrome.isPalindromeUsingIntStream(word)); + } + + @Test + public void whenPalindromeStreams_sentenceShouldBePalindrome() { + for (String sentence : sentences) + assertTrue(palindrome.isPalindromeUsingIntStream(sentence)); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java new file mode 100644 index 0000000000..8688f9dcf5 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.string; + +import static org.junit.Assert.assertEquals; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.Test; + +import com.vdurmont.emoji.EmojiParser; + +public class RemovingEmojiFromStringUnitTest { + String text = "la conférence, commencera à 10 heures 😅"; + String regex = "[^\\p{L}\\p{N}\\p{P}\\p{Z}]"; + + @Test + public void whenRemoveEmojiUsingLibrary_thenSuccess() { + String result = EmojiParser.removeAllEmojis(text); + System.out.println(result); + assertEquals(result, "la conférence, commencera à 10 heures "); + } + + @Test + public void whenReplaceEmojiUsingLibrary_thenSuccess() { + String result = EmojiParser.parseToAliases(text); + System.out.println(result); + assertEquals(result, "la conférence, commencera à 10 heures :sweat_smile:"); + } + + @Test + public void whenRemoveEmojiUsingRegex_thenSuccess() { + String result = text.replaceAll(regex, ""); + System.out.println(result); + assertEquals(result, "la conférence, commencera à 10 heures "); + } + + @Test + public void whenRemoveEmojiUsingMatcher_thenSuccess() { + Pattern pattern = Pattern.compile(regex, Pattern.UNICODE_CHARACTER_CLASS); + Matcher matcher = pattern.matcher(text); + + String result = matcher.replaceAll(""); + System.out.println(result); + assertEquals(result, "la conférence, commencera à 10 heures "); + } + + @Test + public void whenRemoveEmojiUsingCodepoints_thenSuccess() { + String result = text.replaceAll("[\\x{0001f300}-\\x{0001f64f}]|[\\x{0001f680}-\\x{0001f6ff}]", ""); + System.out.println(result); + assertEquals(result, "la conférence, commencera à 10 heures "); + } + + @Test + public void whenRemoveEmojiUsingUnicode_thenSuccess() { + String result = text.replaceAll("[\ud83c\udf00-\ud83d\ude4f]|[\ud83d\ude80-\ud83d\udeff]", ""); + System.out.println(result); + assertEquals(result, "la conférence, commencera à 10 heures "); + } +} diff --git a/core-java/src/test/java/com/baeldung/string/SplitUnitTest.java b/java-strings/src/test/java/com/baeldung/string/SplitUnitTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/string/SplitUnitTest.java rename to java-strings/src/test/java/com/baeldung/string/SplitUnitTest.java index 83fd253b97..3859a2b26b 100644 --- a/core-java/src/test/java/com/baeldung/string/SplitUnitTest.java +++ b/java-strings/src/test/java/com/baeldung/string/SplitUnitTest.java @@ -1,12 +1,13 @@ package com.baeldung.string; -import com.google.common.base.Splitter; -import org.apache.commons.lang.StringUtils; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; + +import com.google.common.base.Splitter; public class SplitUnitTest { diff --git a/java-strings/src/test/java/com/baeldung/string/StringComparisonUnitTest.java b/java-strings/src/test/java/com/baeldung/string/StringComparisonUnitTest.java new file mode 100644 index 0000000000..539f66d9b4 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/StringComparisonUnitTest.java @@ -0,0 +1,154 @@ +package com.baeldung.string; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; + +import java.util.Objects; + +import static org.assertj.core.api.Assertions.assertThat; + +public class StringComparisonUnitTest { + + @Test + public void whenUsingComparisonOperator_ThenComparingStrings(){ + + String string1 = "using comparison operator"; + String string2 = "using comparison operator"; + String string3 = new String("using comparison operator"); + + assertThat(string1 == string2).isTrue(); + assertThat(string1 == string3).isFalse(); + } + + @Test + public void whenUsingEqualsMethod_ThenComparingStrings(){ + + String string1 = "using equals method"; + String string2 = "using equals method"; + + String string3 = "using EQUALS method"; + String string4 = new String("using equals method"); + + assertThat(string1.equals(string2)).isTrue(); + assertThat(string1.equals(string4)).isTrue(); + + assertThat(string1.equals(null)).isFalse(); + assertThat(string1.equals(string3)).isFalse(); + } + + @Test + public void whenUsingEqualsIgnoreCase_ThenComparingStrings(){ + + String string1 = "using equals ignore case"; + String string2 = "USING EQUALS IGNORE CASE"; + + assertThat(string1.equalsIgnoreCase(string2)).isTrue(); + } + + @Test + public void whenUsingCompareTo_ThenComparingStrings(){ + + String author = "author"; + String book = "book"; + String duplicateBook = "book"; + + assertThat(author.compareTo(book)).isEqualTo(-1); + assertThat(book.compareTo(author)).isEqualTo(1); + assertThat(duplicateBook.compareTo(book)).isEqualTo(0); + } + + @Test + public void whenUsingCompareToIgnoreCase_ThenComparingStrings(){ + + String author = "Author"; + String book = "book"; + String duplicateBook = "BOOK"; + + assertThat(author.compareToIgnoreCase(book)).isEqualTo(-1); + assertThat(book.compareToIgnoreCase(author)).isEqualTo(1); + assertThat(duplicateBook.compareToIgnoreCase(book)).isEqualTo(0); + } + + @Test + public void whenUsingObjectsEqualsMethod_ThenComparingStrings(){ + + String string1 = "using objects equals"; + String string2 = "using objects equals"; + String string3 = new String("using objects equals"); + + assertThat(Objects.equals(string1, string2)).isTrue(); + assertThat(Objects.equals(string1, string3)).isTrue(); + + assertThat(Objects.equals(null, null)).isTrue(); + assertThat(Objects.equals(null, string1)).isFalse(); + } + + @Test + public void whenUsingEqualsOfApacheCommons_ThenComparingStrings(){ + + assertThat(StringUtils.equals(null, null)).isTrue(); + assertThat(StringUtils.equals(null, "equals method")).isFalse(); + assertThat(StringUtils.equals("equals method", "equals method")).isTrue(); + assertThat(StringUtils.equals("equals method", "EQUALS METHOD")).isFalse(); + } + + @Test + public void whenUsingEqualsIgnoreCaseOfApacheCommons_ThenComparingStrings(){ + + assertThat(StringUtils.equalsIgnoreCase(null, null)).isTrue(); + assertThat(StringUtils.equalsIgnoreCase(null, "equals method")).isFalse(); + assertThat(StringUtils.equalsIgnoreCase("equals method", "equals method")).isTrue(); + assertThat(StringUtils.equalsIgnoreCase("equals method", "EQUALS METHOD")).isTrue(); + } + + @Test + public void whenUsingEqualsAnyOf_ThenComparingStrings(){ + + assertThat(StringUtils.equalsAny(null, null, null)).isTrue(); + assertThat(StringUtils.equalsAny("equals any", "equals any", "any")).isTrue(); + assertThat(StringUtils.equalsAny("equals any", null, "equals any")).isTrue(); + assertThat(StringUtils.equalsAny(null, "equals", "any")).isFalse(); + assertThat(StringUtils.equalsAny("equals any", "EQUALS ANY", "ANY")).isFalse(); + } + + @Test + public void whenUsingEqualsAnyIgnoreCase_ThenComparingStrings(){ + + assertThat(StringUtils.equalsAnyIgnoreCase(null, null, null)).isTrue(); + assertThat(StringUtils.equalsAnyIgnoreCase("equals any", "equals any", "any")).isTrue(); + assertThat(StringUtils.equalsAnyIgnoreCase("equals any", null, "equals any")).isTrue(); + assertThat(StringUtils.equalsAnyIgnoreCase(null, "equals", "any")).isFalse(); + assertThat(StringUtils.equalsAnyIgnoreCase( + "equals any ignore case", "EQUALS ANY IGNORE CASE", "any")).isTrue(); + } + + @Test + public void whenUsingCompare_thenComparingStringsWithNulls(){ + + assertThat(StringUtils.compare(null, null)).isEqualTo(0); + assertThat(StringUtils.compare(null, "abc")).isEqualTo(-1); + + assertThat(StringUtils.compare("abc", "bbc")).isEqualTo(-1); + assertThat(StringUtils.compare("bbc", "abc")).isEqualTo(1); + assertThat(StringUtils.compare("abc", "abc")).isEqualTo(0); + } + + @Test + public void whenUsingCompareIgnoreCase_ThenComparingStringsWithNulls(){ + + assertThat(StringUtils.compareIgnoreCase(null, null)).isEqualTo(0); + assertThat(StringUtils.compareIgnoreCase(null, "abc")).isEqualTo(-1); + + assertThat(StringUtils.compareIgnoreCase("Abc", "bbc")).isEqualTo(-1); + assertThat(StringUtils.compareIgnoreCase("bbc", "ABC")).isEqualTo(1); + assertThat(StringUtils.compareIgnoreCase("abc", "ABC")).isEqualTo(0); + } + + @Test + public void whenUsingCompareWithNullIsLessOption_ThenComparingStrings(){ + + assertThat(StringUtils.compare(null, "abc", true)).isEqualTo(-1); + assertThat(StringUtils.compare(null, "abc", false)).isEqualTo(1); + } + +} diff --git a/java-strings/src/test/java/com/baeldung/string/StringContainingCharactersUnitTest.java b/java-strings/src/test/java/com/baeldung/string/StringContainingCharactersUnitTest.java new file mode 100644 index 0000000000..be79103e6b --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/StringContainingCharactersUnitTest.java @@ -0,0 +1,136 @@ +package com.baeldung.string; + +import org.junit.Test; + +import java.util.regex.Pattern; + +import static junit.framework.TestCase.assertFalse; +import static junit.framework.TestCase.assertTrue; + +public class StringContainingCharactersUnitTest { + + private static final Pattern[] inputRegexes = new Pattern[4]; + + private static final String regex = "^(?=.*?\\p{Lu})(?=.*?\\p{Ll})(?=.*?\\d)(?=.*?[`~!@#$%^&*()\\-_=+\\\\|\\[{\\]};:'\",<.>/?]).*$"; + + static { + inputRegexes[0] = Pattern.compile(".*[A-Z].*"); + inputRegexes[1] = Pattern.compile(".*[a-z].*"); + inputRegexes[2] = Pattern.compile(".*\\d.*"); + inputRegexes[3] = Pattern.compile(".*[`~!@#$%^&*()\\-_=+\\\\|\\[{\\]};:'\",<.>/?].*"); + } + + private static boolean isMatchingRegex(String input) { + boolean inputMatches = true; + for (Pattern inputRegex : inputRegexes) { + if (!inputRegex + .matcher(input) + .matches()) { + inputMatches = false; + } + } + return inputMatches; + } + + private static boolean checkString(String input) { + String specialChars = "~`!@#$%^&*()-_=+\\|[{]};:'\",<.>/?"; + char currentCharacter; + boolean numberPresent = false; + boolean upperCasePresent = false; + boolean lowerCasePresent = false; + boolean specialCharacterPresent = false; + + for (int i = 0; i < input.length(); i++) { + currentCharacter = input.charAt(i); + if (Character.isDigit(currentCharacter)) { + numberPresent = true; + } else if (Character.isUpperCase(currentCharacter)) { + upperCasePresent = true; + } else if (Character.isLowerCase(currentCharacter)) { + lowerCasePresent = true; + } else if (specialChars.contains(String.valueOf(currentCharacter))) { + specialCharacterPresent = true; + } + } + + return numberPresent && upperCasePresent && lowerCasePresent && specialCharacterPresent; + } + + @Test + public void givenRegexes_whenMatchingCorrectString_thenMatches() { + String validInput = "Ab3;"; + assertTrue(isMatchingRegex(validInput)); + } + + @Test + public void givenRegexes_whenMatchingWrongStrings_thenNotMatching() { + String invalidInput = "Ab3"; + assertFalse(isMatchingRegex(invalidInput)); + + invalidInput = "Ab;"; + assertFalse(isMatchingRegex(invalidInput)); + + invalidInput = "A3;"; + assertFalse(isMatchingRegex(invalidInput)); + + invalidInput = "b3;"; + assertFalse(isMatchingRegex(invalidInput)); + } + + @Test + public void givenValidString_whenChecking_thenCorrect() { + String validInput = "Ab3;"; + assertTrue(checkString(validInput)); + } + + @Test + public void givenInvalidStrings_whenChecking_thenNotCorrect() { + String invalidInput = "Ab3"; + assertFalse(checkString(invalidInput)); + + invalidInput = "Ab;"; + assertFalse(checkString(invalidInput)); + + invalidInput = "A3;"; + assertFalse(checkString(invalidInput)); + + invalidInput = "b3;"; + assertFalse(checkString(invalidInput)); + } + + @Test + public void givenSingleRegex_whenMatchingCorrectString_thenMatches() { + String validInput = "Ab3;"; + assertTrue(Pattern + .compile(regex) + .matcher(validInput) + .matches()); + } + + @Test + public void givenSingleRegex_whenMatchingWrongStrings_thenNotMatching() { + String invalidInput = "Ab3"; + assertFalse(Pattern + .compile(regex) + .matcher(invalidInput) + .matches()); + + invalidInput = "Ab;"; + assertFalse(Pattern + .compile(regex) + .matcher(invalidInput) + .matches()); + + invalidInput = "A3;"; + assertFalse(Pattern + .compile(regex) + .matcher(invalidInput) + .matches()); + + invalidInput = "b3;"; + assertFalse(Pattern + .compile(regex) + .matcher(invalidInput) + .matches()); + } +} diff --git a/core-java/src/test/java/com/baeldung/string/StringHelperUnitTest.java b/java-strings/src/test/java/com/baeldung/string/StringHelperUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/string/StringHelperUnitTest.java rename to java-strings/src/test/java/com/baeldung/string/StringHelperUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java b/java-strings/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java rename to java-strings/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/StringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/StringUnitTest.java new file mode 100644 index 0000000000..0d4fd6eff9 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/StringUnitTest.java @@ -0,0 +1,226 @@ +package com.baeldung.string; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.util.IllegalFormatException; +import java.util.regex.PatternSyntaxException; + +import org.junit.Test; + +public class StringUnitTest { + + @Test + public void whenCallCodePointAt_thenDecimalUnicodeReturned() { + assertEquals(97, "abcd".codePointAt(0)); + } + + @Test(expected = StringIndexOutOfBoundsException.class) + public void whenPassNonExistingIndex_thenExceptionThrown() { + int a = "abcd".codePointAt(4); + } + + @Test + public void whenCallConcat_thenCorrect() { + assertEquals("elephant", "elep".concat("hant")); + } + + @Test + public void whenGetBytes_thenCorrect() throws UnsupportedEncodingException { + byte[] byteArray1 = "abcd".getBytes(); + byte[] byteArray2 = "efgh".getBytes(StandardCharsets.US_ASCII); + byte[] byteArray3 = "ijkl".getBytes("UTF-8"); + byte[] expected1 = new byte[] { 97, 98, 99, 100 }; + byte[] expected2 = new byte[] { 101, 102, 103, 104 }; + byte[] expected3 = new byte[] { 105, 106, 107, 108 }; + + assertArrayEquals(expected1, byteArray1); + assertArrayEquals(expected2, byteArray2); + assertArrayEquals(expected3, byteArray3); + } + + @Test + public void whenGetBytesUsingASCII_thenCorrect() { + byte[] byteArray = "efgh".getBytes(StandardCharsets.US_ASCII); + byte[] expected = new byte[] { 101, 102, 103, 104 }; + + assertArrayEquals(expected, byteArray); + } + + @Test + public void whenCreateStringUsingByteArray_thenCorrect() { + byte[] array = new byte[] { 97, 98, 99, 100 }; + String s = new String(array); + + assertEquals("abcd", s); + } + + @Test + public void whenCallCharAt_thenCorrect() { + assertEquals('P', "Paul".charAt(0)); + } + + @Test(expected = IndexOutOfBoundsException.class) + public void whenCharAtOnNonExistingIndex_thenIndexOutOfBoundsExceptionThrown() { + char character = "Paul".charAt(4); + } + + @Test + public void whenCallCodePointCount_thenCorrect() { + assertEquals(2, "abcd".codePointCount(0, 2)); + } + + @Test(expected = IndexOutOfBoundsException.class) + public void whenSecondIndexEqualToLengthOfString_thenIndexOutOfBoundsExceptionThrown() { + char character = "Paul".charAt(4); + } + + @Test + public void whenCallContains_thenCorrect() { + String s = "abcd"; + + assertTrue(s.contains("abc")); + assertFalse(s.contains("cde")); + } + + @Test + public void whenCallCopyValueOf_thenStringConstructed() { + char[] array = new char[] { 'a', 'b', 'c', 'd' }; + + assertEquals("abcd", String.copyValueOf(array)); + } + + @Test + public void whenCallEndsWith_thenCorrect() { + String s1 = "test"; + + assertTrue(s1.endsWith("t")); + } + + @Test + public void whenFormat_thenCorrect() { + String value = "Baeldung"; + String formatted = String.format("Welcome to %s!", value); + + assertEquals("Welcome to Baeldung!", formatted); + } + + @Test(expected = IllegalFormatException.class) + public void whenInvalidFormatSyntax_thenIllegalFormatExceptionThrown() { + String value = "Baeldung"; + String formatted = String.format("Welcome to %x!", value); + } + + @Test + public void whenCallIndexOf_thenCorrect() { + assertEquals(1, "foo".indexOf("o")); + } + + @Test + public void whenCallIsEmpty_thenCorrect() { + String s1 = ""; + + assertTrue(s1.isEmpty()); + } + + @Test + public void whenCallLastIndexOf_thenCorrect() { + assertEquals(2, "foo".lastIndexOf("o")); + assertEquals(2, "foo".lastIndexOf(111)); + } + + @Test + public void whenCallRegionMatches_thenCorrect() { + assertTrue("welcome to baeldung".regionMatches(false, 11, "baeldung", 0, 8)); + } + + @Test + public void whenCallStartsWith_thenCorrect() { + assertTrue("foo".startsWith("f")); + } + + @Test + public void whenTrim_thenCorrect() { + assertEquals("foo", " foo ".trim()); + } + + @Test + public void whenSplit_thenCorrect() { + String s = "Welcome to Baeldung"; + String[] array = new String[] { "Welcome", "to", "Baeldung" }; + + assertArrayEquals(array, s.split(" ")); + } + + @Test(expected = PatternSyntaxException.class) + public void whenPassInvalidParameterToSplit_thenPatternSyntaxExceptionThrown() { + String s = "Welcome*to Baeldung"; + + String[] result = s.split("*"); + } + + @Test + public void whenCallSubSequence_thenCorrect() { + String s = "Welcome to Baeldung"; + + assertEquals("Welcome", s.subSequence(0, 7)); + } + + @Test + public void whenCallSubstring_thenCorrect() { + String s = "Welcome to Baeldung"; + + assertEquals("Welcome", s.substring(0, 7)); + } + + @Test(expected = IndexOutOfBoundsException.class) + public void whenSecondIndexEqualToLengthOfString_thenCorrect() { + String s = "Welcome to Baeldung"; + + String sub = s.substring(0, 20); + } + + @Test + public void whenConvertToUpperCase_thenCorrect() { + String s = "Welcome to Baeldung!"; + + assertEquals("WELCOME TO BAELDUNG!", s.toUpperCase()); + } + + @Test + public void whenConvertToLowerCase_thenCorrect() { + String s = "WELCOME to BAELDUNG!"; + + assertEquals("welcome to baeldung!", s.toLowerCase()); + } + + @Test + public void whenCallReplace_thenCorrect() { + String s = "I learn Spanish"; + + assertEquals("I learn French", s.replaceAll("Spanish", "French")); + } + + @Test + public void whenIntern_thenCorrect() { + String s1 = "abc"; + String s2 = new String("abc"); + String s3 = new String("foo"); + String s4 = s1.intern(); + String s5 = s2.intern(); + + assertFalse(s3 == s4); + assertTrue(s1 == s5); + } + + @Test + public void whenCallValueOf_thenCorrect() { + long l = 200L; + + assertEquals("200", String.valueOf(l)); + } +} \ No newline at end of file diff --git a/java-strings/src/test/java/com/baeldung/string/SubstringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/SubstringUnitTest.java new file mode 100644 index 0000000000..3a4e231828 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/SubstringUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.string; + +import java.util.Scanner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Assert; +import org.junit.Test; + +public class SubstringUnitTest { + + String text = "Julia Evans was born on 25-09-1984. She is currently living in the USA (United States of America)."; + + @Test + public void givenAString_whenUsedStringUtils_ShouldReturnProperSubstring() { + Assert.assertEquals("United States of America", StringUtils.substringBetween(text, "(", ")")); + Assert.assertEquals("the USA (United States of America).", StringUtils.substringAfter(text, "living in ")); + Assert.assertEquals("Julia Evans", StringUtils.substringBefore(text, " was born")); + } + + @Test + public void givenAString_whenUsedScanner_ShouldReturnProperSubstring() { + try (Scanner scanner = new Scanner(text)) { + scanner.useDelimiter("\\."); + Assert.assertEquals("Julia Evans was born on 25-09-1984", scanner.next()); + } + } + + @Test + public void givenAString_whenUsedSplit_ShouldReturnProperSubstring() { + String[] sentences = text.split("\\."); + Assert.assertEquals("Julia Evans was born on 25-09-1984", sentences[0]); + } + + @Test + public void givenAString_whenUsedRegex_ShouldReturnProperSubstring() { + Pattern pattern = Pattern.compile("\\d{2}\\-\\d{2}-\\d{4}"); + Matcher matcher = pattern.matcher(text); + + if (matcher.find()) { + Assert.assertEquals("25-09-1984", matcher.group()); + } + } + + @Test + public void givenAString_whenUsedSubSequence_ShouldReturnProperSubstring() { + Assert.assertEquals("USA (United States of America)", text.subSequence(67, text.length() - 1)); + } + + @Test + public void givenAString_whenUsedSubstring_ShouldReturnProperSubstring() { + Assert.assertEquals("USA (United States of America).", text.substring(67)); + Assert.assertEquals("USA (United States of America)", text.substring(67, text.length() - 1)); + } + + @Test + public void givenAString_whenUsedSubstringWithIndexOf_ShouldReturnProperSubstring() { + Assert.assertEquals("United States of America", text.substring(text.indexOf('(') + 1, text.indexOf(')'))); + } + +} diff --git a/java-strings/src/test/java/com/baeldung/string/TitleCaseConverterUnitTest.java b/java-strings/src/test/java/com/baeldung/string/TitleCaseConverterUnitTest.java new file mode 100644 index 0000000000..2272565cd3 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/TitleCaseConverterUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung.string; + +import org.junit.Assert; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class TitleCaseConverterUnitTest { + + private static final String TEXT = "tHis IS a tiTLe"; + private static final String TEXT_EXPECTED = "This Is A Title"; + private static final String TEXT_EXPECTED_NOT_FULL = "THis IS A TiTLe"; + + private static final String TEXT_OTHER_DELIMITERS = "tHis, IS a tiTLe"; + private static final String TEXT_EXPECTED_OTHER_DELIMITERS = "This, Is A Title"; + private static final String TEXT_EXPECTED_OTHER_DELIMITERS_NOT_FULL = "THis, IS A TiTLe"; + + @Test + public void whenConvertingToTitleCaseIterating_thenStringConverted() { + assertEquals(TEXT_EXPECTED, TitleCaseConverter.convertToTitleCaseIteratingChars(TEXT)); + } + + @Test + public void whenConvertingToTitleCaseSplitting_thenStringConverted() { + assertEquals(TEXT_EXPECTED, TitleCaseConverter.convertToTitleCaseSplitting(TEXT)); + } + + @Test + public void whenConvertingToTitleCaseUsingWordUtilsFull_thenStringConverted() { + assertEquals(TEXT_EXPECTED, TitleCaseConverter.convertToTileCaseWordUtilsFull(TEXT)); + } + + @Test + public void whenConvertingToTitleCaseUsingWordUtils_thenStringConvertedOnlyFirstCharacter() { + assertEquals(TEXT_EXPECTED_NOT_FULL, TitleCaseConverter.convertToTileCaseWordUtils(TEXT)); + } + + @Test + public void whenConvertingToTitleCaseUsingIcu4j_thenStringConverted() { + assertEquals(TEXT_EXPECTED, TitleCaseConverter.convertToTitleCaseIcu4j(TEXT)); + } + + @Test + public void whenConvertingToTitleCaseWithDifferentDelimiters_thenDelimitersKept() { + assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS, TitleCaseConverter.convertToTitleCaseIteratingChars(TEXT_OTHER_DELIMITERS)); + assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS, TitleCaseConverter.convertToTitleCaseSplitting(TEXT_OTHER_DELIMITERS)); + assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS, TitleCaseConverter.convertToTileCaseWordUtilsFull(TEXT_OTHER_DELIMITERS)); + assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS_NOT_FULL, TitleCaseConverter.convertToTileCaseWordUtils(TEXT_OTHER_DELIMITERS)); + assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS, TitleCaseConverter.convertToTitleCaseIcu4j(TEXT_OTHER_DELIMITERS)); + } + + @Test + public void givenNull_whenConvertingToTileCase_thenReturnNull() { + assertEquals(null, TitleCaseConverter.convertToTitleCaseIteratingChars(null)); + assertEquals(null, TitleCaseConverter.convertToTitleCaseSplitting(null)); + assertEquals(null, TitleCaseConverter.convertToTileCaseWordUtilsFull(null)); + assertEquals(null, TitleCaseConverter.convertToTileCaseWordUtils(null)); + assertEquals(null, TitleCaseConverter.convertToTitleCaseIcu4j(null)); + } + + @Test + public void givenEmptyString_whenConvertingToTileCase_thenReturnEmptyString() { + assertEquals("", TitleCaseConverter.convertToTitleCaseIteratingChars("")); + assertEquals("", TitleCaseConverter.convertToTitleCaseSplitting("")); + assertEquals("", TitleCaseConverter.convertToTileCaseWordUtilsFull("")); + assertEquals("", TitleCaseConverter.convertToTileCaseWordUtils("")); + assertEquals("", TitleCaseConverter.convertToTitleCaseIcu4j("")); + } + +} diff --git a/java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java b/java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java new file mode 100644 index 0000000000..f236c641c3 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java @@ -0,0 +1,67 @@ +package com.baeldung.string.formatter; + +import org.junit.BeforeClass; +import org.junit.Test; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; + +import static org.junit.Assert.assertEquals; + +public class DateToStringFormatterUnitTest { + + private static final String DATE_FORMAT = "MMM d, yyyy HH:mm a"; + private static final String EXPECTED_STRING_DATE = "Aug 1, 2018 12:00 PM"; + private static Date date; + + @BeforeClass + public static void setUp() { + TimeZone.setDefault(TimeZone.getTimeZone("CET")); + Calendar calendar = Calendar.getInstance(); + calendar.set(2018, Calendar.AUGUST, 1, 12, 0); + date = calendar.getTime(); + } + + @Test + public void whenDateConvertedUsingSimpleDateFormatToString_thenCorrect() { + DateFormat formatter = new SimpleDateFormat(DATE_FORMAT); + String formattedDate = formatter.format(date); + + assertEquals(EXPECTED_STRING_DATE, formattedDate); + } + + @Test + public void whenDateConvertedUsingDateFormatToString_thenCorrect() { + String formattedDate = DateFormat + .getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT) + .format(date); + + assertEquals(EXPECTED_STRING_DATE, formattedDate); + } + + @Test + public void whenDateConvertedUsingFormatterToString_thenCorrect() { + String formattedDate = String.format("%1$tb %1$te, %1$tY %1$tI:%1$tM %1$Tp", date); + + assertEquals(EXPECTED_STRING_DATE, formattedDate); + } + + @Test + public void whenDateConvertedUsingDateTimeApiToString_thenCorrect() { + DateTimeFormatter fmt = DateTimeFormatter.ofPattern(DATE_FORMAT); + Instant instant = date.toInstant(); + LocalDateTime ldt = instant + .atZone(ZoneId.of("CET")) + .toLocalDateTime(); + String formattedDate = ldt.format(fmt); + + assertEquals(EXPECTED_STRING_DATE, formattedDate); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java b/java-strings/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java new file mode 100644 index 0000000000..648fdaf65a --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java @@ -0,0 +1,141 @@ +package com.baeldung.string.formatter; + +import java.util.Calendar; +import java.util.Formatter; +import java.util.GregorianCalendar; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class StringFormatterExampleUnitTest { + + @Test + public void givenString_whenFormatSpecifierForCalendar_thenGotExpected() { + //Syntax of Format Specifiers for Date/Time Representation + Calendar c = new GregorianCalendar(2017, 11, 10); + String s = String.format("The date is: %tm %1$te,%1$tY", c); + + + assertEquals("The date is: 12 10,2017", s); + } + + @Test + public void givenString_whenGeneralConversion_thenConvertedString() { + //General Conversions + String s = String.format("The correct answer is %s", false); + assertEquals("The correct answer is false", s); + + s = String.format("The correct answer is %b", null); + assertEquals("The correct answer is false", s); + + s = String.format("The correct answer is %B", true); + assertEquals("The correct answer is TRUE", s); + } + + @Test + public void givenString_whenCharConversion_thenConvertedString() { + //Character Conversions + String s = String.format("The correct answer is %c", 'a'); + assertEquals("The correct answer is a", s); + + s = String.format("The correct answer is %c", null); + assertEquals("The correct answer is null", s); + + s = String.format("The correct answer is %C", 'b'); + assertEquals("The correct answer is B", s); + + s = String.format("The valid unicode character: %c", 0x0400); + assertTrue(Character.isValidCodePoint(0x0400)); + assertEquals("The valid unicode character: Ѐ", s); + } + + @Test(expected = java.util.IllegalFormatCodePointException.class) + public void givenString_whenIllegalCodePointForConversion_thenError() { + String s = String.format("The valid unicode character: %c", 0x11FFFF); + assertFalse(Character.isValidCodePoint(0x11FFFF)); + assertEquals("The valid unicode character: Ä€", s); + } + + @Test + public void givenString_whenNumericIntegralConversion_thenConvertedString() { + //Numeric Integral Conversions + String s = String.format("The number 25 in decimal = %d", 25); + assertEquals("The number 25 in decimal = 25", s); + + s = String.format("The number 25 in octal = %o", 25); + assertEquals("The number 25 in octal = 31", s); + + s = String.format("The number 25 in hexadecimal = %x", 25); + assertEquals("The number 25 in hexadecimal = 19", s); + } + + @Test + public void givenString_whenNumericFloatingConversion_thenConvertedString() { + //Numeric Floating-point Conversions + String s = String.format("The computerized scientific format of 10000.00 " + + "= %e", 10000.00); + assertEquals("The computerized scientific format of 10000.00 = 1.000000e+04", s); + + s = String.format("The decimal format of 10.019 = %f", 10.019); + assertEquals("The decimal format of 10.019 = 10.019000", s); + } + + @Test + public void givenString_whenLineSeparatorConversion_thenConvertedString() { + //Line Separator Conversion + String s = String.format("First Line %nSecond Line"); + assertEquals("First Line " + System.getProperty("line.separator") + + "Second Line", s); + } + + @Test + public void givenString_whenSpecifyFlag_thenGotFormattedString() { + //Without left-justified flag + String s = String.format("Without left justified flag: %5d", 25); + assertEquals("Without left justified flag: 25", s); + + //Using left-justified flag + s = String.format("With left justified flag: %-5d", 25); + assertEquals("With left justified flag: 25 ", s); + } + + @Test + public void givenString_whenSpecifyPrecision_thenGotExpected() { + + //Precision + String s = String.format("Output of 25.09878 with Precision 2: %.2f", 25.09878); + assertEquals("Output of 25.09878 with Precision 2: 25.10", s); + + s = String.format("Output of general conversion type with Precision 2: %.2b", true); + assertEquals("Output of general conversion type with Precision 2: tr", s); + } + + @Test + public void givenString_whenSpecifyArgumentIndex_thenGotExpected() { + Calendar c = new GregorianCalendar(2017, 11, 10); + //Argument_Index + String s = String.format("The date is: %tm %1$te,%1$tY", c); + assertEquals("The date is: 12 10,2017", s); + + s = String.format("The date is: %tm % + 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.samples java-vavr-stream @@ -22,7 +22,6 @@ - UTF-8 0.9.2 diff --git a/java-vavr-stream/src/main/resources/logback.xml b/java-vavr-stream/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-vavr-stream/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/java-websocket/pom.xml b/java-websocket/pom.xml index 461182e504..e8ff8dfc36 100644 --- a/java-websocket/pom.xml +++ b/java-websocket/pom.xml @@ -1,12 +1,10 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung java-websocket war 0.0.1-SNAPSHOT - java-websocket Maven Webapp - http://maven.apache.org com.baeldung @@ -29,7 +27,6 @@ - UTF-8 1.1 2.8.0 diff --git a/java-websocket/src/main/resources/logback.xml b/java-websocket/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-websocket/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/javafx/pom.xml b/javafx/pom.xml index b2de708be1..c9c5bc294e 100644 --- a/javafx/pom.xml +++ b/javafx/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 javafx diff --git a/javafx/src/main/resources/logback.xml b/javafx/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/javafx/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/javax-servlets/README.md b/javax-servlets/README.md index 84330ac94c..3c3b17996b 100644 --- a/javax-servlets/README.md +++ b/javax-servlets/README.md @@ -2,3 +2,8 @@ - [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets) - [An MVC Example with Servlets and JSP](http://www.baeldung.com/mvc-servlet-jsp) - [Handling Cookies and a Session in a Java Servlet](http://www.baeldung.com/java-servlet-cookies-session) +- [Uploading Files with Servlets and JSP](http://www.baeldung.com/upload-file-servlet) +- [Example of Downloading File in a Servlet](http://www.baeldung.com/servlet-download-file) +- [Returning a JSON Response from a Servlet](http://www.baeldung.com/servlet-json-response) +- [Java EE Servlet Exception Handling](http://www.baeldung.com/servlet-exceptions) +- [Context and Servlet Initialization Parameters](http://www.baeldung.com/context-servlet-initialization-param) diff --git a/javax-servlets/pom.xml b/javax-servlets/pom.xml index 41a3bb69be..7b4eecd880 100644 --- a/javax-servlets/pom.xml +++ b/javax-servlets/pom.xml @@ -1,75 +1,94 @@ - - 4.0.0 - javax-servlets - 1.0-SNAPSHOT + + 4.0.0 + com.baeldung.javax-servlets + javax-servlets + 1.0-SNAPSHOT + war + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.assertj + assertj-core + ${assertj.version} + test + - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + + commons-fileupload + commons-fileupload + ${commons-fileupload.version} + + + commons-io + commons-io + ${commons-io.version} + - - - - commons-fileupload - commons-fileupload - 1.3.3 - - - commons-io - commons-io - 2.6 - + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + + + javax.servlet.jsp.jstl + jstl-api + ${jstl.version} + + + javax.servlet.jsp + javax.servlet.jsp-api + ${jsp.version} + + + javax.servlet + jstl + ${jstl.version} + - - - javax.servlet - javax.servlet-api - 4.0.1 - - - javax.servlet.jsp.jstl - jstl-api - 1.2 - - - javax.servlet.jsp - javax.servlet.jsp-api - 2.3.1 - - - javax.servlet - jstl - 1.2 - - - - org.apache.httpcomponents - httpclient - ${org.apache.httpcomponents.version} - test - - - commons-logging - commons-logging - - - - - org.springframework - spring-test - ${spring-test.version} - test - - - - - 4.5.3 - 5.0.5.RELEASE - - - \ No newline at end of file + + org.apache.httpcomponents + httpclient + ${org.apache.httpcomponents.version} + test + + + commons-logging + commons-logging + + + + + com.google.code.gson + gson + ${gson.version} + + + org.springframework + spring-test + ${spring-test.version} + test + + + + 4.5.3 + 5.0.5.RELEASE + 2.8.2 + 3.9.1 + 2.21.0 + 1.3.3 + 2.6 + 4.0.1 + 1.2 + 2.3.1 + + diff --git a/javax-servlets/src/main/java/com/baeldung/model/Employee.java b/javax-servlets/src/main/java/com/baeldung/model/Employee.java new file mode 100644 index 0000000000..698a598962 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/model/Employee.java @@ -0,0 +1,72 @@ +package com.baeldung.model; + +public class Employee { + + private int id; + private String name; + private String department; + private long salary; + + public Employee(int id, String name, String department, long salary) { + super(); + this.id = id; + this.name = name; + this.department = department; + this.salary = salary; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + id; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Employee other = (Employee) obj; + if (id != other.id) + return false; + return true; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDepartment() { + return department; + } + + public void setDepartment(String department) { + this.department = department; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + +} diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/DownloadServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/DownloadServlet.java new file mode 100644 index 0000000000..b1a6621b24 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/DownloadServlet.java @@ -0,0 +1,32 @@ +package com.baeldung.servlets; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@WebServlet("/download") +public class DownloadServlet extends HttpServlet { + private final int ARBITARY_SIZE = 1048; + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + resp.setContentType("text/plain"); + resp.setHeader("Content-disposition", "attachment; filename=sample.txt"); + + try (InputStream in = req.getServletContext().getResourceAsStream("/WEB-INF/sample.txt"); + OutputStream out = resp.getOutputStream()) { + + byte[] buffer = new byte[ARBITARY_SIZE]; + + int numBytesRead; + while ((numBytesRead = in.read(buffer)) > 0) { + out.write(buffer, 0, numBytesRead); + } + } + } +} diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/EmployeeServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/EmployeeServlet.java new file mode 100644 index 0000000000..dbc1a010f7 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/EmployeeServlet.java @@ -0,0 +1,34 @@ +package com.baeldung.servlets; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.baeldung.model.Employee; +import com.google.gson.Gson; + + +@WebServlet(name = "EmployeeServlet", urlPatterns = "/employeeServlet") +public class EmployeeServlet extends HttpServlet { + + private Gson gson = new Gson(); + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws IOException { + + Employee employee = new Employee(1, "Karan", "IT", 5000); + String employeeJsonString = this.gson.toJson(employee); + + PrintWriter out = response.getWriter(); + response.setContentType("application/json"); + response.setCharacterEncoding("UTF-8"); + out.print(employeeJsonString); + out.flush(); + } + +} diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/ErrorHandlerServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/ErrorHandlerServlet.java new file mode 100644 index 0000000000..0008e837c0 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/ErrorHandlerServlet.java @@ -0,0 +1,34 @@ +package com.baeldung.servlets; + +import javax.servlet.annotation.*; +import javax.servlet.http.*; +import java.io.*; +import java.util.*; + +import static javax.servlet.RequestDispatcher.*; + +@WebServlet(urlPatterns = "/errorHandler") +public class ErrorHandlerServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws IOException { + resp.setContentType("text/html; charset=utf-8"); + try (PrintWriter writer = resp.getWriter()) { + writer.write("Error description"); + writer.write("

    Error description

    "); + writer.write("
      "); + Arrays.asList(ERROR_STATUS_CODE, ERROR_EXCEPTION_TYPE, ERROR_MESSAGE) + .forEach(e -> + writer.write("
    • " + e + ":" + req.getAttribute(e) + "
    • ") + ); + writer.write("
    "); + writer.write(""); + } + + Exception exception = (Exception) req.getAttribute(ERROR_EXCEPTION); + if (IllegalArgumentException.class.isInstance(exception)) { + getServletContext().log("Error on an application argument", exception); + } + } +} \ No newline at end of file diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/RandomErrorServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/RandomErrorServlet.java new file mode 100644 index 0000000000..c95bd2cec0 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/RandomErrorServlet.java @@ -0,0 +1,13 @@ +package com.baeldung.servlets; + +import javax.servlet.annotation.*; +import javax.servlet.http.*; + +@WebServlet(urlPatterns = "/randomError") +public class RandomErrorServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest req, final HttpServletResponse resp) { + throw new IllegalStateException("Random error"); + } +} \ No newline at end of file diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/UserServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/UserServlet.java new file mode 100644 index 0000000000..269cee3922 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/UserServlet.java @@ -0,0 +1,49 @@ +package com.baeldung.servlets; + +import java.io.IOException; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebInitParam; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@WebServlet(name = "UserServlet", urlPatterns = {"/userServlet"}, initParams={ + @WebInitParam(name="name", value="Not provided"), + @WebInitParam(name="email", value="Not provided")}) +public class UserServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + forwardRequest(request, response, "/WEB-INF/jsp/result.jsp"); + } + + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + request.setAttribute("name", getRequestParameter(request, "name")); + request.setAttribute("email", getRequestParameter(request, "email")); + request.setAttribute("province", getContextParameter("province")); + request.setAttribute("country", getContextParameter("country")); + } + + protected String getRequestParameter(HttpServletRequest request, String name) { + String param = request.getParameter(name); + return !param.isEmpty() ? param : getInitParameter(name); + } + + protected String getContextParameter(String name) { + return getServletContext().getInitParameter(name); + } + + protected void forwardRequest(HttpServletRequest request, HttpServletResponse response, String path) + throws ServletException, IOException { + request.getRequestDispatcher(path).forward(request, response); + } +} \ No newline at end of file diff --git a/javax-servlets/src/main/resources/logback.xml b/javax-servlets/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/javax-servlets/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/javax-servlets/src/main/webapp/WEB-INF/jsp/result.jsp b/javax-servlets/src/main/webapp/WEB-INF/jsp/result.jsp new file mode 100644 index 0000000000..01cc54858e --- /dev/null +++ b/javax-servlets/src/main/webapp/WEB-INF/jsp/result.jsp @@ -0,0 +1,16 @@ +<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> +<%@ page contentType="text/html" pageEncoding="UTF-8"%> + + + + + User Data + + +

    User Information

    +

    Name: ${name}

    +

    Email: ${email}

    +

    Province: ${province}

    +

    Country: ${country}

    + + diff --git a/javax-servlets/src/main/webapp/WEB-INF/web.xml b/javax-servlets/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..383be7ff25 --- /dev/null +++ b/javax-servlets/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,24 @@ + + + + province + Mendoza + + + country + Argentina + + + 404 + /error-404.html + + + + java.lang.Exception + /errorHandler + + \ No newline at end of file diff --git a/javax-servlets/src/main/webapp/error-404.html b/javax-servlets/src/main/webapp/error-404.html new file mode 100644 index 0000000000..b36fc44160 --- /dev/null +++ b/javax-servlets/src/main/webapp/error-404.html @@ -0,0 +1,14 @@ + + + + + Error page + + + +

    Error: Page not found

    + +Go back home + + + \ No newline at end of file diff --git a/javax-servlets/src/main/webapp/sample.txt b/javax-servlets/src/main/webapp/sample.txt new file mode 100644 index 0000000000..bab4636a96 --- /dev/null +++ b/javax-servlets/src/main/webapp/sample.txt @@ -0,0 +1 @@ +nice simple text file \ No newline at end of file diff --git a/javax-servlets/src/main/webapp/user.jsp b/javax-servlets/src/main/webapp/user.jsp new file mode 100644 index 0000000000..c6e1bb69f9 --- /dev/null +++ b/javax-servlets/src/main/webapp/user.jsp @@ -0,0 +1,19 @@ +<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> +<%@ page contentType="text/html" pageEncoding="UTF-8"%> + + + + Context and Servlet Initialization Parameters + + + +

    Please fill the form below:

    +
    + + + + + +
    + + diff --git a/javax-servlets/src/test/java/com/baeldung/servlets/EmployeeServletIntegrationTest.java b/javax-servlets/src/test/java/com/baeldung/servlets/EmployeeServletIntegrationTest.java new file mode 100644 index 0000000000..4fe4908075 --- /dev/null +++ b/javax-servlets/src/test/java/com/baeldung/servlets/EmployeeServletIntegrationTest.java @@ -0,0 +1,54 @@ +package com.baeldung.servlets; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +import java.io.PrintWriter; +import java.io.StringWriter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import com.baeldung.model.Employee; +import com.google.gson.Gson; + + +@RunWith(MockitoJUnitRunner.class) +public class EmployeeServletIntegrationTest { + + @Mock + HttpServletRequest httpServletRequest; + + @Mock + HttpServletResponse httpServletResponse; + + Employee employee; + + @Test + public void whenPostRequestToEmployeeServlet_thenEmployeeReturnedAsJson() throws Exception { + + //Given + int id = 1; + String name = "Karan Khanna"; + String department = "IT"; + long salary = 5000; + employee = new Employee(id, name, department, salary); + + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + when(httpServletResponse.getWriter()).thenReturn(pw); + + EmployeeServlet employeeServlet = new EmployeeServlet(); + employeeServlet.doGet(httpServletRequest, httpServletResponse); + + String employeeJsonString = sw.getBuffer().toString().trim(); + Employee fetchedEmployee = new Gson().fromJson(employeeJsonString, Employee.class); + assertEquals(fetchedEmployee, employee); + } + +} diff --git a/javax-servlets/src/test/java/com/baeldung/servlets/FormServletLiveTest.java b/javax-servlets/src/test/java/com/baeldung/test/FormServletLiveTest.java similarity index 100% rename from javax-servlets/src/test/java/com/baeldung/servlets/FormServletLiveTest.java rename to javax-servlets/src/test/java/com/baeldung/test/FormServletLiveTest.java diff --git a/javax-servlets/src/test/java/com/baeldung/test/UserServletUnitTest.java b/javax-servlets/src/test/java/com/baeldung/test/UserServletUnitTest.java new file mode 100644 index 0000000000..d4c93791d2 --- /dev/null +++ b/javax-servlets/src/test/java/com/baeldung/test/UserServletUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.servlets; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class UserServletUnitTest { + + private static HttpServletRequest request; + private static HttpServletResponse response; + + + @BeforeClass + public static void setUpHttpServletRequestMockInstance() { + request = mock(HttpServletRequest.class); + } + + @BeforeClass + public static void setUpHttpServletResponsetMockInstance() { + response = mock(HttpServletResponse.class); + } + + @Test + public void givenHttpServletRequestMockInstance_whenCalledgetParameter_thenCalledAtLeastOnce() { + request.getParameter("name"); + verify(request, atLeast(1)).getParameter("name"); + } + + @Test + public void givenHttpServletRequestMockInstance_whenCalledgetParameter_thenOneAssertion() { + when(request.getParameter("name")).thenReturn("username"); + assertThat(request.getParameter("name")).isEqualTo("username"); + } + + @Test + public void givenHttpServletResponseMockInstance_whenCalledgetContentType_thenCalledAtLeastOnce() { + response.getContentType(); + verify(response, atLeast(1)).getContentType(); + } + + @Test + public void givenHttpServletResponseMockInstance_whenCalledgetContentType_thenOneAssertion() { + when(response.getContentType()).thenReturn("text/html"); + assertThat(response.getContentType()).isEqualTo("text/html"); + } +} \ No newline at end of file diff --git a/javaxval/bin/.gitignore b/javaxval/bin/.gitignore deleted file mode 100644 index 55a6bcf596..0000000000 --- a/javaxval/bin/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -.classpath -.project -.settings/ -target/ - - diff --git a/javaxval/bin/pom.xml b/javaxval/bin/pom.xml deleted file mode 100644 index a16072bb1a..0000000000 --- a/javaxval/bin/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - 4.0.0 - com.baeldung - javaxval - 0.1-SNAPSHOT - - - - - - javax.validation - validation-api - 1.1.0.Final - - - - org.hibernate - hibernate-validator - 5.2.1.Final - - - - org.hibernate - hibernate-validator-annotation-processor - 5.2.1.Final - - - - javax.el - javax.el-api - 2.2.4 - - - - org.glassfish.web - javax.el - 2.2.4 - - - - - - \ No newline at end of file diff --git a/javaxval/pom.xml b/javaxval/pom.xml index 5de77ed26b..7af766261b 100644 --- a/javaxval/pom.xml +++ b/javaxval/pom.xml @@ -1,5 +1,5 @@ + 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 javaxval diff --git a/javaxval/src/main/resources/logback.xml b/javaxval/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/javaxval/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/jaxb/pom.xml b/jaxb/pom.xml index 26d7c8d362..3ed6d9b21a 100644 --- a/jaxb/pom.xml +++ b/jaxb/pom.xml @@ -1,5 +1,5 @@ + 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 jaxb @@ -39,6 +39,11 @@ commons-lang3 ${commons-lang3.version} + + javax.activation + activation + ${javax.activation.version} + @@ -70,7 +75,7 @@ - + @@ -111,13 +116,9 @@ - @@ -132,6 +133,8 @@ 2.5 3.5 1.0.0 + + 1.1
    \ No newline at end of file diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java index 0a3da677ce..26cd5814ac 100644 --- a/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java +++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java @@ -1,48 +1,48 @@ - -package com.baeldung.jaxb.gen; - -import javax.xml.bind.annotation.XmlRegistry; - - -/** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the com.baeldung.jaxb.gen package. - *

    An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are - * provided in this class. - * - */ -@XmlRegistry -public class ObjectFactory { - - - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.baeldung.jaxb.gen - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link UserRequest } - * - */ - public UserRequest createUserRequest() { - return new UserRequest(); - } - - /** - * Create an instance of {@link UserResponse } - * - */ - public UserResponse createUserResponse() { - return new UserResponse(); - } - -} + +package com.baeldung.jaxb.gen; + +import javax.xml.bind.annotation.XmlRegistry; + + +/** + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the com.baeldung.jaxb.gen package. + *

    An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are + * provided in this class. + * + */ +@XmlRegistry +public class ObjectFactory { + + + /** + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.baeldung.jaxb.gen + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link UserRequest } + * + */ + public UserRequest createUserRequest() { + return new UserRequest(); + } + + /** + * Create an instance of {@link UserResponse } + * + */ + public UserResponse createUserResponse() { + return new UserResponse(); + } + +} diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java index 1c1abc61a6..4cfbeb8d46 100644 --- a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java +++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java @@ -1,87 +1,87 @@ - -package com.baeldung.jaxb.gen; - -import java.io.Serializable; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for UserRequest complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="UserRequest">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
    - *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "UserRequest", propOrder = { - "id", - "name" -}) -@XmlRootElement(name = "userRequest") -public class UserRequest - implements Serializable -{ - - private final static long serialVersionUID = -1L; - protected int id; - @XmlElement(required = true) - protected String name; - - /** - * Gets the value of the id property. - * - */ - public int getId() { - return id; - } - - /** - * Sets the value of the id property. - * - */ - public void setId(int value) { - this.id = value; - } - - /** - * Gets the value of the name property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getName() { - return name; - } - - /** - * Sets the value of the name property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setName(String value) { - this.name = value; - } - -} + +package com.baeldung.jaxb.gen; + +import java.io.Serializable; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

    Java class for UserRequest complex type. + * + *

    The following schema fragment specifies the expected content contained within this class. + * + *

    + * <complexType name="UserRequest">
    + *   <complexContent>
    + *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    + *       <sequence>
    + *         <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
    + *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
    + *       </sequence>
    + *     </restriction>
    + *   </complexContent>
    + * </complexType>
    + * 
    + * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "UserRequest", propOrder = { + "id", + "name" +}) +@XmlRootElement(name = "userRequest") +public class UserRequest + implements Serializable +{ + + private final static long serialVersionUID = -1L; + protected int id; + @XmlElement(required = true) + protected String name; + + /** + * Gets the value of the id property. + * + */ + public int getId() { + return id; + } + + /** + * Sets the value of the id property. + * + */ + public void setId(int value) { + this.id = value; + } + + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + +} diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java index b80405e4a9..d86778403a 100644 --- a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java +++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java @@ -1,149 +1,149 @@ - -package com.baeldung.jaxb.gen; - -import java.io.Serializable; -import java.util.Calendar; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlSchemaType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import org.w3._2001.xmlschema.Adapter1; - - -/** - *

    Java class for UserResponse complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="UserResponse">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
    - *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *         <element name="gender" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *         <element name="created" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "UserResponse", propOrder = { - "id", - "name", - "gender", - "created" -}) -@XmlRootElement(name = "userResponse") -public class UserResponse - implements Serializable -{ - - private final static long serialVersionUID = -1L; - protected int id; - @XmlElement(required = true) - protected String name; - @XmlElement(required = true) - protected String gender; - @XmlElement(required = true, type = String.class) - @XmlJavaTypeAdapter(Adapter1 .class) - @XmlSchemaType(name = "dateTime") - protected Calendar created; - - /** - * Gets the value of the id property. - * - */ - public int getId() { - return id; - } - - /** - * Sets the value of the id property. - * - */ - public void setId(int value) { - this.id = value; - } - - /** - * Gets the value of the name property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getName() { - return name; - } - - /** - * Sets the value of the name property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setName(String value) { - this.name = value; - } - - /** - * Gets the value of the gender property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getGender() { - return gender; - } - - /** - * Sets the value of the gender property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setGender(String value) { - this.gender = value; - } - - /** - * Gets the value of the created property. - * - * @return - * possible object is - * {@link String } - * - */ - public Calendar getCreated() { - return created; - } - - /** - * Sets the value of the created property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setCreated(Calendar value) { - this.created = value; - } - -} + +package com.baeldung.jaxb.gen; + +import java.io.Serializable; +import java.util.Calendar; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import org.w3._2001.xmlschema.Adapter1; + + +/** + *

    Java class for UserResponse complex type. + * + *

    The following schema fragment specifies the expected content contained within this class. + * + *

    + * <complexType name="UserResponse">
    + *   <complexContent>
    + *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    + *       <sequence>
    + *         <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
    + *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
    + *         <element name="gender" type="{http://www.w3.org/2001/XMLSchema}string"/>
    + *         <element name="created" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
    + *       </sequence>
    + *     </restriction>
    + *   </complexContent>
    + * </complexType>
    + * 
    + * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "UserResponse", propOrder = { + "id", + "name", + "gender", + "created" +}) +@XmlRootElement(name = "userResponse") +public class UserResponse + implements Serializable +{ + + private final static long serialVersionUID = -1L; + protected int id; + @XmlElement(required = true) + protected String name; + @XmlElement(required = true) + protected String gender; + @XmlElement(required = true, type = String.class) + @XmlJavaTypeAdapter(Adapter1 .class) + @XmlSchemaType(name = "dateTime") + protected Calendar created; + + /** + * Gets the value of the id property. + * + */ + public int getId() { + return id; + } + + /** + * Sets the value of the id property. + * + */ + public void setId(int value) { + this.id = value; + } + + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + + /** + * Gets the value of the gender property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getGender() { + return gender; + } + + /** + * Sets the value of the gender property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setGender(String value) { + this.gender = value; + } + + /** + * Gets the value of the created property. + * + * @return + * possible object is + * {@link String } + * + */ + public Calendar getCreated() { + return created; + } + + /** + * Sets the value of the created property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCreated(Calendar value) { + this.created = value; + } + +} diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java index 639d00179c..6384eab27f 100644 --- a/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java +++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java @@ -1,2 +1,2 @@ -@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/jaxb/gen", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) -package com.baeldung.jaxb.gen; +@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/jaxb/gen", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) +package com.baeldung.jaxb.gen; diff --git a/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java b/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java index 54b3c360dc..b4865b5510 100644 --- a/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java +++ b/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java @@ -1,23 +1,23 @@ - -package org.w3._2001.xmlschema; - -import java.util.Calendar; -import javax.xml.bind.annotation.adapters.XmlAdapter; - -public class Adapter1 - extends XmlAdapter -{ - - - public Calendar unmarshal(String value) { - return (javax.xml.bind.DatatypeConverter.parseDateTime(value)); - } - - public String marshal(Calendar value) { - if (value == null) { - return null; - } - return (javax.xml.bind.DatatypeConverter.printDateTime(value)); - } - -} + +package org.w3._2001.xmlschema; + +import java.util.Calendar; +import javax.xml.bind.annotation.adapters.XmlAdapter; + +public class Adapter1 + extends XmlAdapter +{ + + + public Calendar unmarshal(String value) { + return (javax.xml.bind.DatatypeConverter.parseDateTime(value)); + } + + public String marshal(Calendar value) { + if (value == null) { + return null; + } + return (javax.xml.bind.DatatypeConverter.printDateTime(value)); + } + +} diff --git a/jaxb/src/main/resources/log4jstructuraldp.properties b/jaxb/src/main/resources/log4jstructuraldp.properties new file mode 100644 index 0000000000..5bc2bfe4b9 --- /dev/null +++ b/jaxb/src/main/resources/log4jstructuraldp.properties @@ -0,0 +1,9 @@ + +# Root logger +log4j.rootLogger=INFO, file, stdout + +# Write to console +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/jaxb/src/main/resources/logback.xml b/jaxb/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/jaxb/src/main/resources/logback.xml +++ b/jaxb/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java b/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java index b2dde85c0f..77b7f1a0b3 100644 --- a/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java +++ b/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java @@ -44,7 +44,7 @@ public class JaxbIntegrationTest { File bookFile = new File(this.getClass().getResource("/book.xml").getFile()); String sampleBookXML = FileUtils.readFileToString(sampleBookFile, "UTF-8"); String marshallerBookXML = FileUtils.readFileToString(bookFile, "UTF-8"); - Assert.assertEquals(sampleBookXML, marshallerBookXML); + Assert.assertEquals(sampleBookXML.replace("\r", "").replace("\n", ""), marshallerBookXML.replace("\r", "").replace("\n", "")); } @Test diff --git a/jaxb/src/test/resources/book.xml b/jaxb/src/test/resources/book.xml new file mode 100644 index 0000000000..605d531b16 --- /dev/null +++ b/jaxb/src/test/resources/book.xml @@ -0,0 +1,5 @@ + + + Book1 + 2016-12-16T17:28:49.718Z + diff --git a/jee-7/pom.xml b/jee-7/pom.xml index 62e2132de5..08c8b5a068 100644 --- a/jee-7/pom.xml +++ b/jee-7/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung jee-7 @@ -14,29 +14,6 @@ 1.0.0-SNAPSHOT - - ${maven.min.version} - - - - - - org.jboss.arquillian - arquillian-bom - ${arquillian_core.version} - import - pom - - - org.jboss.arquillian.extension - arquillian-drone-bom - ${arquillian-drone-bom.version} - pom - import - - - - javax @@ -161,6 +138,25 @@ + + + + org.jboss.arquillian + arquillian-bom + ${arquillian_core.version} + import + pom + + + org.jboss.arquillian.extension + arquillian-drone-bom + ${arquillian-drone-bom.version} + pom + import + + + + wildfly-managed-arquillian @@ -418,7 +414,7 @@ 1.0.0.Final 2.6 4.2.3.RELEASE - 2.17 + 2.21.0 1.1.2 2.4 2.2.14 diff --git a/jee-7/src/main/resources/logback.xml b/jee-7/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/jee-7/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java b/jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java deleted file mode 100644 index caeba95e45..0000000000 --- a/jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.baeldung.convListVal; - -import static org.jboss.arquillian.graphene.Graphene.guardHttp; - -import java.io.File; -import java.net.URL; - -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.container.test.api.RunAsClient; -import org.jboss.arquillian.drone.api.annotation.Drone; -import org.jboss.arquillian.junit.Arquillian; -import org.jboss.arquillian.test.api.ArquillianResource; -import org.jboss.shrinkwrap.api.ShrinkWrap; -import org.jboss.shrinkwrap.api.asset.EmptyAsset; -import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.openqa.selenium.By; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.support.FindBy; - -@RunWith(Arquillian.class) -public class ConvListValIntegrationTest { - - @ArquillianResource - private URL deploymentUrl; - - private static final String WEBAPP_SRC = "src/main/webapp"; - - @Deployment(testable = false) - public static WebArchive createDeployment() { - return ( ShrinkWrap.create( - WebArchive.class, "jee7.war"). - addClasses(ConvListVal.class, MyListener.class)). - addAsWebResource(new File(WEBAPP_SRC, "ConvListVal.xhtml")). - addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); - } - - @Drone - WebDriver browser; - - @ArquillianResource - URL contextPath; - - @FindBy(id="myForm:age") - private WebElement ageInput; - - @FindBy(id="myForm:average") - private WebElement averageInput; - - @FindBy(id="myForm:send") - private WebElement sendButton; - - @Test - @RunAsClient - public void givenAge_whenAgeInvalid_thenErrorMessage() throws Exception { - browser.get(deploymentUrl.toExternalForm() + "ConvListVal.jsf"); - ageInput.sendKeys("stringage"); - guardHttp(sendButton).click(); - Assert.assertTrue("Show Age error message", browser.findElements(By.id("myForm:ageError")).size() > 0); - } - - @Test - @RunAsClient - public void givenAverage_whenAverageInvalid_thenErrorMessage() throws Exception { - browser.get(deploymentUrl.toExternalForm() + "ConvListVal.jsf"); - averageInput.sendKeys("stringaverage"); - guardHttp(sendButton).click(); - Assert.assertTrue("Show Average error message", browser.findElements(By.id("myForm:averageError")).size() > 0); - } - - @Test - @RunAsClient - public void givenDate_whenDateInvalid_thenErrorMessage() throws Exception { - browser.get(deploymentUrl.toExternalForm() + "ConvListVal.jsf"); - averageInput.sendKeys("123"); - guardHttp(sendButton).click(); - Assert.assertTrue("Show Date error message", browser.findElements(By.id("myForm:myDateError")).size() > 0); - } - - @Test - @RunAsClient - public void givenSurname_whenSurnameMinLenghtInvalid_thenErrorMessage() throws Exception { - browser.get(deploymentUrl.toExternalForm() + "ConvListVal.jsf"); - averageInput.sendKeys("aaa"); - guardHttp(sendButton).click(); - Assert.assertTrue("Show Surname error message", browser.findElements(By.id("myForm:surnameError")).size() > 0); - } - - @Test - @RunAsClient - public void givenSurname_whenSurnameMaxLenghtInvalid_thenErrorMessage() throws Exception { - browser.get(deploymentUrl.toExternalForm() + "ConvListVal.jsf"); - averageInput.sendKeys("aaaaabbbbbc"); - guardHttp(sendButton).click(); - Assert.assertTrue("Show Surname error message", browser.findElements(By.id("myForm:surnameError")).size() > 0); - } - -} diff --git a/jee-7/src/test/java/com/baeldung/convListVal/ConvListValLiveTest.java b/jee-7/src/test/java/com/baeldung/convListVal/ConvListValLiveTest.java new file mode 100644 index 0000000000..0d6fd295e6 --- /dev/null +++ b/jee-7/src/test/java/com/baeldung/convListVal/ConvListValLiveTest.java @@ -0,0 +1,101 @@ +package com.baeldung.convListVal; + +import static org.jboss.arquillian.graphene.Graphene.guardHttp; + +import java.io.File; +import java.net.URL; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.container.test.api.RunAsClient; +import org.jboss.arquillian.drone.api.annotation.Drone; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.EmptyAsset; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.FindBy; + +@RunWith(Arquillian.class) +public class ConvListValLiveTest { + + @ArquillianResource + private URL deploymentUrl; + + private static final String WEBAPP_SRC = "src/main/webapp"; + + @Deployment(testable = false) + public static WebArchive createDeployment() { + return ( ShrinkWrap.create( + WebArchive.class, "jee7.war"). + addClasses(ConvListVal.class, MyListener.class)). + addAsWebResource(new File(WEBAPP_SRC, "ConvListVal.xhtml")). + addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); + } + + @Drone + WebDriver browser; + + @ArquillianResource + URL contextPath; + + @FindBy(id="myForm:age") + private WebElement ageInput; + + @FindBy(id="myForm:average") + private WebElement averageInput; + + @FindBy(id="myForm:send") + private WebElement sendButton; + + @Test + @RunAsClient + public void givenAge_whenAgeInvalid_thenErrorMessage() throws Exception { + browser.get(deploymentUrl.toExternalForm() + "ConvListVal.jsf"); + ageInput.sendKeys("stringage"); + guardHttp(sendButton).click(); + Assert.assertTrue("Show Age error message", browser.findElements(By.id("myForm:ageError")).size() > 0); + } + + @Test + @RunAsClient + public void givenAverage_whenAverageInvalid_thenErrorMessage() throws Exception { + browser.get(deploymentUrl.toExternalForm() + "ConvListVal.jsf"); + averageInput.sendKeys("stringaverage"); + guardHttp(sendButton).click(); + Assert.assertTrue("Show Average error message", browser.findElements(By.id("myForm:averageError")).size() > 0); + } + + @Test + @RunAsClient + public void givenDate_whenDateInvalid_thenErrorMessage() throws Exception { + browser.get(deploymentUrl.toExternalForm() + "ConvListVal.jsf"); + averageInput.sendKeys("123"); + guardHttp(sendButton).click(); + Assert.assertTrue("Show Date error message", browser.findElements(By.id("myForm:myDateError")).size() > 0); + } + + @Test + @RunAsClient + public void givenSurname_whenSurnameMinLenghtInvalid_thenErrorMessage() throws Exception { + browser.get(deploymentUrl.toExternalForm() + "ConvListVal.jsf"); + averageInput.sendKeys("aaa"); + guardHttp(sendButton).click(); + Assert.assertTrue("Show Surname error message", browser.findElements(By.id("myForm:surnameError")).size() > 0); + } + + @Test + @RunAsClient + public void givenSurname_whenSurnameMaxLenghtInvalid_thenErrorMessage() throws Exception { + browser.get(deploymentUrl.toExternalForm() + "ConvListVal.jsf"); + averageInput.sendKeys("aaaaabbbbbc"); + guardHttp(sendButton).click(); + Assert.assertTrue("Show Surname error message", browser.findElements(By.id("myForm:surnameError")).size() > 0); + } + +} diff --git a/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java deleted file mode 100644 index 0e4c91ad67..0000000000 --- a/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.baeldung.timer; - -import com.jayway.awaitility.Awaitility; -import org.hamcrest.Matchers; -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.junit.Arquillian; -import org.jboss.shrinkwrap.api.ShrinkWrap; -import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.jboss.shrinkwrap.resolver.api.maven.Maven; -import org.junit.Test; -import org.junit.runner.RunWith; - -import javax.inject.Inject; -import java.io.File; -import java.util.concurrent.TimeUnit; - -import static com.jayway.awaitility.Awaitility.await; -import static com.jayway.awaitility.Awaitility.to; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; - - -@RunWith(Arquillian.class) -public class AutomaticTimerBeanIntegrationTest { - - //the @AutomaticTimerBean has a method called every 10 seconds - //testing the difference ==> 100000 - final static long TIMEOUT = 10000l; - - //the tolerance accepted , so if between two consecutive calls there has to be at least 9 or max 11 seconds. - //because the timer service is not intended for real-time applications so it will not be exactly 10 seconds - final static long TOLERANCE = 1000l; - - @Inject - TimerEventListener timerEventListener; - - @Deployment - public static WebArchive deploy() { - File[] jars = Maven.resolver().loadPomFromFile("pom.xml") - .resolve("com.jayway.awaitility:awaitility") - .withTransitivity().asFile(); - - //only @AutomaticTimerBean is deployed not the other timers - return ShrinkWrap.create(WebArchive.class) - .addAsLibraries(jars) - .addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, AutomaticTimerBean.class); - } - - - - @Test - public void should_receive_two_pings() { - Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS); - //the test will wait here until two events are triggered - await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(2)); - - TimerEvent firstEvent = timerEventListener.getEvents().get(0); - TimerEvent secondEvent = timerEventListener.getEvents().get(1); - - long delay = secondEvent.getTime() - firstEvent.getTime(); - System.out.println("Actual timeout = " + delay); - - //ensure that the delay between the events is more or less 10 seconds (no real time precision) - assertThat(delay, Matchers.is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE))); - } -} diff --git a/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanLiveTest.java b/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanLiveTest.java new file mode 100644 index 0000000000..41dde6549d --- /dev/null +++ b/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanLiveTest.java @@ -0,0 +1,66 @@ +package com.baeldung.timer; + +import com.jayway.awaitility.Awaitility; +import org.hamcrest.Matchers; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.jboss.shrinkwrap.resolver.api.maven.Maven; +import org.junit.Test; +import org.junit.runner.RunWith; + +import javax.inject.Inject; +import java.io.File; +import java.util.concurrent.TimeUnit; + +import static com.jayway.awaitility.Awaitility.await; +import static com.jayway.awaitility.Awaitility.to; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + + +@RunWith(Arquillian.class) +public class AutomaticTimerBeanLiveTest { + + //the @AutomaticTimerBean has a method called every 10 seconds + //testing the difference ==> 100000 + final static long TIMEOUT = 10000l; + + //the tolerance accepted , so if between two consecutive calls there has to be at least 9 or max 11 seconds. + //because the timer service is not intended for real-time applications so it will not be exactly 10 seconds + final static long TOLERANCE = 1000l; + + @Inject + TimerEventListener timerEventListener; + + @Deployment + public static WebArchive deploy() { + File[] jars = Maven.resolver().loadPomFromFile("pom.xml") + .resolve("com.jayway.awaitility:awaitility") + .withTransitivity().asFile(); + + //only @AutomaticTimerBean is deployed not the other timers + return ShrinkWrap.create(WebArchive.class) + .addAsLibraries(jars) + .addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, AutomaticTimerBean.class); + } + + + + @Test + public void should_receive_two_pings() { + Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS); + //the test will wait here until two events are triggered + await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(2)); + + TimerEvent firstEvent = timerEventListener.getEvents().get(0); + TimerEvent secondEvent = timerEventListener.getEvents().get(1); + + long delay = secondEvent.getTime() - firstEvent.getTime(); + System.out.println("Actual timeout = " + delay); + + //ensure that the delay between the events is more or less 10 seconds (no real time precision) + assertThat(delay, Matchers.is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE))); + } +} diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java deleted file mode 100644 index 13cd1729db..0000000000 --- a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.timer; - -import com.jayway.awaitility.Awaitility; -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.junit.Arquillian; -import org.jboss.shrinkwrap.api.ShrinkWrap; -import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.jboss.shrinkwrap.resolver.api.maven.Maven; -import org.junit.Test; -import org.junit.runner.RunWith; - -import javax.inject.Inject; -import java.io.File; -import java.util.concurrent.TimeUnit; - -import static com.jayway.awaitility.Awaitility.await; -import static com.jayway.awaitility.Awaitility.to; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; - - -@RunWith(Arquillian.class) -public class ProgrammaticAtFixedRateTimerBeanIntegrationTest { - - final static long TIMEOUT = 1000; - final static long TOLERANCE = 500l; - - @Inject - TimerEventListener timerEventListener; - - @Deployment - public static WebArchive deploy() { - File[] jars = Maven.resolver().loadPomFromFile("pom.xml") - .resolve("com.jayway.awaitility:awaitility") - .withTransitivity().asFile(); - - return ShrinkWrap.create(WebArchive.class) - .addAsLibraries(jars) - .addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ProgrammaticAtFixedRateTimerBean.class); - } - - @Test - public void should_receive_ten_pings() { - - Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS); - - await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(10)); - TimerEvent firstEvent = timerEventListener.getEvents().get(0); - TimerEvent secondEvent = timerEventListener.getEvents().get(1); - - long delay = secondEvent.getTime() - firstEvent.getTime(); - System.out.println("Actual timeout = " + delay); - assertThat(delay, is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE))); - } -} \ No newline at end of file diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanLiveTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanLiveTest.java new file mode 100644 index 0000000000..350c094f38 --- /dev/null +++ b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanLiveTest.java @@ -0,0 +1,56 @@ +package com.baeldung.timer; + +import com.jayway.awaitility.Awaitility; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.jboss.shrinkwrap.resolver.api.maven.Maven; +import org.junit.Test; +import org.junit.runner.RunWith; + +import javax.inject.Inject; +import java.io.File; +import java.util.concurrent.TimeUnit; + +import static com.jayway.awaitility.Awaitility.await; +import static com.jayway.awaitility.Awaitility.to; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; + + +@RunWith(Arquillian.class) +public class ProgrammaticAtFixedRateTimerBeanLiveTest { + + final static long TIMEOUT = 1000; + final static long TOLERANCE = 500l; + + @Inject + TimerEventListener timerEventListener; + + @Deployment + public static WebArchive deploy() { + File[] jars = Maven.resolver().loadPomFromFile("pom.xml") + .resolve("com.jayway.awaitility:awaitility") + .withTransitivity().asFile(); + + return ShrinkWrap.create(WebArchive.class) + .addAsLibraries(jars) + .addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ProgrammaticAtFixedRateTimerBean.class); + } + + @Test + public void should_receive_ten_pings() { + + Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS); + + await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(10)); + TimerEvent firstEvent = timerEventListener.getEvents().get(0); + TimerEvent secondEvent = timerEventListener.getEvents().get(1); + + long delay = secondEvent.getTime() - firstEvent.getTime(); + System.out.println("Actual timeout = " + delay); + assertThat(delay, is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE))); + } +} \ No newline at end of file diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java deleted file mode 100644 index b90cb6d909..0000000000 --- a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.timer; - -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.junit.Arquillian; -import org.jboss.shrinkwrap.api.ShrinkWrap; -import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.jboss.shrinkwrap.resolver.api.maven.Maven; -import org.junit.Test; -import org.junit.runner.RunWith; - -import javax.inject.Inject; -import java.io.File; - -import static com.jayway.awaitility.Awaitility.await; -import static com.jayway.awaitility.Awaitility.to; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; - - -@RunWith(Arquillian.class) -public class ProgrammaticTimerBeanIntegrationTest { - - final static long TIMEOUT = 5000l; - final static long TOLERANCE = 1000l; - - @Inject - TimerEventListener timerEventListener; - - @Deployment - public static WebArchive deploy() { - File[] jars = Maven.resolver().loadPomFromFile("pom.xml") - .resolve("com.jayway.awaitility:awaitility") - .withTransitivity().asFile(); - - return ShrinkWrap.create(WebArchive.class) - .addAsLibraries(jars) - .addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ProgrammaticTimerBean.class); - } - - @Test - public void should_receive_two_pings() { - - await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(2)); - - TimerEvent firstEvent = timerEventListener.getEvents().get(0); - TimerEvent secondEvent = timerEventListener.getEvents().get(1); - - long delay = secondEvent.getTime() - firstEvent.getTime(); - System.out.println("Actual timeout = " + delay); - assertThat(delay, is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE))); - } -} \ No newline at end of file diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanLiveTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanLiveTest.java new file mode 100644 index 0000000000..ad079c131b --- /dev/null +++ b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanLiveTest.java @@ -0,0 +1,53 @@ +package com.baeldung.timer; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.jboss.shrinkwrap.resolver.api.maven.Maven; +import org.junit.Test; +import org.junit.runner.RunWith; + +import javax.inject.Inject; +import java.io.File; + +import static com.jayway.awaitility.Awaitility.await; +import static com.jayway.awaitility.Awaitility.to; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; + + +@RunWith(Arquillian.class) +public class ProgrammaticTimerBeanLiveTest { + + final static long TIMEOUT = 5000l; + final static long TOLERANCE = 1000l; + + @Inject + TimerEventListener timerEventListener; + + @Deployment + public static WebArchive deploy() { + File[] jars = Maven.resolver().loadPomFromFile("pom.xml") + .resolve("com.jayway.awaitility:awaitility") + .withTransitivity().asFile(); + + return ShrinkWrap.create(WebArchive.class) + .addAsLibraries(jars) + .addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ProgrammaticTimerBean.class); + } + + @Test + public void should_receive_two_pings() { + + await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(2)); + + TimerEvent firstEvent = timerEventListener.getEvents().get(0); + TimerEvent secondEvent = timerEventListener.getEvents().get(1); + + long delay = secondEvent.getTime() - firstEvent.getTime(); + System.out.println("Actual timeout = " + delay); + assertThat(delay, is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE))); + } +} \ No newline at end of file diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java deleted file mode 100644 index e2e660f79b..0000000000 --- a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.timer; - -import com.jayway.awaitility.Awaitility; -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.junit.Arquillian; -import org.jboss.shrinkwrap.api.ShrinkWrap; -import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.jboss.shrinkwrap.resolver.api.maven.Maven; -import org.junit.Test; -import org.junit.runner.RunWith; - -import javax.inject.Inject; -import java.io.File; -import java.util.concurrent.TimeUnit; - -import static com.jayway.awaitility.Awaitility.await; -import static com.jayway.awaitility.Awaitility.to; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; - - -@RunWith(Arquillian.class) -public class ProgrammaticWithFixedDelayTimerBeanIntegrationTest { - - final static long TIMEOUT = 15000l; - final static long TOLERANCE = 1000l; - - @Inject - TimerEventListener timerEventListener; - - @Deployment - public static WebArchive deploy() { - File[] jars = Maven.resolver().loadPomFromFile("pom.xml") - .resolve("com.jayway.awaitility:awaitility") - .withTransitivity().asFile(); - - return ShrinkWrap.create(WebArchive.class) - .addAsLibraries(jars) - .addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ProgrammaticWithInitialFixedDelayTimerBean.class); - } - - @Test - public void should_receive_two_pings() { - - Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS); - - // 10 seconds pause so we get the startTime and it will trigger first event - long startTime = System.currentTimeMillis(); - - await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(2)); - TimerEvent firstEvent = timerEventListener.getEvents().get(0); - TimerEvent secondEvent = timerEventListener.getEvents().get(1); - - long delay = secondEvent.getTime() - startTime; - System.out.println("Actual timeout = " + delay); - - //apx 15 seconds = 10 delay + 2 timers (first after a pause of 10 seconds and the next others every 5 seconds) - assertThat(delay, is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE))); - } -} \ No newline at end of file diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanLiveTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanLiveTest.java new file mode 100644 index 0000000000..974f0a285f --- /dev/null +++ b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanLiveTest.java @@ -0,0 +1,61 @@ +package com.baeldung.timer; + +import com.jayway.awaitility.Awaitility; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.jboss.shrinkwrap.resolver.api.maven.Maven; +import org.junit.Test; +import org.junit.runner.RunWith; + +import javax.inject.Inject; +import java.io.File; +import java.util.concurrent.TimeUnit; + +import static com.jayway.awaitility.Awaitility.await; +import static com.jayway.awaitility.Awaitility.to; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; + + +@RunWith(Arquillian.class) +public class ProgrammaticWithFixedDelayTimerBeanLiveTest { + + final static long TIMEOUT = 15000l; + final static long TOLERANCE = 1000l; + + @Inject + TimerEventListener timerEventListener; + + @Deployment + public static WebArchive deploy() { + File[] jars = Maven.resolver().loadPomFromFile("pom.xml") + .resolve("com.jayway.awaitility:awaitility") + .withTransitivity().asFile(); + + return ShrinkWrap.create(WebArchive.class) + .addAsLibraries(jars) + .addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ProgrammaticWithInitialFixedDelayTimerBean.class); + } + + @Test + public void should_receive_two_pings() { + + Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS); + + // 10 seconds pause so we get the startTime and it will trigger first event + long startTime = System.currentTimeMillis(); + + await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(2)); + TimerEvent firstEvent = timerEventListener.getEvents().get(0); + TimerEvent secondEvent = timerEventListener.getEvents().get(1); + + long delay = secondEvent.getTime() - startTime; + System.out.println("Actual timeout = " + delay); + + //apx 15 seconds = 10 delay + 2 timers (first after a pause of 10 seconds and the next others every 5 seconds) + assertThat(delay, is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE))); + } +} \ No newline at end of file diff --git a/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java deleted file mode 100644 index 580edade77..0000000000 --- a/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.baeldung.timer; - -import com.jayway.awaitility.Awaitility; -import org.hamcrest.Matchers; -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.junit.Arquillian; -import org.jboss.shrinkwrap.api.ShrinkWrap; -import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.jboss.shrinkwrap.resolver.api.maven.Maven; -import org.junit.Test; -import org.junit.runner.RunWith; - -import javax.inject.Inject; -import java.io.File; -import java.util.concurrent.TimeUnit; - -import static com.jayway.awaitility.Awaitility.await; -import static com.jayway.awaitility.Awaitility.to; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; - -@RunWith(Arquillian.class) -public class ScheduleTimerBeanIntegrationTest { - - private final static long TIMEOUT = 5000l; - private final static long TOLERANCE = 1000l; - - @Inject TimerEventListener timerEventListener; - - @Deployment - public static WebArchive deploy() { - File[] jars = Maven - .resolver() - .loadPomFromFile("pom.xml") - .resolve("com.jayway.awaitility:awaitility") - .withTransitivity() - .asFile(); - - return ShrinkWrap - .create(WebArchive.class) - .addAsLibraries(jars) - .addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ScheduleTimerBean.class); - } - - @Test - public void should_receive_three_pings() { - - Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS); - await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(3)); - - TimerEvent firstEvent = timerEventListener - .getEvents() - .get(0); - TimerEvent secondEvent = timerEventListener - .getEvents() - .get(1); - TimerEvent thirdEvent = timerEventListener - .getEvents() - .get(2); - - long delay = secondEvent.getTime() - firstEvent.getTime(); - assertThat(delay, Matchers.is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE))); - delay = thirdEvent.getTime() - secondEvent.getTime(); - assertThat(delay, Matchers.is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE))); - - } -} diff --git a/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanLiveTest.java b/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanLiveTest.java new file mode 100644 index 0000000000..a4ed9ceb68 --- /dev/null +++ b/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanLiveTest.java @@ -0,0 +1,67 @@ +package com.baeldung.timer; + +import com.jayway.awaitility.Awaitility; +import org.hamcrest.Matchers; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.jboss.shrinkwrap.resolver.api.maven.Maven; +import org.junit.Test; +import org.junit.runner.RunWith; + +import javax.inject.Inject; +import java.io.File; +import java.util.concurrent.TimeUnit; + +import static com.jayway.awaitility.Awaitility.await; +import static com.jayway.awaitility.Awaitility.to; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +@RunWith(Arquillian.class) +public class ScheduleTimerBeanLiveTest { + + private final static long TIMEOUT = 5000l; + private final static long TOLERANCE = 1000l; + + @Inject TimerEventListener timerEventListener; + + @Deployment + public static WebArchive deploy() { + File[] jars = Maven + .resolver() + .loadPomFromFile("pom.xml") + .resolve("com.jayway.awaitility:awaitility") + .withTransitivity() + .asFile(); + + return ShrinkWrap + .create(WebArchive.class) + .addAsLibraries(jars) + .addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ScheduleTimerBean.class); + } + + @Test + public void should_receive_three_pings() { + + Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS); + await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(3)); + + TimerEvent firstEvent = timerEventListener + .getEvents() + .get(0); + TimerEvent secondEvent = timerEventListener + .getEvents() + .get(1); + TimerEvent thirdEvent = timerEventListener + .getEvents() + .get(2); + + long delay = secondEvent.getTime() - firstEvent.getTime(); + assertThat(delay, Matchers.is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE))); + delay = thirdEvent.getTime() - secondEvent.getTime(); + assertThat(delay, Matchers.is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE))); + + } +} diff --git a/jenkins/hello-world/pom.xml b/jenkins/hello-world/pom.xml index 8c6d691b29..5684deaea3 100644 --- a/jenkins/hello-world/pom.xml +++ b/jenkins/hello-world/pom.xml @@ -1,19 +1,10 @@ - + 4.0.0 - - org.jenkins-ci.plugins - plugin - 2.33 - - jenkins-hello-world 1.0-SNAPSHOT hpi - - - 2.7.3 - Hello World Plugin A sample Jenkins Hello World plugin https://wiki.jenkins-ci.org/display/JENKINS/TODO+Plugin @@ -23,52 +14,60 @@ http://opensource.org/licenses/MIT + + + org.jenkins-ci.plugins + plugin + 2.33 + + + org.jenkins-ci.plugins structs - 1.7 + ${structs.version} org.jenkins-ci.plugins.workflow workflow-step-api - 2.12 + ${workflow-step-api.version} test org.jenkins-ci.plugins.workflow workflow-cps - 2.39 + ${workflow-cps.version} test org.jenkins-ci.plugins.workflow workflow-job - 2.11.2 + ${workflow-job.version} test org.jenkins-ci.plugins.workflow workflow-basic-steps - 2.6 + ${workflow-basic-steps.version} test org.jenkins-ci.plugins.workflow workflow-durable-task-step - 2.13 + ${workflow-durable-task-step.version} test org.jenkins-ci.plugins.workflow workflow-api - 2.20 + ${workflow-api.version} test org.jenkins-ci.plugins.workflow workflow-support - 2.14 + ${workflow-support.version} test @@ -86,4 +85,19 @@ https://repo.jenkins-ci.org/public/ + + + + 2.7.3 + + 1.7 + 2.12 + 2.39 + 2.11.2 + 2.6 + 2.13 + 2.20 + 2.14 + + diff --git a/jenkins/hello-world/src/main/resources/logback.xml b/jenkins/hello-world/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/jenkins/hello-world/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/jersey/README.md b/jersey/README.md index a4c8c52d68..3121c560cf 100644 --- a/jersey/README.md +++ b/jersey/README.md @@ -1 +1,2 @@ -- [Jersey Filters and Interceptors] (http://www.baeldung.com/jersey-filters-interceptors) +- [Jersey Filters and Interceptors](http://www.baeldung.com/jersey-filters-interceptors) +- [Jersey MVC Support](https://www.baeldung.com/jersey-mvc) diff --git a/jersey/pom.xml b/jersey/pom.xml index b41ea1f340..e248f9cf90 100644 --- a/jersey/pom.xml +++ b/jersey/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.baeldung jersey @@ -31,9 +30,26 @@ ${jersey.version} - org.slf4j - slf4j-api - ${slf4j.version} + org.glassfish.jersey.containers + jersey-container-grizzly2-servlet + ${jersey.version} + + + org.glassfish.jersey.ext + jersey-mvc-freemarker + ${jersey.version} + + + org.glassfish.jersey.test-framework + jersey-test-framework-core + ${jersey.version} + test + + + org.glassfish.jersey.test-framework.providers + jersey-test-framework-provider-grizzly2 + ${jersey.version} + test @@ -47,12 +63,18 @@ false + + org.codehaus.mojo + exec-maven-plugin + + com.baeldung.jersey.server.http.EmbeddedHttpServer + + 2.26 - 1.7.25 3.2.0 diff --git a/jersey/src/main/java/com/baeldung/jersey/server/Responder.java b/jersey/src/main/java/com/baeldung/jersey/server/Responder.java new file mode 100644 index 0000000000..cb0c976fe3 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/Responder.java @@ -0,0 +1,102 @@ +package com.baeldung.jersey.server; + +import com.baeldung.jersey.server.model.Person; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +@Path("/response") +public class Responder { + + @GET + @Path("/ok") + public Response getOkResponse() { + + String message = "This is a text response"; + + return Response + .status(Response.Status.OK) + .entity(message) + .build(); + } + + @GET + @Path("/not_ok") + public Response getNOkTextResponse() { + + String message = "There was an internal server error"; + + return Response + .status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(message) + .build(); + } + + @GET + @Path("/text_plain") + public Response getTextResponseTypeDefined() { + + String message = "This is a plain text response"; + + return Response + .status(Response.Status.OK) + .entity(message) + .type(MediaType.TEXT_PLAIN) + .build(); + } + + @GET + @Path("/text_plain_annotation") + @Produces({ MediaType.TEXT_PLAIN }) + public Response getTextResponseTypeAnnotated() { + + String message = "This is a plain text response via annotation"; + + return Response + .status(Response.Status.OK) + .entity(message) + .build(); + } + + @GET + @Path("/pojo") + public Response getPojoResponse() { + + Person person = new Person("Abh", "Nepal"); + + return Response + .status(Response.Status.OK) + .entity(person) + .build(); + } + + @GET + @Path("/json") + public Response getJsonResponse() { + + String message = "{\"hello\": \"This is a JSON response\"}"; + + return Response + .status(Response.Status.OK) + .entity(message) + .type(MediaType.APPLICATION_JSON) + .build(); + } + + @GET + @Path("/xml") + @Produces(MediaType.TEXT_XML) + public String sayXMLHello() { + return "" + " This is a xml response "; + } + + @GET + @Path("/html") + @Produces(MediaType.TEXT_HTML) + public String sayHtmlHello() { + return " " + "" + " This is a html title " + "

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

    " + " "; + } +} \ No newline at end of file diff --git a/jersey/src/main/java/com/baeldung/jersey/server/config/ViewApplicationConfig.java b/jersey/src/main/java/com/baeldung/jersey/server/config/ViewApplicationConfig.java new file mode 100644 index 0000000000..d4744066c4 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/config/ViewApplicationConfig.java @@ -0,0 +1,14 @@ +package com.baeldung.jersey.server.config; + +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.server.mvc.freemarker.FreemarkerMvcFeature; + +public class ViewApplicationConfig extends ResourceConfig { + + public ViewApplicationConfig() { + packages("com.baeldung.jersey.server"); + property(FreemarkerMvcFeature.TEMPLATE_BASE_PATH, "templates/freemarker"); + register(FreemarkerMvcFeature.class);; + } + +} diff --git a/jersey/src/main/java/com/baeldung/jersey/server/http/EmbeddedHttpServer.java b/jersey/src/main/java/com/baeldung/jersey/server/http/EmbeddedHttpServer.java new file mode 100644 index 0000000000..4afa086858 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/http/EmbeddedHttpServer.java @@ -0,0 +1,35 @@ +package com.baeldung.jersey.server.http; + +import java.io.IOException; +import java.net.URI; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.glassfish.grizzly.http.server.HttpServer; +import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; + +import com.baeldung.jersey.server.config.ViewApplicationConfig; + +public class EmbeddedHttpServer { + + private static final URI BASE_URI = URI.create("http://localhost:8082/"); + + public static void main(String[] args) { + try { + final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, new ViewApplicationConfig(), false); + + Runtime.getRuntime() + .addShutdownHook(new Thread(() -> { + server.shutdownNow(); + })); + + server.start(); + + System.out.println(String.format("Application started.\nTry out %s\nStop the application using CTRL+C", BASE_URI + "fruit")); + } catch (IOException ex) { + Logger.getLogger(EmbeddedHttpServer.class.getName()) + .log(Level.SEVERE, null, ex); + } + + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java b/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java new file mode 100644 index 0000000000..30620e331d --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java @@ -0,0 +1,20 @@ +package com.baeldung.jersey.server.model; + +public class Fruit { + + private final String name; + private final String colour; + + public Fruit(String name, String colour) { + this.name = name; + this.colour = colour; + } + + public String getName() { + return name; + } + + public String getColour() { + return colour; + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/server/model/Person.java b/jersey/src/main/java/com/baeldung/jersey/server/model/Person.java new file mode 100644 index 0000000000..98c86bbc3d --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/model/Person.java @@ -0,0 +1,32 @@ +package com.baeldung.jersey.server.model; + +public class Person { + String name; + String address; + + public Person(String name, String address) { + this.name = name; + this.address = address; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + @Override + public String toString() { + return "Person [name: " + getName() + " address: " + getAddress() + "]"; + } +} \ No newline at end of file diff --git a/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java b/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java new file mode 100644 index 0000000000..4e1fa4aa11 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java @@ -0,0 +1,55 @@ +package com.baeldung.jersey.server.rest; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +import org.glassfish.jersey.server.mvc.ErrorTemplate; +import org.glassfish.jersey.server.mvc.Template; +import org.glassfish.jersey.server.mvc.Viewable; + +import com.baeldung.jersey.server.model.Fruit; + +@Path("/fruit") +public class FruitResource { + + @GET + public Viewable get() { + return new Viewable("/index.ftl", "Fruit Index Page"); + } + + @GET + @Template(name = "/all.ftl") + @Path("/all") + @Produces(MediaType.TEXT_HTML) + public Map getAllFruit() { + final List fruits = new ArrayList<>(); + fruits.add(new Fruit("banana", "yellow")); + fruits.add(new Fruit("apple", "red")); + fruits.add(new Fruit("kiwi", "green")); + + final Map model = new HashMap(); + model.put("items", fruits); + return model; + } + + @GET + @ErrorTemplate(name = "/error.ftl") + @Template(name = "/named.ftl") + @Path("{name}") + @Produces(MediaType.TEXT_HTML) + public String getFruitByName(@PathParam("name") String name) { + if (!"banana".equalsIgnoreCase(name)) { + throw new IllegalArgumentException("Fruit not found: " + name); + } + return name; + } + +} diff --git a/jersey/src/main/resources/logback.xml b/jersey/src/main/resources/logback.xml index d87a87bf53..7d900d8ea8 100644 --- a/jersey/src/main/resources/logback.xml +++ b/jersey/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/jersey/src/main/resources/templates/freemarker/all.ftl b/jersey/src/main/resources/templates/freemarker/all.ftl new file mode 100644 index 0000000000..59406a60ca --- /dev/null +++ b/jersey/src/main/resources/templates/freemarker/all.ftl @@ -0,0 +1,14 @@ + + + All fruit! + + +

    All fruit!

    +

    Fruits:

    +
      + <#list items as fruit> +
    • ${fruit.name}
    • + +
    + + \ No newline at end of file diff --git a/jersey/src/main/resources/templates/freemarker/error.ftl b/jersey/src/main/resources/templates/freemarker/error.ftl new file mode 100644 index 0000000000..8ea6828ba5 --- /dev/null +++ b/jersey/src/main/resources/templates/freemarker/error.ftl @@ -0,0 +1,8 @@ + + + Welcome! + + +

    Error - ${model.message}!

    + + \ No newline at end of file diff --git a/jersey/src/main/resources/templates/freemarker/index.ftl b/jersey/src/main/resources/templates/freemarker/index.ftl new file mode 100644 index 0000000000..01447f24e8 --- /dev/null +++ b/jersey/src/main/resources/templates/freemarker/index.ftl @@ -0,0 +1,8 @@ + + + Welcome! + + +

    Welcome ${model}!

    + + \ No newline at end of file diff --git a/jersey/src/main/resources/templates/freemarker/named.ftl b/jersey/src/main/resources/templates/freemarker/named.ftl new file mode 100644 index 0000000000..ccde3307e6 --- /dev/null +++ b/jersey/src/main/resources/templates/freemarker/named.ftl @@ -0,0 +1,8 @@ + + + Welcome! + + +

    Found fruit - ${model}!

    + + \ No newline at end of file diff --git a/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java b/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java new file mode 100644 index 0000000000..a6fd606e3f --- /dev/null +++ b/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java @@ -0,0 +1,35 @@ +package com.baeldung.jersey.client; + +import javax.ws.rs.core.Response; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +@Ignore +public class JerseyClientIntegrationTest { + + private static int HTTP_OK = 200; + + @Test + public void givenGreetingResource_whenCallingHelloGreeting_thenHelloReturned() { + String response = JerseyClient.getHelloGreeting(); + + Assert.assertEquals("hello", response); + } + + @Test + public void givenGreetingResource_whenCallingHiGreeting_thenHiReturned() { + String response = JerseyClient.getHiGreeting(); + + Assert.assertEquals("hi", response); + } + + @Test + public void givenGreetingResource_whenCallingCustomGreeting_thenCustomGreetingReturned() { + Response response = JerseyClient.getCustomGreeting(); + + Assert.assertEquals(HTTP_OK, response.getStatus()); + } + +} diff --git a/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java b/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java deleted file mode 100644 index 72ba4cc5b9..0000000000 --- a/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.jersey.client; - -import javax.ws.rs.core.Response; - -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - -@Ignore -public class JerseyClientTest { - - private static int HTTP_OK = 200; - - @Test - public void givenGreetingResource_whenCallingHelloGreeting_thenHelloReturned() { - String response = JerseyClient.getHelloGreeting(); - - Assert.assertEquals("hello", response); - } - - @Test - public void givenGreetingResource_whenCallingHiGreeting_thenHiReturned() { - String response = JerseyClient.getHiGreeting(); - - Assert.assertEquals("hi", response); - } - - @Test - public void givenGreetingResource_whenCallingCustomGreeting_thenCustomGreetingReturned() { - Response response = JerseyClient.getCustomGreeting(); - - Assert.assertEquals(HTTP_OK, response.getStatus()); - } - -} diff --git a/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java b/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java new file mode 100644 index 0000000000..a0b6daed51 --- /dev/null +++ b/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java @@ -0,0 +1,42 @@ +package com.baeldung.jersey.server.rest; + +import static org.hamcrest.CoreMatchers.allOf; +import static org.hamcrest.CoreMatchers.containsString; + +import javax.ws.rs.core.Application; + +import org.glassfish.jersey.test.JerseyTest; +import org.junit.Assert; +import org.junit.Test; + +import com.baeldung.jersey.server.config.ViewApplicationConfig; + +public class FruitResourceIntegrationTest extends JerseyTest { + + @Override + protected Application configure() { + return new ViewApplicationConfig(); + } + + @Test + public void testAllFruit() { + final String response = target("/fruit/all").request() + .get(String.class); + Assert.assertThat(response, allOf(containsString("banana"), containsString("apple"), containsString("kiwi"))); + } + + @Test + public void testIndex() { + final String response = target("/fruit").request() + .get(String.class); + Assert.assertThat(response, containsString("Welcome Fruit Index Page!")); + } + + @Test + public void testErrorTemplate() { + final String response = target("/fruit/orange").request() + .get(String.class); + Assert.assertThat(response, containsString("Error - Fruit not found: orange!")); + } + +} diff --git a/jgroups/pom.xml b/jgroups/pom.xml index 6340e41565..34bdd59919 100644 --- a/jgroups/pom.xml +++ b/jgroups/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 jgroups 0.1-SNAPSHOT @@ -28,7 +28,6 @@ - UTF-8 4.0.10.Final diff --git a/jgroups/src/main/resources/logback.xml b/jgroups/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/jgroups/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/jhipster/jhipster-microservice/car-app/pom.xml b/jhipster/jhipster-microservice/car-app/pom.xml index 77e214234e..c52def554f 100644 --- a/jhipster/jhipster-microservice/car-app/pom.xml +++ b/jhipster/jhipster-microservice/car-app/pom.xml @@ -1,19 +1,19 @@ - + 4.0.0 - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 - com.car.app - carapp + car-app 0.0.1-SNAPSHOT war - Carapp + car-app ${maven.version} @@ -47,8 +47,8 @@ 3.1.3 v6.10.0 - - + + ${project.build.directory}/test-results 0.0.20 @@ -61,13 +61,15 @@ S3437,UndocumentedApi,BoldAndItalicTagsCheck - + src/main/webapp/app/**/*.* Web:BoldAndItalicTagsCheck src/main/java/**/* squid:S3437 - + src/main/java/**/* squid:UndocumentedApi @@ -399,8 +401,7 @@ org.springframework.cloud spring-cloud-starter-ribbon - + netty-transport-native-epoll @@ -428,15 +429,13 @@ + spring-boot:run - + org.eclipse.m2e lifecycle-mapping @@ -454,7 +453,7 @@ - + @@ -506,8 +505,8 @@ maven-compiler-plugin ${maven-compiler-plugin.version} - 1.8 - 1.8 + ${maven.compiler.source} + ${maven.compiler.target} org.mapstruct @@ -657,9 +656,9 @@ src/main/resources/config/liquibase/changelog/${maven.build.timestamp}_changelog.xml org.h2.Driver jdbc:h2:file:./target/h2db/db/carapp - + carapp - + hibernate:spring:com.car.app.domain?dialect=org.hibernate.dialect.H2Dialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy true debug @@ -676,15 +675,13 @@ true true - + + no-liquibase @@ -708,7 +705,7 @@ org.apache.maven.plugins maven-war-plugin - + @@ -747,7 +744,7 @@ org.apache.maven.plugins maven-war-plugin - + org.springframework.boot @@ -779,15 +776,9 @@ - + cc @@ -847,10 +838,7 @@ true true true - +
    @@ -874,9 +862,7 @@ - + graphite @@ -886,9 +872,7 @@ - + prometheus @@ -909,11 +893,7 @@ - + IDE diff --git a/jhipster/jhipster-microservice/dealer-app/pom.xml b/jhipster/jhipster-microservice/dealer-app/pom.xml index beada8f064..a9366e9bd3 100644 --- a/jhipster/jhipster-microservice/dealer-app/pom.xml +++ b/jhipster/jhipster-microservice/dealer-app/pom.xml @@ -1,110 +1,19 @@ - + 4.0.0 - - - parent-boot-5 - com.baeldung - 0.0.1-SNAPSHOT - ../../../parent-boot-5 - - com.dealer.app - dealerapp + dealer-app 0.0.1-SNAPSHOT war - Dealerapp + dealer-app - - ${maven.version} - - - - -Djava.security.egd=file:/dev/./urandom -Xmx256m - 3.6.2 - 2.0.0 - 2.5 - 3.5 - 0.4.13 - 1.2 - 5.2.8.Final - 2.6.0 - 0.7.9 - 1.8 - 3.21.0-GA - 1.0.0 - 1.1.0 - 0.7.0 - 3.6 - 2.0.0 - 4.8 - jdt_apt - 1.1.0.Final - 1.4.1 - 3.0.1 - yyyyMMddHHmmss - 3.0.0 - 3.1.3 - v6.10.0 - - - - 0.0.20 - - ${project.build.directory}/test-results - false - 3.2.2 - 2.12.1 - 3.2 - - src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* - - S3437,UndocumentedApi,BoldAndItalicTagsCheck - - - src/main/webapp/app/**/*.* - Web:BoldAndItalicTagsCheck - - src/main/java/**/* - squid:S3437 - - src/main/java/**/* - squid:UndocumentedApi - - ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec - ${project.testresult.directory}/coverage/jacoco/jacoco.exec - jacoco - - ${project.testresult.directory}/karma - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.basedir}/src/main/ - ${project.testresult.directory}/surefire-reports - ${project.basedir}/src/test/ - - 2.5.0 - - Camden.SR5 - 2.6.1 - 1.4.10.Final - 1.1.0.Final - v0.21.3 - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../../parent-boot-1 + @@ -360,8 +269,7 @@ org.springframework.cloud spring-cloud-starter-ribbon - + io.netty @@ -423,6 +331,7 @@ + spring-boot:run @@ -620,10 +529,7 @@ true true - + @@ -646,11 +552,8 @@ - + org.eclipse.m2e lifecycle-mapping @@ -672,7 +575,7 @@ - + @@ -682,6 +585,7 @@ + no-liquibase @@ -778,15 +682,9 @@ - + cc @@ -815,10 +713,7 @@ true true true - +
    @@ -873,9 +768,7 @@ - + graphite @@ -885,9 +778,7 @@ - + prometheus @@ -908,11 +799,7 @@ - + IDE @@ -923,4 +810,97 @@ + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + ${maven.version} + + + + -Djava.security.egd=file:/dev/./urandom -Xmx256m + 3.6.2 + 2.0.0 + 2.5 + 3.5 + 0.4.13 + 1.2 + 5.2.8.Final + 2.6.0 + 0.7.9 + 3.21.0-GA + 1.0.0 + 1.1.0 + 0.7.0 + 3.6 + 2.0.0 + 4.8 + jdt_apt + 1.1.0.Final + 1.4.1 + 3.0.1 + yyyyMMddHHmmss + 3.0.0 + 3.1.3 + v6.10.0 + + + + 0.0.20 + + ${project.build.directory}/test-results + false + 3.2.2 + 2.12.1 + 3.2 + + src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* + + S3437,UndocumentedApi,BoldAndItalicTagsCheck + + + src/main/webapp/app/**/*.* + Web:BoldAndItalicTagsCheck + + src/main/java/**/* + squid:S3437 + + src/main/java/**/* + squid:UndocumentedApi + + ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec + ${project.testresult.directory}/coverage/jacoco/jacoco.exec + jacoco + + ${project.testresult.directory}/karma + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.basedir}/src/main/ + ${project.testresult.directory}/surefire-reports + ${project.basedir}/src/test/ + + 2.5.0 + + Camden.SR5 + 2.6.1 + 1.4.10.Final + 1.1.0.Final + v0.21.3 + + diff --git a/jhipster/jhipster-microservice/gateway-app/package.json b/jhipster/jhipster-microservice/gateway-app/package.json index ece70314ab..abdff9ffe3 100644 --- a/jhipster/jhipster-microservice/gateway-app/package.json +++ b/jhipster/jhipster-microservice/gateway-app/package.json @@ -49,7 +49,7 @@ "karma-phantomjs-launcher": "1.0.2", "karma-script-launcher": "1.0.0", "lazypipe": "1.0.1", - "lodash": "4.15.0", + "lodash": "4.17.10", "main-bower-files": "2.13.1", "map-stream": "0.0.6", "phantomjs-prebuilt": "2.1.12", diff --git a/jhipster/jhipster-microservice/gateway-app/pom.xml b/jhipster/jhipster-microservice/gateway-app/pom.xml index d90addf51b..0ae74e11bb 100644 --- a/jhipster/jhipster-microservice/gateway-app/pom.xml +++ b/jhipster/jhipster-microservice/gateway-app/pom.xml @@ -1,112 +1,19 @@ - + 4.0.0 - - - parent-boot-5 - com.baeldung - 0.0.1-SNAPSHOT - ../../../parent-boot-5 - - com.gateway - gateway + gateway-app 0.0.1-SNAPSHOT war - Gateway + gateway-app - - ${maven.version} - - - - -Djava.security.egd=file:/dev/./urandom -Xmx256m - 3.6.2 - 2.0.0 - 1.10 - 2.5 - 3.5 - 0.4.13 - 1.3 - 1.2 - 5.2.8.Final - 2.6.0 - 0.7.9 - 3.21.0-GA - 1.0.0 - 1.1.0 - 0.7.0 - 3.6 - 2.0.0 - 4.8 - 1.3.0 - jdt_apt - 1.1.0.Final - 1.4.1 - 3.0.1 - yyyyMMddHHmmss - 3.0.0 - 3.1.3 - v6.10.0 - - - - 0.0.20 - - ${project.build.directory}/test-results - false - 3.2.2 - 2.12.1 - 3.2 - - src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* - - S3437,UndocumentedApi,BoldAndItalicTagsCheck - - - src/main/webapp/app/**/*.* - Web:BoldAndItalicTagsCheck - - src/main/java/**/* - squid:S3437 - - src/main/java/**/* - squid:UndocumentedApi - - ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec - ${project.testresult.directory}/coverage/jacoco/jacoco.exec - jacoco - - ${project.testresult.directory}/karma - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.basedir}/src/main/ - ${project.testresult.directory}/surefire-reports - ${project.basedir}/src/test/ - - 2.5.0 - - Camden.SR5 - 2.6.1 - 1.4.10.Final - 1.1.0.Final - v0.21.3 - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../../parent-boot-1 + @@ -401,8 +308,7 @@ org.springframework.cloud spring-cloud-starter-ribbon - + io.netty @@ -464,6 +370,7 @@ + spring-boot:run @@ -661,10 +568,7 @@ true true - + @@ -687,11 +591,8 @@ - + org.eclipse.m2e lifecycle-mapping @@ -713,7 +614,7 @@ - + @@ -729,7 +630,7 @@ - + @@ -739,6 +640,7 @@ + no-liquibase @@ -891,15 +793,9 @@ - + cc @@ -928,10 +824,7 @@ true true true - + @@ -986,9 +879,7 @@ - + graphite @@ -998,9 +889,7 @@ - + prometheus @@ -1021,11 +910,7 @@ - + IDE @@ -1036,4 +921,100 @@ + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + ${maven.version} + + + + -Djava.security.egd=file:/dev/./urandom -Xmx256m + 3.6.2 + 2.0.0 + 1.10 + 2.5 + 3.5 + 0.4.13 + 1.3 + 1.2 + 5.2.8.Final + 2.6.0 + 0.7.9 + 3.21.0-GA + 1.0.0 + 1.1.0 + 0.7.0 + 3.6 + 2.0.0 + 4.8 + 1.3.0 + jdt_apt + 1.1.0.Final + 1.4.1 + 3.0.1 + yyyyMMddHHmmss + 3.0.0 + 3.1.3 + v6.10.0 + + + + 0.0.20 + + ${project.build.directory}/test-results + false + 3.2.2 + 2.12.1 + 3.2 + + src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* + + S3437,UndocumentedApi,BoldAndItalicTagsCheck + + + src/main/webapp/app/**/*.* + Web:BoldAndItalicTagsCheck + + src/main/java/**/* + squid:S3437 + + src/main/java/**/* + squid:UndocumentedApi + + ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec + ${project.testresult.directory}/coverage/jacoco/jacoco.exec + jacoco + + ${project.testresult.directory}/karma + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.basedir}/src/main/ + ${project.testresult.directory}/surefire-reports + ${project.basedir}/src/test/ + + 2.5.0 + + Camden.SR5 + 2.6.1 + 1.4.10.Final + 1.1.0.Final + v0.21.3 + + diff --git a/jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/service/UserServiceIntIntegrationTest.java b/jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/service/UserServiceIntegrationTest.java similarity index 100% rename from jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/service/UserServiceIntIntegrationTest.java rename to jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/service/UserServiceIntegrationTest.java diff --git a/jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/web/rest/UserResourceIntIntegrationTest.java b/jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/web/rest/UserResourceIntegrationTest.java similarity index 100% rename from jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/web/rest/UserResourceIntIntegrationTest.java rename to jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/web/rest/UserResourceIntegrationTest.java diff --git a/jhipster/jhipster-monolithic/package.json b/jhipster/jhipster-monolithic/package.json index 40bbd28799..5f72047fb3 100644 --- a/jhipster/jhipster-monolithic/package.json +++ b/jhipster/jhipster-monolithic/package.json @@ -64,7 +64,7 @@ "karma-sourcemap-loader": "0.3.7", "karma-webpack": "2.0.2", "lazypipe": "1.0.1", - "lodash": "4.17.4", + "lodash": "4.17.10", "map-stream": "0.0.6", "phantomjs-prebuilt": "2.1.14", "protractor": "5.1.1", diff --git a/jhipster/jhipster-monolithic/pom.xml b/jhipster/jhipster-monolithic/pom.xml index fc8e8353b4..9708b83a70 100644 --- a/jhipster/jhipster-monolithic/pom.xml +++ b/jhipster/jhipster-monolithic/pom.xml @@ -1,109 +1,17 @@ - - + 4.0.0 + jhipster-monolithic + war + JHipster Monolithic Application - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 - com.baeldung - jhipster-monolithic - 0.0.1-SNAPSHOT - war - JHipster Monolithic Application - - - ${maven.version} - - - - -Djava.security.egd=file:/dev/./urandom -Xmx256m - 3.6.2 - 2.0.0 - 2.5 - 3.5 - 0.4.13 - 1.3 - 2.2.1 - 2.2.3 - 5.2.8.Final - 2.6.0 - 0.7.9 - 1.8 - 3.21.0-GA - 1.0.0 - 1.1.0 - 0.7.0 - 1.1.3 - 3.6 - 2.0.0 - 4.8 - jdt_apt - 1.1.0.Final - 1.4.1 - 3.0.1 - yyyyMMddHHmmss - 3.0.0 - 3.1.3 - v6.10.0 - 4.3.0 - - - - - ${project.build.directory}/test-results - 0.0.20 - false - 3.2.2 - 2.12.1 - 3.2 - - src/main/webapp/content/**/*.*, - src/main/webapp/bower_components/**/*.*, - src/main/webapp/i18n/*.js, target/www/**/*.* - - - S3437,UndocumentedApi,BoldAndItalicTagsCheck - - - src/main/webapp/app/**/*.* - Web:BoldAndItalicTagsCheck - - src/main/java/**/* - squid:S3437 - - src/main/java/**/* - squid:UndocumentedApi - - ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec - ${project.testresult.directory}/coverage/jacoco/jacoco.exec - jacoco - - ${project.testresult.directory}/karma - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.basedir}/src/main/ - ${project.testresult.directory}/surefire-reports - ${project.basedir}/src/test/ - - 2.5.0 - - 2.6.1 - 1.4.10.Final - 1.1.0.Final - - com.fasterxml.jackson.datatype @@ -129,8 +37,7 @@ com.jayway.jsonpath json-path test - + com.jcraft @@ -180,8 +87,7 @@ io.dropwizard.metrics metrics-annotation - ${dropwizard-metrics.version} - + io.dropwizard.metrics metrics-core @@ -189,18 +95,15 @@ io.dropwizard.metrics metrics-json - ${dropwizard-metrics.version} - + io.dropwizard.metrics metrics-jvm - ${dropwizard-metrics.version} - + io.dropwizard.metrics metrics-servlet - ${dropwizard-metrics.version} - + io.dropwizard.metrics metrics-servlets @@ -389,13 +292,13 @@ + spring-boot:run - + org.eclipse.m2e lifecycle-mapping @@ -413,7 +316,7 @@ - + @@ -427,7 +330,7 @@ - + @@ -437,7 +340,7 @@ - + com.spotify docker-maven-plugin @@ -484,12 +387,9 @@ target/gatling/results src/test/gatling/bodies src/test/gatling/simulations - + true - + @@ -512,6 +412,7 @@ org.apache.maven.plugins maven-eclipse-plugin + ${maven-eclipse-plugin.version} true true @@ -587,19 +488,6 @@ - - org.apache.maven.plugins - maven-surefire-plugin - - - alphabetical - - **/*IntTest.java - - - - org.jacoco jacoco-maven-plugin @@ -611,13 +499,11 @@ prepare-agent - + ${project.testresult.directory}/coverage/jacoco/jacoco.exec - + post-unit-test test @@ -634,7 +520,7 @@ org.liquibase liquibase-maven-plugin - ${liquibase.version} + ${liquibase-maven-plugin.version} javax.validation @@ -662,9 +548,9 @@ src/main/resources/config/liquibase/changelog/${maven.build.timestamp}_changelog.xml org.h2.Driver jdbc:h2:file:./target/h2db/db/baeldung - + baeldung - + hibernate:spring:com.baeldung.domain?dialect=org.hibernate.dialect.H2Dialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy true debug @@ -681,13 +567,13 @@ true true - + + no-liquibase @@ -865,12 +751,9 @@ - + cc @@ -930,8 +813,7 @@ true true true - + @@ -986,8 +868,7 @@ - + IDE @@ -998,4 +879,88 @@ + + + -Djava.security.egd=file:/dev/./urandom -Xmx256m + 3.6.2 + 2.0.0 + 2.5 + 3.5 + 0.4.13 + 1.3 + 2.2.1 + 2.2.3 + 5.2.8.Final + 2.6.0 + 0.7.9 + 3.21.0-GA + 1.0.0 + 1.1.0 + 0.7.0 + 1.1.3 + 3.6 + 2.0.0 + 3.6.2 + 4.8 + jdt_apt + 1.1.0.Final + 1.4.1 + 3.0.1 + 2.10 + yyyyMMddHHmmss + 3.0.0 + 3.1.3 + v6.10.0 + 4.3.0 + + + + + ${project.build.directory}/test-results + 0.0.20 + false + 3.2.2 + 2.12.1 + 3.2 + + src/main/webapp/content/**/*.*, + src/main/webapp/bower_components/**/*.*, + src/main/webapp/i18n/*.js, target/www/**/*.* + + + S3437,UndocumentedApi,BoldAndItalicTagsCheck + + + src/main/webapp/app/**/*.* + Web:BoldAndItalicTagsCheck + + src/main/java/**/* + squid:S3437 + + src/main/java/**/* + squid:UndocumentedApi + + ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec + ${project.testresult.directory}/coverage/jacoco/jacoco.exec + jacoco + + ${project.testresult.directory}/karma + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.basedir}/src/main/ + ${project.testresult.directory}/surefire-reports + ${project.basedir}/src/test/ + + 2.5.0 + + 2.6.1 + 1.4.10.Final + 1.1.0.Final + + diff --git a/jhipster/jhipster-monolithic/src/main/resources/logback-spring.xml b/jhipster/jhipster-monolithic/src/main/resources/logback-spring.xml index 3c62a70c31..2fda7cc968 100644 --- a/jhipster/jhipster-monolithic/src/main/resources/logback-spring.xml +++ b/jhipster/jhipster-monolithic/src/main/resources/logback-spring.xml @@ -3,28 +3,9 @@ - - - - - - + diff --git a/jhipster/jhipster-monolithic/src/test/java/com/baeldung/service/UserServiceIntIntegrationTest.java b/jhipster/jhipster-monolithic/src/test/java/com/baeldung/service/UserServiceIntIntegrationTest.java deleted file mode 100644 index 8b4825453e..0000000000 --- a/jhipster/jhipster-monolithic/src/test/java/com/baeldung/service/UserServiceIntIntegrationTest.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.baeldung.service; - -import com.baeldung.BaeldungApp; -import com.baeldung.domain.User; -import com.baeldung.config.Constants; -import com.baeldung.repository.UserRepository; -import com.baeldung.service.dto.UserDTO; -import java.time.ZonedDateTime; -import com.baeldung.service.util.RandomUtil; -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.transaction.annotation.Transactional; -import org.springframework.test.context.junit4.SpringRunner; - -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import java.util.Optional; -import java.util.List; - -import static org.assertj.core.api.Assertions.*; - -/** - * Test class for the UserResource REST controller. - * - * @see UserService - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BaeldungApp.class) -@Transactional -public class UserServiceIntegrationTest { - - @Autowired - private UserRepository userRepository; - - @Autowired - private UserService userService; - - @Test - public void assertThatUserMustExistToResetPassword() { - Optional maybeUser = userService.requestPasswordReset("john.doe@localhost"); - assertThat(maybeUser.isPresent()).isFalse(); - - maybeUser = userService.requestPasswordReset("admin@localhost"); - assertThat(maybeUser.isPresent()).isTrue(); - - assertThat(maybeUser.get().getEmail()).isEqualTo("admin@localhost"); - assertThat(maybeUser.get().getResetDate()).isNotNull(); - assertThat(maybeUser.get().getResetKey()).isNotNull(); - } - - @Test - public void assertThatOnlyActivatedUserCanRequestPasswordReset() { - User user = userService.createUser("johndoe", "johndoe", "John", "Doe", "john.doe@localhost", "http://placehold.it/50x50", "en-US"); - Optional maybeUser = userService.requestPasswordReset("john.doe@localhost"); - assertThat(maybeUser.isPresent()).isFalse(); - userRepository.delete(user); - } - - @Test - public void assertThatResetKeyMustNotBeOlderThan24Hours() { - User user = userService.createUser("johndoe", "johndoe", "John", "Doe", "john.doe@localhost", "http://placehold.it/50x50", "en-US"); - - ZonedDateTime daysAgo = ZonedDateTime.now().minusHours(25); - String resetKey = RandomUtil.generateResetKey(); - user.setActivated(true); - user.setResetDate(daysAgo); - user.setResetKey(resetKey); - - userRepository.save(user); - - Optional maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); - - assertThat(maybeUser.isPresent()).isFalse(); - - userRepository.delete(user); - } - - @Test - public void assertThatResetKeyMustBeValid() { - User user = userService.createUser("johndoe", "johndoe", "John", "Doe", "john.doe@localhost", "http://placehold.it/50x50", "en-US"); - - ZonedDateTime daysAgo = ZonedDateTime.now().minusHours(25); - user.setActivated(true); - user.setResetDate(daysAgo); - user.setResetKey("1234"); - userRepository.save(user); - Optional maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); - assertThat(maybeUser.isPresent()).isFalse(); - userRepository.delete(user); - } - - @Test - public void assertThatUserCanResetPassword() { - User user = userService.createUser("johndoe", "johndoe", "John", "Doe", "john.doe@localhost", "http://placehold.it/50x50", "en-US"); - String oldPassword = user.getPassword(); - ZonedDateTime daysAgo = ZonedDateTime.now().minusHours(2); - String resetKey = RandomUtil.generateResetKey(); - user.setActivated(true); - user.setResetDate(daysAgo); - user.setResetKey(resetKey); - userRepository.save(user); - Optional maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); - assertThat(maybeUser.isPresent()).isTrue(); - assertThat(maybeUser.get().getResetDate()).isNull(); - assertThat(maybeUser.get().getResetKey()).isNull(); - assertThat(maybeUser.get().getPassword()).isNotEqualTo(oldPassword); - - userRepository.delete(user); - } - - @Test - public void testFindNotActivatedUsersByCreationDateBefore() { - userService.removeNotActivatedUsers(); - ZonedDateTime now = ZonedDateTime.now(); - List users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minusDays(3)); - assertThat(users).isEmpty(); - } - - @Test - public void assertThatAnonymousUserIsNotGet() { - final PageRequest pageable = new PageRequest(0, (int) userRepository.count()); - final Page allManagedUsers = userService.getAllManagedUsers(pageable); - assertThat(allManagedUsers.getContent().stream() - .noneMatch(user -> Constants.ANONYMOUS_USER.equals(user.getLogin()))) - .isTrue(); - } -} diff --git a/jhipster/jhipster-monolithic/src/test/java/com/baeldung/web/rest/CommentResourceIntegrationTest.java b/jhipster/jhipster-monolithic/src/test/java/com/baeldung/web/rest/CommentResourceIntegrationTest.java index 4f544d9eeb..1d4e7126d6 100644 --- a/jhipster/jhipster-monolithic/src/test/java/com/baeldung/web/rest/CommentResourceIntegrationTest.java +++ b/jhipster/jhipster-monolithic/src/test/java/com/baeldung/web/rest/CommentResourceIntegrationTest.java @@ -86,7 +86,7 @@ public class CommentResourceIntegrationTest { .text(DEFAULT_TEXT) .creationDate(DEFAULT_CREATION_DATE); // Add required entity - Post post = PostResourceIntTest.createEntity(em); + Post post = PostResourceIntegrationTest.createEntity(em); em.persist(post); em.flush(); comment.setPost(post); diff --git a/jhipster/jhipster-monolithic/src/test/java/com/baeldung/web/rest/PostResourceIntegrationTest.java b/jhipster/jhipster-monolithic/src/test/java/com/baeldung/web/rest/PostResourceIntegrationTest.java index a9a4bc74b9..a37f901f7a 100644 --- a/jhipster/jhipster-monolithic/src/test/java/com/baeldung/web/rest/PostResourceIntegrationTest.java +++ b/jhipster/jhipster-monolithic/src/test/java/com/baeldung/web/rest/PostResourceIntegrationTest.java @@ -90,7 +90,7 @@ public class PostResourceIntegrationTest { .content(DEFAULT_CONTENT) .creationDate(DEFAULT_CREATION_DATE); // Add required entity - User creator = UserResourceIntTest.createEntity(em); + User creator = UserResourceIntegrationTest.createEntity(em); em.persist(creator); em.flush(); post.setCreator(creator); diff --git a/jhipster/jhipster-monolithic/src/test/java/com/baeldung/web/rest/UserResourceIntIntegrationTest.java b/jhipster/jhipster-monolithic/src/test/java/com/baeldung/web/rest/UserResourceIntegrationTest.java similarity index 100% rename from jhipster/jhipster-monolithic/src/test/java/com/baeldung/web/rest/UserResourceIntIntegrationTest.java rename to jhipster/jhipster-monolithic/src/test/java/com/baeldung/web/rest/UserResourceIntegrationTest.java diff --git a/jjwt/pom.xml b/jjwt/pom.xml index 51d4dcf1c0..6bf9f4426a 100644 --- a/jjwt/pom.xml +++ b/jjwt/pom.xml @@ -1,19 +1,19 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 io.jsonwebtoken - jjwtfun + jjwt 0.0.1-SNAPSHOT jar - jjwtfun + jjwt Exercising the JJWT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/jjwt/src/main/resources/logback.xml b/jjwt/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/jjwt/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/jmeter/pom.xml b/jmeter/pom.xml index bb5769ef57..943b75e03b 100644 --- a/jmeter/pom.xml +++ b/jmeter/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 jmeter 0.0.1-SNAPSHOT @@ -9,10 +9,10 @@ Intro to Performance testing using JMeter - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -59,9 +59,6 @@ - UTF-8 - UTF-8 - 1.8 2.6.0 diff --git a/jmeter/src/main/resources/logback.xml b/jmeter/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/jmeter/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/jmh/README.md b/jmh/README.md index 2a2c6a173a..9c5a70e3c2 100644 --- a/jmh/README.md +++ b/jmh/README.md @@ -1,3 +1,4 @@ ## Relevant articles: - [Microbenchmarking with Java](http://www.baeldung.com/java-microbenchmark-harness) + diff --git a/jmh/pom.xml b/jmh/pom.xml index 60b59262b4..1e01809fe6 100644 --- a/jmh/pom.xml +++ b/jmh/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung jmh @@ -11,8 +11,8 @@ com.baeldung parent-java - 0.0.1-SNAPSHOT - ../parent-java + 0.0.1-SNAPSHOT + ../parent-java @@ -33,6 +33,7 @@ org.apache.maven.plugins maven-jar-plugin + ${maven-jar-plugin.version} @@ -45,10 +46,8 @@ - UTF-8 - UTF-8 - 21.0 1.19 + 3.0.2 \ No newline at end of file diff --git a/jmh/src/main/resources/logback.xml b/jmh/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/jmh/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/jni/README.md b/jni/README.md new file mode 100644 index 0000000000..663cafb0c0 --- /dev/null +++ b/jni/README.md @@ -0,0 +1,4 @@ + +### Relevant Articles: + +- [Guide to JNI (Java Native Interface)](http://www.baeldung.com/jni) diff --git a/jni/pom.xml b/jni/pom.xml index 752277f526..274b9b58c3 100644 --- a/jni/pom.xml +++ b/jni/pom.xml @@ -1,15 +1,21 @@ - - 4.0.0 - com.baeldung - jni - 0.0.1-SNAPSHOT - - - - junit - junit - 4.8.1 - test - - + + 4.0.0 + com.baeldung + jni + 0.0.1-SNAPSHOT + + + + junit + junit + ${junit.version} + test + + + + + 4.8.1 + + \ No newline at end of file diff --git a/jni/src/main/resources/logback.xml b/jni/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/jni/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/jnosql/README.md b/jnosql/README.md new file mode 100644 index 0000000000..d580cbc920 --- /dev/null +++ b/jnosql/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [A Guide to Eclipse JNoSQL](http://www.baeldung.com/eclipse-jnosql) diff --git a/jnosql/jnosql-artemis/pom.xml b/jnosql/jnosql-artemis/pom.xml new file mode 100644 index 0000000000..9c2bfd1ba0 --- /dev/null +++ b/jnosql/jnosql-artemis/pom.xml @@ -0,0 +1,88 @@ + + + 4.0.0 + + + com.baeldung.jnosql + jnosql + 1.0-SNAPSHOT + + + jnosql-artemis + war + + + 2.4.2 + false + + + + ${project.artifactId} + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + ${liberty-maven-plugin.version} + + + io.openliberty + openliberty-webProfile8 + RELEASE + zip + + project + true + src/main/liberty/config/server.xml + + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + + + + + + javax + javaee-web-api + 8.0 + provided + + + + org.jnosql.artemis + artemis-configuration + ${jnosql.version} + + + org.jnosql.artemis + artemis-document + ${jnosql.version} + + + org.jnosql.diana + mongodb-driver + ${jnosql.version} + + + + + diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/AppConfig.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/AppConfig.java new file mode 100644 index 0000000000..bf445d9d01 --- /dev/null +++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/AppConfig.java @@ -0,0 +1,10 @@ +package com.baeldung.jnosql.artemis; + +import javax.enterprise.context.Initialized; +import javax.enterprise.event.Observes; +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("") +public class AppConfig extends Application { +} diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EmbeddedMongoDBSetup.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EmbeddedMongoDBSetup.java new file mode 100644 index 0000000000..8b3e161f85 --- /dev/null +++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EmbeddedMongoDBSetup.java @@ -0,0 +1,52 @@ +package com.baeldung.jnosql.artemis; + +import de.flapdoodle.embed.mongo.MongodExecutable; +import de.flapdoodle.embed.mongo.MongodProcess; +import de.flapdoodle.embed.mongo.MongodStarter; +import de.flapdoodle.embed.mongo.config.MongodConfigBuilder; +import de.flapdoodle.embed.mongo.config.Net; +import de.flapdoodle.embed.mongo.distribution.Version; +import de.flapdoodle.embed.process.runtime.Network; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.context.Destroyed; +import javax.enterprise.context.Initialized; +import javax.enterprise.event.Observes; +import java.io.IOException; + +@ApplicationScoped +public class EmbeddedMongoDBSetup { + + private static final String MONGODB_HOST = "localhost"; + private static final int MONGODB_PORT = 27019; + + private static final MongodStarter starter = MongodStarter.getDefaultInstance(); + private static MongodExecutable _mongodExe; + private static MongodProcess _mongod; + + public void init(@Observes @Initialized(ApplicationScoped.class) Object init) { + try { + System.out.println("Starting Embedded MongoDB"); + initdb(); + System.out.println("Embedded MongoDB started"); + } catch (IOException e) { + System.out.println("Embedded MongoDB starting error !!"); + e.printStackTrace(); + } + } + + private void initdb() throws IOException { + _mongodExe = starter.prepare(new MongodConfigBuilder() + .version(Version.Main.DEVELOPMENT) + .net(new Net(MONGODB_HOST, MONGODB_PORT, Network.localhostIsIPv6())) + .build()); + _mongod = _mongodExe.start(); + } + + public void destroy(@Observes @Destroyed(ApplicationScoped.class) Object init) { + System.out.println("Stopping Embedded MongoDB"); + _mongod.stop(); + _mongodExe.stop(); + System.out.println("Embedded MongoDB stopped !"); + } +} diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EntityManagerProducer.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EntityManagerProducer.java new file mode 100644 index 0000000000..c51868886b --- /dev/null +++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EntityManagerProducer.java @@ -0,0 +1,33 @@ +package com.baeldung.jnosql.artemis; + +import org.jnosql.artemis.ConfigurationUnit; +import org.jnosql.diana.api.document.DocumentCollectionManager; +import org.jnosql.diana.api.document.DocumentCollectionManagerFactory; +import org.jnosql.diana.mongodb.document.MongoDBDocumentCollectionManager; +import org.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration; + +import javax.annotation.PostConstruct; +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.Disposes; +import javax.enterprise.inject.Produces; +import javax.inject.Inject; + +@ApplicationScoped +public class EntityManagerProducer { + + private static final String DATABASE = "todos"; + + @Inject + @ConfigurationUnit(name = "document") + private DocumentCollectionManagerFactory managerFactory; + + @Produces + public DocumentCollectionManager getEntityManager() { + return managerFactory.get(DATABASE); + } + + public void close(@Disposes DocumentCollectionManager entityManager) { + entityManager.close(); + } + +} diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/RepositoryTodoManager.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/RepositoryTodoManager.java new file mode 100644 index 0000000000..2b19858f6d --- /dev/null +++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/RepositoryTodoManager.java @@ -0,0 +1,41 @@ +package com.baeldung.jnosql.artemis; + +import com.baeldung.jnosql.artemis.qualifier.Repo; +import org.jnosql.artemis.Database; +import org.jnosql.artemis.DatabaseType; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import java.util.List; +import java.util.Optional; + +@ApplicationScoped +@Repo +public class RepositoryTodoManager implements TodoManager { + + @Inject + @Database(DatabaseType.DOCUMENT) + private TodoRepository repository; + + @Override + public Todo add(Todo todo) { + return repository.save(todo); + } + + @Override + public Todo get(String id) { + Optional todo = repository.findById(id); + return todo.get(); + } + + @Override + public List getAll() { + return repository.findAll(); + } + + @Override + public void delete(String id) { + repository.deleteById(id); + } + +} diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TemplateTodoManager.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TemplateTodoManager.java new file mode 100644 index 0000000000..8c9ce745f7 --- /dev/null +++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TemplateTodoManager.java @@ -0,0 +1,43 @@ +package com.baeldung.jnosql.artemis; + +import com.baeldung.jnosql.artemis.qualifier.Template; +import org.jnosql.artemis.document.DocumentTemplate; +import org.jnosql.diana.api.document.DocumentQuery; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import java.util.List; +import java.util.Optional; + +import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.select; + +@ApplicationScoped +@Template +public class TemplateTodoManager implements TodoManager { + + @Inject + private DocumentTemplate documentTemplate; + + @Override + public Todo add(Todo todo) { + return documentTemplate.insert(todo); + } + + @Override + public Todo get(String id) { + Optional todo = documentTemplate.find(Todo.class, id); + return todo.get(); + } + + @Override + public List getAll() { + DocumentQuery query = select().from("Todo").build(); + return documentTemplate.select(query); + } + + @Override + public void delete(String id) { + documentTemplate.delete(Todo.class, id); + } + +} diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/Todo.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/Todo.java new file mode 100644 index 0000000000..f250ddfa66 --- /dev/null +++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/Todo.java @@ -0,0 +1,51 @@ +package com.baeldung.jnosql.artemis; + +import org.jnosql.artemis.Column; +import org.jnosql.artemis.Entity; +import org.jnosql.artemis.Id; + +import java.io.Serializable; + +@Entity +public class Todo implements Serializable { + + @Id("id") + public String id; + @Column + public String name; + @Column + public String description; + + public Todo() { + } + + public Todo(String id, String name, String description) { + this.id = id; + this.name = name; + this.description = description; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } +} diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoManager.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoManager.java new file mode 100644 index 0000000000..cdcfea5b40 --- /dev/null +++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoManager.java @@ -0,0 +1,14 @@ +package com.baeldung.jnosql.artemis; + +import java.util.List; + +public interface TodoManager { + + Todo add(Todo todo); + + Todo get(String id); + + List getAll(); + + void delete(String id); +} diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoRepository.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoRepository.java new file mode 100644 index 0000000000..52381d1757 --- /dev/null +++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.jnosql.artemis; + +import org.jnosql.artemis.Repository; + +import java.util.List; + +public interface TodoRepository extends Repository { + List findByName(String name); + List findAll(); +} diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoResource.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoResource.java new file mode 100644 index 0000000000..42149af3cc --- /dev/null +++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoResource.java @@ -0,0 +1,48 @@ +package com.baeldung.jnosql.artemis; + +import com.baeldung.jnosql.artemis.qualifier.Repo; +import com.baeldung.jnosql.artemis.qualifier.Template; + +import javax.inject.Inject; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; + +@Path("todos") +public class TodoResource { + + /* + Use eiher @Template or @Repo + */ + @Inject + @Template + //@Repo + private TodoManager todoManager; + + @GET + @Path("") + @Produces(MediaType.APPLICATION_JSON) + public Response all() { + return Response.ok(todoManager.getAll()).build(); + } + + @GET + @Path("{id}") + @Produces(MediaType.APPLICATION_JSON) + public Response get(@PathParam("id") String id) { + Todo todo = todoManager.get(id); + return Response.ok(todo).build(); + } + + @POST + @Consumes(MediaType.APPLICATION_JSON) + public Response add(Todo todo) { + Todo savedTodo = todoManager.add(todo); + System.out.println(savedTodo.id); + return Response.created( + UriBuilder.fromResource(this.getClass()).path(String.valueOf(savedTodo.id)).build()) + .build(); + } + +} diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Repo.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Repo.java new file mode 100644 index 0000000000..a5883946db --- /dev/null +++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Repo.java @@ -0,0 +1,13 @@ +package com.baeldung.jnosql.artemis.qualifier; + +import javax.inject.Qualifier; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.TYPE}) +@Qualifier +public @interface Repo { +} \ No newline at end of file diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Template.java b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Template.java new file mode 100644 index 0000000000..81fbbe5271 --- /dev/null +++ b/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Template.java @@ -0,0 +1,13 @@ +package com.baeldung.jnosql.artemis.qualifier; + +import javax.inject.Qualifier; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.TYPE}) +@Qualifier +public @interface Template { +} \ No newline at end of file diff --git a/jnosql/jnosql-artemis/src/main/liberty/config/server.xml b/jnosql/jnosql-artemis/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..897aca853a --- /dev/null +++ b/jnosql/jnosql-artemis/src/main/liberty/config/server.xml @@ -0,0 +1,6 @@ + + + webProfile-8.0 + + + diff --git a/jnosql/jnosql-artemis/src/main/resources/META-INF/beans.xml b/jnosql/jnosql-artemis/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..4f0b3cdeeb --- /dev/null +++ b/jnosql/jnosql-artemis/src/main/resources/META-INF/beans.xml @@ -0,0 +1,6 @@ + + \ No newline at end of file diff --git a/jnosql/jnosql-artemis/src/main/resources/META-INF/jnosql.json b/jnosql/jnosql-artemis/src/main/resources/META-INF/jnosql.json new file mode 100644 index 0000000000..b8e26cf54a --- /dev/null +++ b/jnosql/jnosql-artemis/src/main/resources/META-INF/jnosql.json @@ -0,0 +1,10 @@ +[ + { + "description": "The mongodb document configuration", + "name": "document", + "provider": "org.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration", + "settings": { + "mongodb-server-host-1":"localhost:27019" + } + } +] \ No newline at end of file diff --git a/jnosql/jnosql-artemis/src/main/resources/logback.xml b/jnosql/jnosql-artemis/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/jnosql/jnosql-artemis/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/jnosql/jnosql-artemis/src/main/webapp/WEB-INF/jnosql.json b/jnosql/jnosql-artemis/src/main/webapp/WEB-INF/jnosql.json new file mode 100644 index 0000000000..b8e26cf54a --- /dev/null +++ b/jnosql/jnosql-artemis/src/main/webapp/WEB-INF/jnosql.json @@ -0,0 +1,10 @@ +[ + { + "description": "The mongodb document configuration", + "name": "document", + "provider": "org.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration", + "settings": { + "mongodb-server-host-1":"localhost:27019" + } + } +] \ No newline at end of file diff --git a/jnosql/jnosql-diana/pom.xml b/jnosql/jnosql-diana/pom.xml new file mode 100644 index 0000000000..767defb2a8 --- /dev/null +++ b/jnosql/jnosql-diana/pom.xml @@ -0,0 +1,93 @@ + + + 4.0.0 + + + com.baeldung.jnosql + jnosql + 1.0-SNAPSHOT + + + jnosql-diana + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + document + + java + + + com.baeldung.jnosql.diana.document.DocumentApp + + + + column + + java + + + com.baeldung.jnosql.diana.column.ColumnFamilyApp + + + + key + + java + + + com.baeldung.jnosql.diana.key.KeyValueApp + + + + + + + + + + + + org.jnosql.diana + diana-document + 0.0.5 + + + org.jnosql.diana + mongodb-driver + 0.0.5 + + + + + org.jnosql.diana + diana-column + 0.0.5 + + + org.jnosql.diana + cassandra-driver + 0.0.5 + + + + + org.jnosql.diana + diana-key-value + 0.0.5 + + + org.jnosql.diana + hazelcast-driver + 0.0.5 + + + + \ No newline at end of file diff --git a/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/column/ColumnFamilyApp.java b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/column/ColumnFamilyApp.java new file mode 100644 index 0000000000..5b65f9ad73 --- /dev/null +++ b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/column/ColumnFamilyApp.java @@ -0,0 +1,32 @@ +package com.baeldung.jnosql.diana.column; + +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +import org.jnosql.diana.api.column.*; +import org.jnosql.diana.cassandra.column.CassandraConfiguration; + +public class ColumnFamilyApp { + + private static final String KEY_SPACE = "myKeySpace"; + private static final String COLUMN_FAMILY = "books"; + + public static void main(String... args) throws Exception { + + EmbeddedCassandraServerHelper.startEmbeddedCassandra(); + + ColumnConfiguration configuration = new CassandraConfiguration(); + try(ColumnFamilyManagerFactory entityManagerFactory = configuration.get()) { + ColumnFamilyManager entityManager = entityManagerFactory.get(KEY_SPACE); + ColumnEntity columnEntity = ColumnEntity.of(COLUMN_FAMILY); + Column key = Columns.of("id", 10L); + Column name = Columns.of("name", "JNoSQL in Acion"); + columnEntity.add(key); + columnEntity.add(name); + ColumnEntity saved = entityManager.insert(columnEntity); + System.out.println(saved); + } + + EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); + EmbeddedCassandraServerHelper.stopEmbeddedCassandra(); + } + +} diff --git a/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/DocumentApp.java b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/DocumentApp.java new file mode 100644 index 0000000000..258c812a31 --- /dev/null +++ b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/DocumentApp.java @@ -0,0 +1,67 @@ +package com.baeldung.jnosql.diana.document; + +import org.jnosql.diana.api.Settings; +import org.jnosql.diana.api.document.*; +import org.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.delete; +import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.select; + +public class DocumentApp { + + private static final String DB_NAME = "my-db"; + private static final String DOCUMENT_COLLECTION = "books"; + + public static final String KEY_NAME = "_id"; + + DocumentConfiguration configuration = new MongoDBDocumentConfiguration(); + + public static void main(String... args) throws Exception { + MongoDbInit.startMongoDb(); + + DocumentApp app = new DocumentApp(); + app.process(); + + MongoDbInit.stopMongoDb(); + } + + public void process() { + + Map map = new HashMap<>(); + map.put("mongodb-server-host-1", "localhost:27017"); + + try (DocumentCollectionManagerFactory managerFactory = configuration.get(Settings.of(map)); + DocumentCollectionManager manager = managerFactory.get(DB_NAME);) { + + DocumentEntity documentEntity = DocumentEntity.of(DOCUMENT_COLLECTION); + documentEntity.add(Document.of(KEY_NAME, "100")); + documentEntity.add(Document.of("name", "JNoSQL in Action")); + documentEntity.add(Document.of("pages", 620)); + + //CREATE + DocumentEntity saved = manager.insert(documentEntity); + + //READ + DocumentQuery query = select().from(DOCUMENT_COLLECTION).where(KEY_NAME).eq("100").build(); + List entities = manager.select(query); + System.out.println(entities.get(0)); + + //UPDATE + saved.add(Document.of("author", "baeldung")); + DocumentEntity updated = manager.update(saved); + System.out.println(updated); + + //DELETE + DocumentDeleteQuery deleteQuery = delete().from(DOCUMENT_COLLECTION).where(KEY_NAME).eq("100").build(); + manager.delete(deleteQuery); + + List documentEntityList = manager.select(select().from(DOCUMENT_COLLECTION).build()); + System.out.println(documentEntityList); + } + } + +} diff --git a/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/MongoDbInit.java b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/MongoDbInit.java new file mode 100644 index 0000000000..19bb347581 --- /dev/null +++ b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/MongoDbInit.java @@ -0,0 +1,32 @@ +package com.baeldung.jnosql.diana.document; + +import de.flapdoodle.embed.mongo.MongodExecutable; +import de.flapdoodle.embed.mongo.MongodProcess; +import de.flapdoodle.embed.mongo.MongodStarter; +import de.flapdoodle.embed.mongo.config.MongodConfigBuilder; +import de.flapdoodle.embed.mongo.config.Net; +import de.flapdoodle.embed.mongo.distribution.Version; +import de.flapdoodle.embed.process.runtime.Network; + +import java.io.IOException; + +public abstract class MongoDbInit { + + private static final MongodStarter starter = MongodStarter.getDefaultInstance(); + private static MongodExecutable _mongodExe; + private static MongodProcess _mongod; + + public static void startMongoDb() throws IOException { + _mongodExe = starter.prepare(new MongodConfigBuilder() + .version(Version.Main.DEVELOPMENT) + .net(new Net("localhost", 27017, Network.localhostIsIPv6())) + .build()); + _mongod = _mongodExe.start(); + } + + public static void stopMongoDb(){ + _mongod.stop(); + _mongodExe.stop(); + } + +} \ No newline at end of file diff --git a/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/Book.java b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/Book.java new file mode 100644 index 0000000000..afa20e66b1 --- /dev/null +++ b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/Book.java @@ -0,0 +1,63 @@ +package com.baeldung.jnosql.diana.key; + +import java.io.Serializable; + +public class Book implements Serializable { + + private String isbn; + private String name; + private String author; + private int pages; + + public Book() { + } + + public Book(String isbn, String name, String author, int pages) { + this.isbn = isbn; + this.name = name; + this.author = author; + this.pages = pages; + } + + public String getIsbn() { + return isbn; + } + + public void setIsbn(String isbn) { + this.isbn = isbn; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public int getPages() { + return pages; + } + + public void setPages(int pages) { + this.pages = pages; + } + + @Override + public String toString() { + return "Book{" + + "isbn='" + isbn + '\'' + + ", name='" + name + '\'' + + ", author='" + author + '\'' + + ", pages=" + pages + + '}'; + } +} diff --git a/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/KeyValueApp.java b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/KeyValueApp.java new file mode 100644 index 0000000000..ab51bfa4fc --- /dev/null +++ b/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/KeyValueApp.java @@ -0,0 +1,33 @@ +package com.baeldung.jnosql.diana.key; + +import com.hazelcast.core.Hazelcast; +import org.jnosql.diana.api.Value; +import org.jnosql.diana.api.key.BucketManager; +import org.jnosql.diana.api.key.BucketManagerFactory; +import org.jnosql.diana.api.key.KeyValueConfiguration; +import org.jnosql.diana.api.key.KeyValueEntity; +import org.jnosql.diana.hazelcast.key.HazelcastKeyValueConfiguration; + +import java.util.Optional; + +public class KeyValueApp { + + private static final String BUCKET_NAME = "books"; + + public static void main(String... args) throws Exception { + KeyValueConfiguration configuration = new HazelcastKeyValueConfiguration(); + try (BucketManagerFactory managerFactory = configuration.get()) { + BucketManager manager = managerFactory.getBucketManager(BUCKET_NAME); + + Book book = new Book("12345", "JNoSQL in Action", "baeldung", 420); + KeyValueEntity keyValueEntity = KeyValueEntity.of(book.getIsbn(), book); + manager.put(keyValueEntity); + + Optional optionalValue = manager.get("12345"); + Value value = optionalValue.get(); + Book savedBook = value.get(Book.class); + System.out.println(savedBook); + } + Hazelcast.shutdownAll(); + } +} diff --git a/jnosql/jnosql-diana/src/main/resources/diana-cassandra.properties b/jnosql/jnosql-diana/src/main/resources/diana-cassandra.properties new file mode 100644 index 0000000000..5d7d840d65 --- /dev/null +++ b/jnosql/jnosql-diana/src/main/resources/diana-cassandra.properties @@ -0,0 +1,5 @@ +cassandra-host-1=localhost +cassandra-port=9142 +#cassandra-threads-number=2 +cassandra-query-1=CREATE KEYSPACE IF NOT EXISTS myKeySpace WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3}; +cassandra-query-2=CREATE COLUMNFAMILY IF NOT EXISTS myKeySpace.books (id bigint PRIMARY KEY, name text); diff --git a/jnosql/jnosql-diana/src/main/resources/diana-hazelcast.properties b/jnosql/jnosql-diana/src/main/resources/diana-hazelcast.properties new file mode 100644 index 0000000000..010b4a6e47 --- /dev/null +++ b/jnosql/jnosql-diana/src/main/resources/diana-hazelcast.properties @@ -0,0 +1 @@ +hazelcast-instanceName=hazelcast \ No newline at end of file diff --git a/jnosql/jnosql-diana/src/main/resources/diana-mongodb.properties b/jnosql/jnosql-diana/src/main/resources/diana-mongodb.properties new file mode 100644 index 0000000000..5b425bd7bf --- /dev/null +++ b/jnosql/jnosql-diana/src/main/resources/diana-mongodb.properties @@ -0,0 +1,2 @@ +#Define Host and Port +mongodb-server-host-1=localhost:27017 diff --git a/jnosql/jnosql-diana/src/main/resources/logback.xml b/jnosql/jnosql-diana/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/jnosql/jnosql-diana/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/jnosql/pom.xml b/jnosql/pom.xml new file mode 100644 index 0000000000..c87ad3cf4b --- /dev/null +++ b/jnosql/pom.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + + com.baeldung.jnosql + jnosql + 1.0-SNAPSHOT + pom + + + 1.8 + 1.8 + 0.0.5 + + + + jnosql-diana + jnosql-artemis + + + diff --git a/jooby/pom.xml b/jooby/pom.xml index 8d4ed186aa..2867b7f4b6 100644 --- a/jooby/pom.xml +++ b/jooby/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 jooby com.baeldung.jooby @@ -10,7 +10,7 @@ org.jooby modules - ${jooby.modules.version} + 1.1.3 @@ -44,6 +44,7 @@ org.apache.maven.plugins maven-shade-plugin + ${maven-shade-plugin.version} @@ -52,7 +53,8 @@ 1.1.3 com.baeldung.jooby.App 1.1.3 - 1.1.3 + + 2.4.3 diff --git a/jooby/src/main/resources/logback.xml b/jooby/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/jooby/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/jpa-storedprocedure/README.md b/jpa-storedprocedure/README.md deleted file mode 100644 index 39d6784d8b..0000000000 --- a/jpa-storedprocedure/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) diff --git a/jpa-storedprocedure/pom.xml b/jpa-storedprocedure/pom.xml deleted file mode 100644 index e6cfe153d5..0000000000 --- a/jpa-storedprocedure/pom.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - 4.0.0 - com.baeldung - jpa-storedprocedure - 1.0 - jar - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - JpaStoredProcedure - - - maven-assembly-plugin - - ${project.basedir} - - - jar-with-dependencies - - - - - - - - - - javax - javaee-api - ${jee.version} - provided - - - org.hibernate - hibernate-entitymanager - ${hibernate.version} - - - - mysql - mysql-connector-java - ${mysql.version} - - - commons-io - commons-io - ${commons-io.version} - - - - - 7.0 - 5.2.5.Final - 6.0.5 - 2.5 - - - \ No newline at end of file diff --git a/jpa-storedprocedure/src/main/resources/META-INF/persistence.xml b/jpa-storedprocedure/src/main/resources/META-INF/persistence.xml deleted file mode 100644 index 4c443cb7cf..0000000000 --- a/jpa-storedprocedure/src/main/resources/META-INF/persistence.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.model.Car - - - - - - - - - - \ No newline at end of file diff --git a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java deleted file mode 100644 index c0fb5485aa..0000000000 --- a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.baeldung.jpa.storedprocedure; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.ParameterMode; -import javax.persistence.Persistence; -import javax.persistence.StoredProcedureQuery; - -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.baeldung.jpa.model.Car; - -public class StoredProcedureIntegrationTest { - - private static EntityManagerFactory factory = null; - private static EntityManager entityManager = null; - - @BeforeClass - public static void init() { - factory = Persistence.createEntityManagerFactory("jpa-db"); - entityManager = factory.createEntityManager(); - } - - @Before - public void setup() { - } - - @Test - public void createCarTest() { - final EntityTransaction transaction = entityManager.getTransaction(); - try { - transaction.begin(); - final Car car = new Car("Fiat Marea", 2015); - entityManager.persist(car); - transaction.commit(); - } catch (final Exception e) { - System.out.println(e.getCause()); - if (transaction.isActive()) { - transaction.rollback(); - } - } - } - - @Test - public void findCarsByYearNamedProcedure() { - final StoredProcedureQuery findByYearProcedure = entityManager.createNamedStoredProcedureQuery("findByYearProcedure"); - final StoredProcedureQuery storedProcedure = findByYearProcedure.setParameter("p_year", 2015); - storedProcedure.getResultList() - .forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); - } - - @Test - public void findCarsByYearNoNamed() { - final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class) - .registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN) - .setParameter(1, 2015); - storedProcedure.getResultList() - .forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); - } - - @AfterClass - public static void destroy() { - - if (entityManager != null) { - entityManager.close(); - } - if (factory != null) { - factory.close(); - } - } -} diff --git a/jsf/pom.xml b/jsf/pom.xml index e58e61de7f..2ac8a9f7c2 100644 --- a/jsf/pom.xml +++ b/jsf/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 jsf 0.1-SNAPSHOT @@ -36,11 +36,6 @@ ${jstl.version} - - org.springframework - spring-web - ${org.springframework.version} - org.springframework spring-webmvc @@ -73,13 +68,13 @@ provided ${javax.servlet.version} - - + + - org.primefaces - primefaces - 6.2 - + org.primefaces + primefaces + ${primefaces.version} + @@ -111,5 +106,7 @@ 2.6 + 6.2 + \ No newline at end of file diff --git a/jsf/src/main/resources/logback.xml b/jsf/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/jsf/src/main/resources/logback.xml +++ b/jsf/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/json-path/README.md b/json-path/README.md index 3563dcf880..7a84ea7bde 100644 --- a/json-path/README.md +++ b/json-path/README.md @@ -1,3 +1,4 @@ ## Relevant articles: - [Introduction to JsonPath](http://www.baeldung.com/guide-to-jayway-jsonpath) +- [Count with JsonPath](http://www.baeldung.com/jsonpath-count) diff --git a/json-path/pom.xml b/json-path/pom.xml index 18bbb5af33..0f8ff3bd31 100644 --- a/json-path/pom.xml +++ b/json-path/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 json-path 0.0.1-SNAPSHOT diff --git a/json-path/src/main/resources/logback.xml b/json-path/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/json-path/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/json-path/src/main/resources/online_store.json b/json-path/src/main/resources/online_store.json new file mode 100644 index 0000000000..c0ddf274d8 --- /dev/null +++ b/json-path/src/main/resources/online_store.json @@ -0,0 +1,23 @@ +{ + "items":{ + "book":[ + { + "author":"Arthur Conan Doyle", + "title":"Sherlock Holmes", + "price":8.99 + }, + { + "author":"J. R. R. Tolkien", + "title":"The Lord of the Rings", + "isbn":"0-395-19395-8", + "price":22.99 + } + ], + "bicycle":{ + "color":"red", + "price":19.95 + } + }, + "url":"mystore.com", + "owner":"baeldung" +} \ No newline at end of file diff --git a/json-path/src/test/java/com/baeldung/jsonpath/introduction/JsonPathUnitTest.java b/json-path/src/test/java/com/baeldung/jsonpath/introduction/JsonPathUnitTest.java new file mode 100644 index 0000000000..3408629a6d --- /dev/null +++ b/json-path/src/test/java/com/baeldung/jsonpath/introduction/JsonPathUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.jsonpath.introduction; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.Map; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.jayway.jsonpath.JsonPath; + +import net.minidev.json.JSONArray; + +public class JsonPathUnitTest { + + private static String json; + private static File jsonFile = new File("src/main/resources/online_store.json"); + + private static String readFile(File file, Charset charset) throws IOException { + return new String(Files.readAllBytes(file.toPath()), charset); + } + + @BeforeClass + public static void init() throws IOException { + json = readFile(jsonFile, StandardCharsets.UTF_8); + } + + @Test + public void shouldMatchCountOfObjects() { + Map objectMap = JsonPath.read(json, "$"); + assertEquals(3, objectMap.keySet() + .size()); + } + + @Test + public void shouldMatchCountOfArrays() { + JSONArray jsonArray = JsonPath.read(json, "$.items.book[*]"); + assertEquals(2, jsonArray.size()); + } + +} diff --git a/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceIntegrationTest.java b/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceIntegrationTest.java new file mode 100644 index 0000000000..85e5d3e826 --- /dev/null +++ b/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceIntegrationTest.java @@ -0,0 +1,101 @@ +package com.baeldung.jsonpath.introduction; + +import com.jayway.jsonpath.Configuration; +import com.jayway.jsonpath.DocumentContext; +import com.jayway.jsonpath.JsonPath; +import com.jayway.jsonpath.Option; +import org.junit.Test; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Scanner; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +public class ServiceIntegrationTest { + private InputStream jsonInputStream = this.getClass() + .getClassLoader() + .getResourceAsStream("intro_service.json"); + private String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z") + .next(); + + @Test + public void givenId_whenRequestingRecordData_thenSucceed() { + Object dataObject = JsonPath.parse(jsonString) + .read("$[?(@.id == 2)]"); + String dataString = dataObject.toString(); + + assertThat(dataString, containsString("2")); + assertThat(dataString, containsString("Quantum of Solace")); + assertThat(dataString, containsString("Twenty-second James Bond movie")); + } + + @Test + public void givenStarring_whenRequestingMovieTitle_thenSucceed() { + List> dataList = JsonPath.parse(jsonString) + .read("$[?('Eva Green' in @['starring'])]"); + String title = (String) dataList.get(0) + .get("title"); + + assertEquals("Casino Royale", title); + } + + @Test + public void givenCompleteStructure_whenCalculatingTotalRevenue_thenSucceed() { + DocumentContext context = JsonPath.parse(jsonString); + int length = context.read("$.length()"); + long revenue = 0; + for (int i = 0; i < length; i++) { + revenue += context.read("$[" + i + "]['box office']", Long.class); + } + + assertEquals(594275385L + 591692078L + 1110526981L + 879376275L, revenue); + } + + @Test + public void givenStructure_whenRequestingHighestRevenueMovieTitle_thenSucceed() { + DocumentContext context = JsonPath.parse(jsonString); + List revenueList = context.read("$[*]['box office']"); + Integer[] revenueArray = revenueList.toArray(new Integer[0]); + Arrays.sort(revenueArray); + + int highestRevenue = revenueArray[revenueArray.length - 1]; + Configuration pathConfiguration = Configuration.builder() + .options(Option.AS_PATH_LIST) + .build(); + List pathList = JsonPath.using(pathConfiguration) + .parse(jsonString) + .read("$[?(@['box office'] == " + highestRevenue + ")]"); + + Map dataRecord = context.read(pathList.get(0)); + String title = dataRecord.get("title"); + + assertEquals("Skyfall", title); + } + + @Test + public void givenDirector_whenRequestingLatestMovieTitle_thenSucceed() { + DocumentContext context = JsonPath.parse(jsonString); + List> dataList = context.read("$[?(@.director == 'Sam Mendes')]"); + + List dateList = new ArrayList<>(); + for (Map item : dataList) { + Object date = item.get("release date"); + dateList.add(date); + } + Long[] dateArray = dateList.toArray(new Long[0]); + Arrays.sort(dateArray); + + long latestTime = dateArray[dateArray.length - 1]; + List> finalDataList = context.read("$[?(@['director'] == 'Sam Mendes' && @['release date'] == " + latestTime + ")]"); + String title = (String) finalDataList.get(0) + .get("title"); + + assertEquals("Spectre", title); + } +} \ No newline at end of file diff --git a/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceTest.java b/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceTest.java deleted file mode 100644 index 067e5cf8ce..0000000000 --- a/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceTest.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.baeldung.jsonpath.introduction; - -import com.jayway.jsonpath.Configuration; -import com.jayway.jsonpath.DocumentContext; -import com.jayway.jsonpath.JsonPath; -import com.jayway.jsonpath.Option; -import org.junit.Test; - -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Scanner; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -public class ServiceTest { - private InputStream jsonInputStream = this.getClass() - .getClassLoader() - .getResourceAsStream("intro_service.json"); - private String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z") - .next(); - - @Test - public void givenId_whenRequestingRecordData_thenSucceed() { - Object dataObject = JsonPath.parse(jsonString) - .read("$[?(@.id == 2)]"); - String dataString = dataObject.toString(); - - assertThat(dataString, containsString("2")); - assertThat(dataString, containsString("Quantum of Solace")); - assertThat(dataString, containsString("Twenty-second James Bond movie")); - } - - @Test - public void givenStarring_whenRequestingMovieTitle_thenSucceed() { - List> dataList = JsonPath.parse(jsonString) - .read("$[?('Eva Green' in @['starring'])]"); - String title = (String) dataList.get(0) - .get("title"); - - assertEquals("Casino Royale", title); - } - - @Test - public void givenCompleteStructure_whenCalculatingTotalRevenue_thenSucceed() { - DocumentContext context = JsonPath.parse(jsonString); - int length = context.read("$.length()"); - long revenue = 0; - for (int i = 0; i < length; i++) { - revenue += context.read("$[" + i + "]['box office']", Long.class); - } - - assertEquals(594275385L + 591692078L + 1110526981L + 879376275L, revenue); - } - - @Test - public void givenStructure_whenRequestingHighestRevenueMovieTitle_thenSucceed() { - DocumentContext context = JsonPath.parse(jsonString); - List revenueList = context.read("$[*]['box office']"); - Integer[] revenueArray = revenueList.toArray(new Integer[0]); - Arrays.sort(revenueArray); - - int highestRevenue = revenueArray[revenueArray.length - 1]; - Configuration pathConfiguration = Configuration.builder() - .options(Option.AS_PATH_LIST) - .build(); - List pathList = JsonPath.using(pathConfiguration) - .parse(jsonString) - .read("$[?(@['box office'] == " + highestRevenue + ")]"); - - Map dataRecord = context.read(pathList.get(0)); - String title = dataRecord.get("title"); - - assertEquals("Skyfall", title); - } - - @Test - public void givenDirector_whenRequestingLatestMovieTitle_thenSucceed() { - DocumentContext context = JsonPath.parse(jsonString); - List> dataList = context.read("$[?(@.director == 'Sam Mendes')]"); - - List dateList = new ArrayList<>(); - for (Map item : dataList) { - Object date = item.get("release date"); - dateList.add(date); - } - Long[] dateArray = dateList.toArray(new Long[0]); - Arrays.sort(dateArray); - - long latestTime = dateArray[dateArray.length - 1]; - List> finalDataList = context.read("$[?(@['director'] == 'Sam Mendes' && @['release date'] == " + latestTime + ")]"); - String title = (String) finalDataList.get(0) - .get("title"); - - assertEquals("Spectre", title); - } -} \ No newline at end of file diff --git a/json-path/src/test/resources/logback.xml b/json-path/src/test/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/json-path/src/test/resources/logback.xml +++ b/json-path/src/test/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/json/README.md b/json/README.md index 1317ada8be..e0679bc60b 100644 --- a/json/README.md +++ b/json/README.md @@ -8,3 +8,5 @@ - [Introduction to JSONForms](http://www.baeldung.com/introduction-to-jsonforms) - [Introduction to JsonPath](http://www.baeldung.com/guide-to-jayway-jsonpath) - [Introduction to JSON-Java (org.json)](http://www.baeldung.com/java-org-json) +- [Overview of JSON Pointer](https://www.baeldung.com/json-pointer) +- [Introduction to the JSON Binding API (JSR 367) in Java](http://www.baeldung.com/java-json-binding-api) \ No newline at end of file diff --git a/json/pom.xml b/json/pom.xml index 5d05b73489..b688baec06 100644 --- a/json/pom.xml +++ b/json/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung json @@ -32,12 +32,44 @@ org.json json 20171018 + + + javax.json.bind + javax.json.bind-api + ${jsonb-api.version} + + + junit + junit + 4.12 + test + + + + org.glassfish + javax.json + 1.1.2 + + + org.eclipse + yasson + ${yasson.version} + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + test 1.4.1 1.2.21 + 1.0 + 4.1 + 1.0.1 diff --git a/jsonb/src/main/java/com/baeldung/adapter/PersonAdapter.java b/json/src/main/java/com/baeldung/adapter/PersonAdapter.java similarity index 100% rename from jsonb/src/main/java/com/baeldung/adapter/PersonAdapter.java rename to json/src/main/java/com/baeldung/adapter/PersonAdapter.java diff --git a/jsonb/src/main/java/com/baeldung/jsonb/Person.java b/json/src/main/java/com/baeldung/jsonb/Person.java similarity index 100% rename from jsonb/src/main/java/com/baeldung/jsonb/Person.java rename to json/src/main/java/com/baeldung/jsonb/Person.java diff --git a/json/src/main/java/com/baeldung/jsonpointer/JsonPointerCrud.java b/json/src/main/java/com/baeldung/jsonpointer/JsonPointerCrud.java new file mode 100644 index 0000000000..4398aa7867 --- /dev/null +++ b/json/src/main/java/com/baeldung/jsonpointer/JsonPointerCrud.java @@ -0,0 +1,95 @@ +package com.baeldung.jsonpointer; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Paths; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonPointer; +import javax.json.JsonReader; +import javax.json.JsonString; +import javax.json.JsonStructure; + +public class JsonPointerCrud { + + private JsonStructure jsonStructure = null; + + public JsonPointerCrud(String fileName) throws IOException { + + try (JsonReader reader = Json.createReader(Files.newBufferedReader(Paths.get(fileName)))) { + jsonStructure = reader.read(); + } catch (FileNotFoundException e) { + System.out.println("Error to open json file: " + e.getMessage()); + } + + } + + public JsonPointerCrud(InputStream stream) { + + JsonReader reader = Json.createReader(stream); + jsonStructure = reader.read(); + reader.close(); + + } + + public JsonStructure insert(String key, String value) { + + JsonPointer jsonPointer = Json.createPointer("/" + key); + JsonString jsonValue = Json.createValue(value); + jsonStructure = jsonPointer.add(jsonStructure, jsonValue); + + return jsonStructure; + + } + + public JsonStructure update(String key, String newValue) { + + JsonPointer jsonPointer = Json.createPointer("/" + key); + JsonString jsonNewValue = Json.createValue(newValue); + jsonStructure = jsonPointer.replace(jsonStructure, jsonNewValue); + + return jsonStructure; + } + + public JsonStructure delete(String key) { + + JsonPointer jsonPointer = Json.createPointer("/" + key); + jsonPointer.getValue(jsonStructure); + jsonStructure = jsonPointer.remove(jsonStructure); + + return jsonStructure; + + } + + public String fetchValueFromKey(String key) { + JsonPointer jsonPointer = Json.createPointer("/" + key); + JsonString jsonString = (JsonString) jsonPointer.getValue(jsonStructure); + + return jsonString.getString(); + } + + public String fetchListValues(String key) { + JsonPointer jsonPointer = Json.createPointer("/" + key); + JsonObject jsonObject = (JsonObject) jsonPointer.getValue(jsonStructure); + + return jsonObject.toString(); + } + + public String fetchFullJSON() { + JsonPointer jsonPointer = Json.createPointer(""); + JsonObject jsonObject = (JsonObject) jsonPointer.getValue(jsonStructure); + + return jsonObject.toString(); + + } + + public boolean check(String key) { + JsonPointer jsonPointer = Json.createPointer("/" + key); + boolean found = jsonPointer.containsValue(jsonStructure); + + return found; + } +} diff --git a/json/src/main/resources/logback.xml b/json/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/json/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/json/src/test/java/com/baeldung/jsonb/JsonbUnitTest.java b/json/src/test/java/com/baeldung/jsonb/JsonbUnitTest.java new file mode 100644 index 0000000000..f258700c6b --- /dev/null +++ b/json/src/test/java/com/baeldung/jsonb/JsonbUnitTest.java @@ -0,0 +1,189 @@ +package com.baeldung.jsonb; + +import static org.junit.Assert.assertTrue; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.json.bind.Jsonb; +import javax.json.bind.JsonbBuilder; +import javax.json.bind.JsonbConfig; +import javax.json.bind.config.PropertyNamingStrategy; +import javax.json.bind.config.PropertyOrderStrategy; + +import org.apache.commons.collections4.ListUtils; +import org.junit.Test; + +import com.baeldung.adapter.PersonAdapter; +import com.baeldung.jsonb.Person; + +public class JsonbUnitTest { + + @Test + public void givenPersonList_whenSerializeWithJsonb_thenGetPersonJsonArray() { + Jsonb jsonb = JsonbBuilder.create(); + // @formatter:off + List personList = Arrays.asList( + new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), + new Person(2, "Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)), + new Person(3, "Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), + new Person(4, "Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500))); + // @formatter:on + String jsonArrayPerson = jsonb.toJson(personList); + // @formatter:off + String jsonExpected = "[" + + "{\"email\":\"jhon@test.com\"," + + "\"id\":1,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1000.0\"}," + + "{\"email\":\"jhon1@test.com\"," + + "\"id\":2,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1500.0\"},{\"email\":null," + + "\"id\":3,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1000.0\"}," + + "{\"email\":\"tom@test.com\"," + + "\"id\":4,\"person-name\":\"Tom\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1500.0\"}" + + "]"; + // @formatter:on + assertTrue(jsonArrayPerson.equals(jsonExpected)); + } + + @Test + public void givenPersonJsonArray_whenDeserializeWithJsonb_thenGetPersonList() { + Jsonb jsonb = JsonbBuilder.create(); + // @formatter:off + String personJsonArray = + "[" + + "{\"email\":\"jhon@test.com\"," + + "\"id\":1,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1000.0\"}," + + "{\"email\":\"jhon1@test.com\"," + + "\"id\":2,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1500.0\"},{\"email\":null," + + "\"id\":3,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1000.0\"}," + + "{\"email\":\"tom@test.com\"," + + "\"id\":4,\"person-name\":\"Tom\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1500.0\"}" + + "]"; + // @formatter:on + @SuppressWarnings("serial") + List personList = jsonb.fromJson(personJsonArray, new ArrayList() { + }.getClass() + .getGenericSuperclass()); + // @formatter:off + List personListExpected = Arrays.asList( + new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), + new Person(2, "Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)), + new Person(3, "Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), + new Person(4, "Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500))); + // @formatter:on + assertTrue(ListUtils.isEqualList(personList, personListExpected)); + } + + @Test + public void givenPersonObject_whenNamingStrategy_thenGetCustomPersonJson() { + JsonbConfig config = new JsonbConfig().withPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE_WITH_UNDERSCORES); + Jsonb jsonb = JsonbBuilder.create(config); + Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); + String jsonPerson = jsonb.toJson(person); + // @formatter:off + String jsonExpected = + "{\"email\":\"jhon@test.com\"," + + "\"id\":1," + + "\"person-name\":\"Jhon\"," + + "\"registered_date\":\"07-09-2019\"," + + "\"salary\":\"1000.0\"}"; + // @formatter:on + assertTrue(jsonExpected.equals(jsonPerson)); + } + + @Test + public void givenPersonObject_whenWithPropertyOrderStrategy_thenGetReversePersonJson() { + JsonbConfig config = new JsonbConfig().withPropertyOrderStrategy(PropertyOrderStrategy.REVERSE); + Jsonb jsonb = JsonbBuilder.create(config); + Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); + String jsonPerson = jsonb.toJson(person); + // @formatter:off + String jsonExpected = + "{\"salary\":\"1000.0\","+ + "\"registeredDate\":\"07-09-2019\"," + + "\"person-name\":\"Jhon\"," + + "\"id\":1," + + "\"email\":\"jhon@test.com\"}"; + // @formatter:on + assertTrue(jsonExpected.equals(jsonPerson)); + } + + @Test + public void givenPersonObject_whenSerializeWithJsonb_thenGetPersonJson() { + Jsonb jsonb = JsonbBuilder.create(); + Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); + String jsonPerson = jsonb.toJson(person); + // @formatter:off + String jsonExpected = + "{\"email\":\"jhon@test.com\"," + + "\"id\":1," + + "\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"07-09-2019\"," + + "\"salary\":\"1000.0\"}"; + // @formatter:on + assertTrue(jsonExpected.equals(jsonPerson)); + } + + @Test + public void givenPersonJson_whenDeserializeWithJsonb_thenGetPersonObject() { + Jsonb jsonb = JsonbBuilder.create(); + Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0)); + // @formatter:off + String jsonPerson = + "{\"email\":\"jhon@test.com\"," + + "\"id\":1," + + "\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"07-09-2019\"," + + "\"salary\":\"1000.0\"}"; + // @formatter:on + assertTrue(jsonb.fromJson(jsonPerson, Person.class) + .equals(person)); + } + + @Test + public void givenPersonObject_whenSerializeWithAdapter_thenGetPersonJson() { + JsonbConfig config = new JsonbConfig().withAdapters(new PersonAdapter()); + Jsonb jsonb = JsonbBuilder.create(config); + Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));// new Person(1, "Jhon"); + String jsonPerson = jsonb.toJson(person); + // @formatter:off + String jsonExpected = + "{\"id\":1," + + "\"name\":\"Jhon\"}"; + // @formatter:on + assertTrue(jsonExpected.equals(jsonPerson)); + } + + @Test + public void givenPersonJson_whenDeserializeWithAdapter_thenGetPersonObject() { + JsonbConfig config = new JsonbConfig().withAdapters(new PersonAdapter()); + Jsonb jsonb = JsonbBuilder.create(config); + Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));// new Person(1, "Jhon"); + // @formatter:off + String jsonPerson = + "{\"id\":1," + + "\"name\":\"Jhon\"}"; + // @formatter:on + assertTrue(jsonb.fromJson(jsonPerson, Person.class) + .equals(person)); + } + +} diff --git a/json/src/test/java/com/baeldung/jsonpointer/JsonPointerCrudUnitTest.java b/json/src/test/java/com/baeldung/jsonpointer/JsonPointerCrudUnitTest.java new file mode 100644 index 0000000000..c1553db325 --- /dev/null +++ b/json/src/test/java/com/baeldung/jsonpointer/JsonPointerCrudUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.jsonpointer; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class JsonPointerCrudUnitTest { + + @Test + public void testJsonPointerCrudForAddress() { + + JsonPointerCrud jsonPointerCrud = new JsonPointerCrud(JsonPointerCrudUnitTest.class.getResourceAsStream("/address.json")); + + assertFalse(jsonPointerCrud.check("city")); + + // insert a value + jsonPointerCrud.insert("city", "Rio de Janeiro"); + + assertTrue(jsonPointerCrud.check("city")); + + // fetch full json + String fullJSON = jsonPointerCrud.fetchFullJSON(); + + assertTrue(fullJSON.contains("name")); + + assertTrue(fullJSON.contains("city")); + + // fetch value + String cityName = jsonPointerCrud.fetchValueFromKey("city"); + + assertEquals(cityName, "Rio de Janeiro"); + + // update value + jsonPointerCrud.update("city", "Sao Paulo"); + + // fetch value + cityName = jsonPointerCrud.fetchValueFromKey("city"); + + assertEquals(cityName, "Sao Paulo"); + + // delete + jsonPointerCrud.delete("city"); + + assertFalse(jsonPointerCrud.check("city")); + + } + + @Test + public void testJsonPointerCrudForBooks() { + + JsonPointerCrud jsonPointerCrud = new JsonPointerCrud(JsonPointerCrudUnitTest.class.getResourceAsStream("/books.json")); + + // fetch value + String book = jsonPointerCrud.fetchListValues("books/1"); + + assertEquals(book, "{\"title\":\"Title 2\",\"author\":\"John Doe\"}"); + + } +} \ No newline at end of file diff --git a/json/src/test/resources/address.json b/json/src/test/resources/address.json new file mode 100644 index 0000000000..599fcae12b --- /dev/null +++ b/json/src/test/resources/address.json @@ -0,0 +1,4 @@ +{ + "name": "Customer 01", + "street name": "Street 01" +} \ No newline at end of file diff --git a/json/src/test/resources/books.json b/json/src/test/resources/books.json new file mode 100644 index 0000000000..0defc3de98 --- /dev/null +++ b/json/src/test/resources/books.json @@ -0,0 +1,7 @@ +{ + "library": "My Personal Library", + "books": [ + { "title":"Title 1", "author":"Jane Doe" }, + { "title":"Title 2", "author":"John Doe" } + ] +} \ No newline at end of file diff --git a/jsonb/README.md b/jsonb/README.md deleted file mode 100644 index 9293a44808..0000000000 --- a/jsonb/README.md +++ /dev/null @@ -1,4 +0,0 @@ -## JSON B - -## Relevant articles: -- [Introduction to the JSON Binding API (JSR 367) in Java](http://www.baeldung.com/java-json-binding-api) diff --git a/jsonb/pom.xml b/jsonb/pom.xml deleted file mode 100644 index c4ef1efed6..0000000000 --- a/jsonb/pom.xml +++ /dev/null @@ -1,104 +0,0 @@ - - - 4.0.0 - com.baeldung - json-b - 0.0.1-SNAPSHOT - jar - json-b - json-b sample project - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - javax.json.bind - javax.json.bind-api - ${jsonb-api.version} - - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - test - - - - org.junit.jupiter - junit-jupiter-api - ${junit.jupiter.version} - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - test - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - - - - - - yasson - - true - - - - - org.eclipse - yasson - ${yasson.version} - - - org.glassfish - javax.json - ${javax.json.version} - - - - - johnzon - - - - org.apache.geronimo.specs - geronimo-json_1.1_spec - ${geronimo-json_1.1_spec.version} - - - org.apache.johnzon - johnzon-jsonb - ${johnzon.version} - - - - - - - UTF-8 - UTF-8 - 1.8 - 1.8 - 1.0.0 - 5.0.0 - 1.0 - 1.1.3 - 1.0 - 1.0.1 - 1.1.2 - 4.1 - - - \ No newline at end of file diff --git a/jsonb/src/test/java/com/baeldung/jsonb/JsonbTest.java b/jsonb/src/test/java/com/baeldung/jsonb/JsonbTest.java deleted file mode 100644 index 67beda77e1..0000000000 --- a/jsonb/src/test/java/com/baeldung/jsonb/JsonbTest.java +++ /dev/null @@ -1,188 +0,0 @@ -package com.baeldung.jsonb; - -import static org.junit.Assert.assertTrue; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.json.bind.Jsonb; -import javax.json.bind.JsonbBuilder; -import javax.json.bind.JsonbConfig; -import javax.json.bind.config.PropertyNamingStrategy; -import javax.json.bind.config.PropertyOrderStrategy; - -import org.apache.commons.collections4.ListUtils; -import org.junit.Test; - -import com.baeldung.adapter.PersonAdapter; - -public class JsonbTest { - - @Test - public void givenPersonList_whenSerializeWithJsonb_thenGetPersonJsonArray() { - Jsonb jsonb = JsonbBuilder.create(); - // @formatter:off - List personList = Arrays.asList( - new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), - new Person(2, "Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)), - new Person(3, "Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), - new Person(4, "Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500))); - // @formatter:on - String jsonArrayPerson = jsonb.toJson(personList); - // @formatter:off - String jsonExpected = "[" + - "{\"email\":\"jhon@test.com\"," + - "\"id\":1,\"person-name\":\"Jhon\"," + - "\"registeredDate\":\"09-09-2019\"," + - "\"salary\":\"1000.0\"}," + - "{\"email\":\"jhon1@test.com\"," + - "\"id\":2,\"person-name\":\"Jhon\"," + - "\"registeredDate\":\"09-09-2019\"," + - "\"salary\":\"1500.0\"},{\"email\":null," + - "\"id\":3,\"person-name\":\"Jhon\"," + - "\"registeredDate\":\"09-09-2019\"," + - "\"salary\":\"1000.0\"}," + - "{\"email\":\"tom@test.com\"," + - "\"id\":4,\"person-name\":\"Tom\"," + - "\"registeredDate\":\"09-09-2019\"," + - "\"salary\":\"1500.0\"}" - + "]"; - // @formatter:on - assertTrue(jsonArrayPerson.equals(jsonExpected)); - } - - @Test - public void givenPersonJsonArray_whenDeserializeWithJsonb_thenGetPersonList() { - Jsonb jsonb = JsonbBuilder.create(); - // @formatter:off - String personJsonArray = - "[" + - "{\"email\":\"jhon@test.com\"," + - "\"id\":1,\"person-name\":\"Jhon\"," + - "\"registeredDate\":\"09-09-2019\"," + - "\"salary\":\"1000.0\"}," + - "{\"email\":\"jhon1@test.com\"," + - "\"id\":2,\"person-name\":\"Jhon\"," + - "\"registeredDate\":\"09-09-2019\"," + - "\"salary\":\"1500.0\"},{\"email\":null," + - "\"id\":3,\"person-name\":\"Jhon\"," + - "\"registeredDate\":\"09-09-2019\"," + - "\"salary\":\"1000.0\"}," + - "{\"email\":\"tom@test.com\"," + - "\"id\":4,\"person-name\":\"Tom\"," + - "\"registeredDate\":\"09-09-2019\"," + - "\"salary\":\"1500.0\"}" - + "]"; - // @formatter:on - @SuppressWarnings("serial") - List personList = jsonb.fromJson(personJsonArray, new ArrayList() { - }.getClass() - .getGenericSuperclass()); - // @formatter:off - List personListExpected = Arrays.asList( - new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), - new Person(2, "Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)), - new Person(3, "Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), - new Person(4, "Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500))); - // @formatter:on - assertTrue(ListUtils.isEqualList(personList, personListExpected)); - } - - @Test - public void givenPersonObject_whenNamingStrategy_thenGetCustomPersonJson() { - JsonbConfig config = new JsonbConfig().withPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE_WITH_UNDERSCORES); - Jsonb jsonb = JsonbBuilder.create(config); - Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); - String jsonPerson = jsonb.toJson(person); - // @formatter:off - String jsonExpected = - "{\"email\":\"jhon@test.com\"," + - "\"id\":1," + - "\"person-name\":\"Jhon\"," + - "\"registered_date\":\"07-09-2019\"," + - "\"salary\":\"1000.0\"}"; - // @formatter:on - assertTrue(jsonExpected.equals(jsonPerson)); - } - - @Test - public void givenPersonObject_whenWithPropertyOrderStrategy_thenGetReversePersonJson() { - JsonbConfig config = new JsonbConfig().withPropertyOrderStrategy(PropertyOrderStrategy.REVERSE); - Jsonb jsonb = JsonbBuilder.create(config); - Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); - String jsonPerson = jsonb.toJson(person); - // @formatter:off - String jsonExpected = - "{\"salary\":\"1000.0\","+ - "\"registeredDate\":\"07-09-2019\"," + - "\"person-name\":\"Jhon\"," + - "\"id\":1," + - "\"email\":\"jhon@test.com\"}"; - // @formatter:on - assertTrue(jsonExpected.equals(jsonPerson)); - } - - @Test - public void givenPersonObject_whenSerializeWithJsonb_thenGetPersonJson() { - Jsonb jsonb = JsonbBuilder.create(); - Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); - String jsonPerson = jsonb.toJson(person); - // @formatter:off - String jsonExpected = - "{\"email\":\"jhon@test.com\"," + - "\"id\":1," + - "\"person-name\":\"Jhon\"," + - "\"registeredDate\":\"07-09-2019\"," + - "\"salary\":\"1000.0\"}"; - // @formatter:on - assertTrue(jsonExpected.equals(jsonPerson)); - } - - @Test - public void givenPersonJson_whenDeserializeWithJsonb_thenGetPersonObject() { - Jsonb jsonb = JsonbBuilder.create(); - Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0)); - // @formatter:off - String jsonPerson = - "{\"email\":\"jhon@test.com\"," + - "\"id\":1," + - "\"person-name\":\"Jhon\"," + - "\"registeredDate\":\"07-09-2019\"," + - "\"salary\":\"1000.0\"}"; - // @formatter:on - assertTrue(jsonb.fromJson(jsonPerson, Person.class) - .equals(person)); - } - - @Test - public void givenPersonObject_whenSerializeWithAdapter_thenGetPersonJson() { - JsonbConfig config = new JsonbConfig().withAdapters(new PersonAdapter()); - Jsonb jsonb = JsonbBuilder.create(config); - Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));// new Person(1, "Jhon"); - String jsonPerson = jsonb.toJson(person); - // @formatter:off - String jsonExpected = - "{\"id\":1," + - "\"name\":\"Jhon\"}"; - // @formatter:on - assertTrue(jsonExpected.equals(jsonPerson)); - } - - @Test - public void givenPersonJson_whenDeserializeWithAdapter_thenGetPersonObject() { - JsonbConfig config = new JsonbConfig().withAdapters(new PersonAdapter()); - Jsonb jsonb = JsonbBuilder.create(config); - Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));// new Person(1, "Jhon"); - // @formatter:off - String jsonPerson = - "{\"id\":1," + - "\"name\":\"Jhon\"}"; - // @formatter:on - assertTrue(jsonb.fromJson(jsonPerson, Person.class) - .equals(person)); - } - -} diff --git a/jsoup/pom.xml b/jsoup/pom.xml index a914b7c6ba..2704d7bc00 100644 --- a/jsoup/pom.xml +++ b/jsoup/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 jsoup jar diff --git a/jta/pom.xml b/jta/pom.xml new file mode 100644 index 0000000000..89bdccf25e --- /dev/null +++ b/jta/pom.xml @@ -0,0 +1,88 @@ + + + 4.0.0 + com.baeldung + jta-demo + 1.0-SNAPSHOT + jar + + JEE JTA demo + + + org.springframework.boot + spring-boot-starter-parent + 2.0.4.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-jta-bitronix + + + org.springframework.boot + spring-boot-starter-jdbc + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.hsqldb + hsqldb + 2.4.1 + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + + diff --git a/jta/src/main/java/com/baeldung/jtademo/JtaDemoApplication.java b/jta/src/main/java/com/baeldung/jtademo/JtaDemoApplication.java new file mode 100644 index 0000000000..4d8779efe5 --- /dev/null +++ b/jta/src/main/java/com/baeldung/jtademo/JtaDemoApplication.java @@ -0,0 +1,48 @@ +package com.baeldung.jtademo; + +import org.hsqldb.jdbc.pool.JDBCXADataSource; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.jta.bitronix.BitronixXADataSourceWrapper; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.sql.DataSource; + +@EnableAutoConfiguration +@EnableTransactionManagement +@Configuration +@ComponentScan +public class JtaDemoApplication { + + @Bean("dataSourceAccount") + public DataSource dataSource() throws Exception { + return createHsqlXADatasource("jdbc:hsqldb:mem:accountDb"); + } + + @Bean("dataSourceAudit") + public DataSource dataSourceAudit() throws Exception { + return createHsqlXADatasource("jdbc:hsqldb:mem:auditDb"); + } + + private DataSource createHsqlXADatasource(String connectionUrl) throws Exception { + JDBCXADataSource dataSource = new JDBCXADataSource(); + dataSource.setUrl(connectionUrl); + dataSource.setUser("sa"); + BitronixXADataSourceWrapper wrapper = new BitronixXADataSourceWrapper(); + return wrapper.wrapDataSource(dataSource); + } + + @Bean("jdbcTemplateAccount") + public JdbcTemplate jdbcTemplate(@Qualifier("dataSourceAccount") DataSource dataSource) { + return new JdbcTemplate(dataSource); + } + + @Bean("jdbcTemplateAudit") + public JdbcTemplate jdbcTemplateAudit(@Qualifier("dataSourceAudit") DataSource dataSource) { + return new JdbcTemplate(dataSource); + } +} diff --git a/jta/src/main/java/com/baeldung/jtademo/dto/TransferLog.java b/jta/src/main/java/com/baeldung/jtademo/dto/TransferLog.java new file mode 100644 index 0000000000..cc1474ce81 --- /dev/null +++ b/jta/src/main/java/com/baeldung/jtademo/dto/TransferLog.java @@ -0,0 +1,27 @@ +package com.baeldung.jtademo.dto; + +import java.math.BigDecimal; + +public class TransferLog { + private String fromAccountId; + private String toAccountId; + private BigDecimal amount; + + public TransferLog(String fromAccountId, String toAccountId, BigDecimal amount) { + this.fromAccountId = fromAccountId; + this.toAccountId = toAccountId; + this.amount = amount; + } + + public String getFromAccountId() { + return fromAccountId; + } + + public String getToAccountId() { + return toAccountId; + } + + public BigDecimal getAmount() { + return amount; + } +} diff --git a/jta/src/main/java/com/baeldung/jtademo/services/AuditService.java b/jta/src/main/java/com/baeldung/jtademo/services/AuditService.java new file mode 100644 index 0000000000..f6810e15c8 --- /dev/null +++ b/jta/src/main/java/com/baeldung/jtademo/services/AuditService.java @@ -0,0 +1,33 @@ +package com.baeldung.jtademo.services; + +import com.baeldung.jtademo.dto.TransferLog; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.ResultSetExtractor; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; + +@Service +public class AuditService { + + final JdbcTemplate jdbcTemplate; + + @Autowired + public AuditService(@Qualifier("jdbcTemplateAudit") JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + public void log(String fromAccount, String toAccount, BigDecimal amount) { + jdbcTemplate.update("insert into AUDIT_LOG(FROM_ACCOUNT, TO_ACCOUNT, AMOUNT) values ?,?,?", fromAccount, toAccount, amount); + } + + public TransferLog lastTransferLog() { + return jdbcTemplate.query("select FROM_ACCOUNT,TO_ACCOUNT,AMOUNT from AUDIT_LOG order by ID desc", (ResultSetExtractor) (rs) -> { + if (!rs.next()) + return null; + return new TransferLog(rs.getString(1), rs.getString(2), BigDecimal.valueOf(rs.getDouble(3))); + }); + } +} diff --git a/jta/src/main/java/com/baeldung/jtademo/services/BankAccountService.java b/jta/src/main/java/com/baeldung/jtademo/services/BankAccountService.java new file mode 100644 index 0000000000..0c881edbaa --- /dev/null +++ b/jta/src/main/java/com/baeldung/jtademo/services/BankAccountService.java @@ -0,0 +1,32 @@ +package com.baeldung.jtademo.services; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.ResultSetExtractor; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; + +@Service +public class BankAccountService { + + final JdbcTemplate jdbcTemplate; + + @Autowired + public BankAccountService(@Qualifier("jdbcTemplateAccount") JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + public void transfer(String fromAccountId, String toAccountId, BigDecimal amount) { + jdbcTemplate.update("update ACCOUNT set BALANCE=BALANCE-? where ID=?", amount, fromAccountId); + jdbcTemplate.update("update ACCOUNT set BALANCE=BALANCE+? where ID=?", amount, toAccountId); + } + + public BigDecimal balanceOf(String accountId) { + return jdbcTemplate.query("select BALANCE from ACCOUNT where ID=?", new Object[] { accountId }, (ResultSetExtractor) (rs) -> { + rs.next(); + return new BigDecimal(rs.getDouble(1)); + }); + } +} diff --git a/jta/src/main/java/com/baeldung/jtademo/services/TellerService.java b/jta/src/main/java/com/baeldung/jtademo/services/TellerService.java new file mode 100644 index 0000000000..d3bd80a2ee --- /dev/null +++ b/jta/src/main/java/com/baeldung/jtademo/services/TellerService.java @@ -0,0 +1,45 @@ +package com.baeldung.jtademo.services; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.transaction.Transactional; +import javax.transaction.UserTransaction; +import java.math.BigDecimal; + +@Service +public class TellerService { + private final BankAccountService bankAccountService; + private final AuditService auditService; + private final UserTransaction userTransaction; + + @Autowired + public TellerService(BankAccountService bankAccountService, AuditService auditService, UserTransaction userTransaction) { + this.bankAccountService = bankAccountService; + this.auditService = auditService; + this.userTransaction = userTransaction; + } + + @Transactional + public void executeTransfer(String fromAccontId, String toAccountId, BigDecimal amount) { + bankAccountService.transfer(fromAccontId, toAccountId, amount); + auditService.log(fromAccontId, toAccountId, amount); + BigDecimal balance = bankAccountService.balanceOf(fromAccontId); + if (balance.compareTo(BigDecimal.ZERO) <= 0) { + throw new RuntimeException("Insufficient fund."); + } + } + + public void executeTransferProgrammaticTx(String fromAccontId, String toAccountId, BigDecimal amount) throws Exception { + userTransaction.begin(); + bankAccountService.transfer(fromAccontId, toAccountId, amount); + auditService.log(fromAccontId, toAccountId, amount); + BigDecimal balance = bankAccountService.balanceOf(fromAccontId); + if (balance.compareTo(BigDecimal.ZERO) <= 0) { + userTransaction.rollback(); + throw new RuntimeException("Insufficient fund."); + } else { + userTransaction.commit(); + } + } +} diff --git a/jta/src/main/java/com/baeldung/jtademo/services/TestHelper.java b/jta/src/main/java/com/baeldung/jtademo/services/TestHelper.java new file mode 100644 index 0000000000..c1e8e355ec --- /dev/null +++ b/jta/src/main/java/com/baeldung/jtademo/services/TestHelper.java @@ -0,0 +1,43 @@ +package com.baeldung.jtademo.services; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.init.ScriptUtils; +import org.springframework.stereotype.Component; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; + +@Component +public class TestHelper { + final JdbcTemplate jdbcTemplateAccount; + + final JdbcTemplate jdbcTemplateAudit; + + @Autowired + public TestHelper(@Qualifier("jdbcTemplateAccount") JdbcTemplate jdbcTemplateAccount, @Qualifier("jdbcTemplateAudit") JdbcTemplate jdbcTemplateAudit) { + this.jdbcTemplateAccount = jdbcTemplateAccount; + this.jdbcTemplateAudit = jdbcTemplateAudit; + } + + public void runAccountDbInit() throws SQLException { + runScript("account.sql", jdbcTemplateAccount.getDataSource()); + } + + public void runAuditDbInit() throws SQLException { + runScript("audit.sql", jdbcTemplateAudit.getDataSource()); + } + + private void runScript(String scriptName, DataSource dataSouorce) throws SQLException { + DefaultResourceLoader resourceLoader = new DefaultResourceLoader(); + Resource script = resourceLoader.getResource(scriptName); + try (Connection con = dataSouorce.getConnection()) { + ScriptUtils.executeSqlScript(con, script); + } + } + +} diff --git a/jta/src/main/resources/account.sql b/jta/src/main/resources/account.sql new file mode 100644 index 0000000000..af14f89b01 --- /dev/null +++ b/jta/src/main/resources/account.sql @@ -0,0 +1,9 @@ +DROP SCHEMA PUBLIC CASCADE; + +create table ACCOUNT ( +ID char(8) PRIMARY KEY, +BALANCE NUMERIC(28,10) +); + +insert into ACCOUNT(ID, BALANCE) values ('a0000001', 1000); +insert into ACCOUNT(ID, BALANCE) values ('a0000002', 2000); \ No newline at end of file diff --git a/jta/src/main/resources/application.properties b/jta/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/jta/src/main/resources/audit.sql b/jta/src/main/resources/audit.sql new file mode 100644 index 0000000000..aa5845f402 --- /dev/null +++ b/jta/src/main/resources/audit.sql @@ -0,0 +1,8 @@ +DROP SCHEMA PUBLIC CASCADE; + +create table AUDIT_LOG ( +ID INTEGER IDENTITY PRIMARY KEY, +FROM_ACCOUNT varchar(8), +TO_ACCOUNT varchar(8), +AMOUNT numeric(28,10) +); \ No newline at end of file diff --git a/jta/src/test/java/com/baeldung/jtademo/JtaDemoUnitTest.java b/jta/src/test/java/com/baeldung/jtademo/JtaDemoUnitTest.java new file mode 100644 index 0000000000..3f6004262b --- /dev/null +++ b/jta/src/test/java/com/baeldung/jtademo/JtaDemoUnitTest.java @@ -0,0 +1,91 @@ +package com.baeldung.jtademo; + +import com.baeldung.jtademo.dto.TransferLog; +import com.baeldung.jtademo.services.AuditService; +import com.baeldung.jtademo.services.BankAccountService; +import com.baeldung.jtademo.services.TellerService; +import com.baeldung.jtademo.services.TestHelper; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.math.BigDecimal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = JtaDemoApplication.class) +public class JtaDemoUnitTest { + @Autowired + TestHelper testHelper; + + @Autowired + TellerService tellerService; + + @Autowired + BankAccountService accountService; + + @Autowired + AuditService auditService; + + @Before + public void beforeTest() throws Exception { + testHelper.runAuditDbInit(); + testHelper.runAccountDbInit(); + } + + @Test + public void givenAnnotationTx_whenNoException_thenAllCommitted() throws Exception { + tellerService.executeTransfer("a0000001", "a0000002", BigDecimal.valueOf(500)); + + assertThat(accountService.balanceOf("a0000001")).isEqualByComparingTo(BigDecimal.valueOf(500)); + assertThat(accountService.balanceOf("a0000002")).isEqualByComparingTo(BigDecimal.valueOf(2500)); + + TransferLog lastTransferLog = auditService.lastTransferLog(); + assertThat(lastTransferLog).isNotNull(); + assertThat(lastTransferLog.getFromAccountId()).isEqualTo("a0000001"); + assertThat(lastTransferLog.getToAccountId()).isEqualTo("a0000002"); + assertThat(lastTransferLog.getAmount()).isEqualByComparingTo(BigDecimal.valueOf(500)); + } + + @Test + public void givenAnnotationTx_whenException_thenAllRolledBack() throws Exception { + assertThatThrownBy(() -> { + tellerService.executeTransfer("a0000002", "a0000001", BigDecimal.valueOf(100000)); + }).hasMessage("Insufficient fund."); + + assertThat(accountService.balanceOf("a0000001")).isEqualByComparingTo(BigDecimal.valueOf(1000)); + assertThat(accountService.balanceOf("a0000002")).isEqualByComparingTo(BigDecimal.valueOf(2000)); + assertThat(auditService.lastTransferLog()).isNull(); + } + + @Test + public void givenProgrammaticTx_whenCommit_thenAllCommitted() throws Exception { + tellerService.executeTransferProgrammaticTx("a0000001", "a0000002", BigDecimal.valueOf(500)); + + BigDecimal result = accountService.balanceOf("a0000001"); + assertThat(accountService.balanceOf("a0000001")).isEqualByComparingTo(BigDecimal.valueOf(500)); + assertThat(accountService.balanceOf("a0000002")).isEqualByComparingTo(BigDecimal.valueOf(2500)); + + TransferLog lastTransferLog = auditService.lastTransferLog(); + assertThat(lastTransferLog).isNotNull(); + assertThat(lastTransferLog.getFromAccountId()).isEqualTo("a0000001"); + assertThat(lastTransferLog.getToAccountId()).isEqualTo("a0000002"); + assertThat(lastTransferLog.getAmount()).isEqualByComparingTo(BigDecimal.valueOf(500)); + } + + @Test + public void givenProgrammaticTx_whenRollback_thenAllRolledBack() throws Exception { + assertThatThrownBy(() -> { + tellerService.executeTransferProgrammaticTx("a0000002", "a0000001", BigDecimal.valueOf(100000)); + }).hasMessage("Insufficient fund."); + + assertThat(accountService.balanceOf("a0000001")).isEqualByComparingTo(BigDecimal.valueOf(1000)); + assertThat(accountService.balanceOf("a0000002")).isEqualByComparingTo(BigDecimal.valueOf(2000)); + assertThat(auditService.lastTransferLog()).isNull(); + } +} diff --git a/junit5/README.md b/junit5/README.md deleted file mode 100644 index fb1685fdd5..0000000000 --- a/junit5/README.md +++ /dev/null @@ -1,2 +0,0 @@ -## Relevant articles: -- [The Order of Tests in JUnit](http://www.baeldung.com/junit-5-test-order) diff --git a/junit5/src/main/java/com/baeldung/junit5/DefaultOrderOfExecutionTest.java b/junit5/src/main/java/com/baeldung/junit5/DefaultOrderOfExecutionTest.java deleted file mode 100644 index 15b07ee03a..0000000000 --- a/junit5/src/main/java/com/baeldung/junit5/DefaultOrderOfExecutionTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.junit5; - -import static org.junit.Assert.assertEquals; - -import org.junit.AfterClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; - -@FixMethodOrder(MethodSorters.DEFAULT) -public class DefaultOrderOfExecutionTest { - private static StringBuilder output = new StringBuilder(""); - - @Test - public void secondTest() { - output.append("b"); - } - - @Test - public void thirdTest() { - output.append("c"); - } - - @Test - public void firstTest() { - output.append("a"); - } - - @AfterClass - public static void assertOutput() { - assertEquals(output.toString(), "cab"); - } -} diff --git a/junit5/src/main/java/com/baeldung/junit5/JVMOrderOfExecutionTest.java b/junit5/src/main/java/com/baeldung/junit5/JVMOrderOfExecutionTest.java deleted file mode 100644 index 189efc8945..0000000000 --- a/junit5/src/main/java/com/baeldung/junit5/JVMOrderOfExecutionTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.junit5; - -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; - -@FixMethodOrder(MethodSorters.JVM) -public class JVMOrderOfExecutionTest { - - private static StringBuilder output = new StringBuilder(""); - - @Test - public void secondTest() { - output.append("b"); - } - - @Test - public void thirdTest() { - output.append("c"); - } - - @Test - public void firstTest() { - output.append("a"); - } -} \ No newline at end of file diff --git a/junit5/src/main/java/com/baeldung/junit5/NameAscendingOrderOfExecutionTest.java b/junit5/src/main/java/com/baeldung/junit5/NameAscendingOrderOfExecutionTest.java deleted file mode 100644 index 88de057fc8..0000000000 --- a/junit5/src/main/java/com/baeldung/junit5/NameAscendingOrderOfExecutionTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.junit5; - -import static org.junit.Assert.assertEquals; - -import org.junit.AfterClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class NameAscendingOrderOfExecutionTest { - private static StringBuilder output = new StringBuilder(""); - - @Test - public void secondTest() { - output.append("b"); - } - - @Test - public void thirdTest() { - output.append("c"); - } - - @Test - public void firstTest() { - output.append("a"); - } - - @AfterClass - public static void assertOutput() { - assertEquals(output.toString(), "abc"); - } -} diff --git a/jws/pom.xml b/jws/pom.xml index 4199021060..1970ab9921 100644 --- a/jws/pom.xml +++ b/jws/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.example jws @@ -13,20 +13,23 @@ 1.0.0-SNAPSHOT + + + OpenNMS Repository + http://repo.opennms.org/maven2/ + + + - javax.jnlp + javax.samples.jnlp jnlp-servlet ${jnlp-servlet.version} - system - ${project.basedir}/java-core-samples-lib/jnlp-servlet.jar - javax.jnlp - jardiff - ${jardiff.version} - system - ${project.basedir}/java-core-samples-lib/jardiff.jar + javax.samples.jnlp + jnlp-jardiff + ${jnlp-jardiff.version} @@ -81,8 +84,8 @@ 3.0.2 3.0.0 - 7.0 - 7.0 + 1.6.0 + 1.6.0 diff --git a/jws/src/main/resources/logback.xml b/jws/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/jws/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/kotlin-js/.gitignore b/kotlin-js/.gitignore new file mode 100644 index 0000000000..1db5e66882 --- /dev/null +++ b/kotlin-js/.gitignore @@ -0,0 +1,13 @@ +/bin/ + +#ignore gradle +.gradle/ + + +#ignore build and generated files +build/ +node/ + +#ignore installed node modules and package lock file +node_modules/ +package-lock.json diff --git a/kotlin-js/README.md b/kotlin-js/README.md new file mode 100644 index 0000000000..445ad6da9a --- /dev/null +++ b/kotlin-js/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Kotlin and Javascript](http://www.baeldung.com/kotlin-javascript) diff --git a/kotlin-js/build.gradle b/kotlin-js/build.gradle new file mode 100755 index 0000000000..9efef0f475 --- /dev/null +++ b/kotlin-js/build.gradle @@ -0,0 +1,27 @@ +buildscript { + ext.kotlin_version = '1.2.41' + repositories { + mavenCentral() + } + dependencies { + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +group 'com.baeldung' +version '1.0-SNAPSHOT' +apply plugin: 'kotlin2js' + +repositories { + mavenCentral() +} + +dependencies { + compile "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version" + testCompile "org.jetbrains.kotlin:kotlin-test-js:$kotlin_version" +} + +compileKotlin2Js.kotlinOptions { + moduleKind = "commonjs" + outputFile = "node/crypto.js" +} diff --git a/kotlin-js/gradle/wrapper/gradle-wrapper.jar b/kotlin-js/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..01b8bf6b1f Binary files /dev/null and b/kotlin-js/gradle/wrapper/gradle-wrapper.jar differ diff --git a/kotlin-js/gradle/wrapper/gradle-wrapper.properties b/kotlin-js/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..933b6473ce --- /dev/null +++ b/kotlin-js/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip diff --git a/kotlin-js/gradlew b/kotlin-js/gradlew new file mode 100755 index 0000000000..cccdd3d517 --- /dev/null +++ b/kotlin-js/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# 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 + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# 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 +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +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" -a "$nonstop" = "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 + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/kotlin-js/gradlew.bat b/kotlin-js/gradlew.bat new file mode 100755 index 0000000000..e95643d6a2 --- /dev/null +++ b/kotlin-js/gradlew.bat @@ -0,0 +1,84 @@ +@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 + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@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= + +@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 + +: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=%* + +: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/kotlin-js/package.json b/kotlin-js/package.json new file mode 100755 index 0000000000..c75313e3ff --- /dev/null +++ b/kotlin-js/package.json @@ -0,0 +1,17 @@ +{ + "name": "kotlin-node.js", + "version": "1.0.0", + "description": "Example of using NodeJS in Kotlin", + "main": "crypto.js", + "dependencies": { + "express": "^4.15.2", + "fs": "0.0.1-security", + "kotlin": "^1.1.0", + "node.js": "0.0.0", + "request": "^2.85.0" + }, + "devDependencies": {}, + "scripts": { + "start": "node node/crypto.js" + } +} diff --git a/kotlin-js/settings.gradle b/kotlin-js/settings.gradle new file mode 100755 index 0000000000..64767a30c5 --- /dev/null +++ b/kotlin-js/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'KotlinNode' diff --git a/kotlin-js/src/main/kotlin/com/baeldung/kotlinjs/CryptoRate.kt b/kotlin-js/src/main/kotlin/com/baeldung/kotlinjs/CryptoRate.kt new file mode 100755 index 0000000000..92ef4a7356 --- /dev/null +++ b/kotlin-js/src/main/kotlin/com/baeldung/kotlinjs/CryptoRate.kt @@ -0,0 +1,27 @@ +package com.baeldung.kotlinjs + +external fun require(module: String): dynamic + +data class CryptoCurrency(var name: String, var price: Float) + +fun main(args: Array) { + println("Crypto Currency price API!") + val express = require("express") + val app = express() + + app.get("/crypto", { _, res -> + res.send(generateCryptoRates()) + }) + + app.listen(3000, { + println("Listening on port 3000") + }) +} +fun generateCryptoRates(): Array{ + val cryptoCurrency = arrayOf( + CryptoCurrency("Bitcoin", 90000F), + CryptoCurrency("ETH",1000F), + CryptoCurrency("TRX",10F) + ); + return cryptoCurrency +} \ No newline at end of file diff --git a/kotlin-js/src/main/resources/logback.xml b/kotlin-js/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/kotlin-js/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/kotlin-libraries/.gitignore b/kotlin-libraries/.gitignore new file mode 100644 index 0000000000..0c017e8f8c --- /dev/null +++ b/kotlin-libraries/.gitignore @@ -0,0 +1,14 @@ +/bin/ + +#ignore gradle +.gradle/ + + +#ignore build and generated files +build/ +node/ +out/ + +#ignore installed node modules and package lock file +node_modules/ +package-lock.json diff --git a/kotlin-libraries/README.md b/kotlin-libraries/README.md new file mode 100644 index 0000000000..ce30c71792 --- /dev/null +++ b/kotlin-libraries/README.md @@ -0,0 +1,10 @@ +## Relevant articles: + +- [Kotlin with Mockito](http://www.baeldung.com/kotlin-mockito) +- [HTTP Requests with Kotlin and khttp](http://www.baeldung.com/kotlin-khttp) +- [Kotlin Dependency Injection with Kodein](http://www.baeldung.com/kotlin-kodein-dependency-injection) +- [Writing Specifications with Kotlin and Spek](http://www.baeldung.com/kotlin-spek) +- [Processing JSON with Kotlin and Klaxson](http://www.baeldung.com/kotlin-json-klaxson) +- [Kotlin with Ktor](http://www.baeldung.com/kotlin-ktor) +- [Idiomatic Logging in Kotlin](http://www.baeldung.com/kotlin-logging) +- [Guide to the Kotlin Exposed Framework](https://www.baeldung.com/kotlin-exposed-persistence) \ No newline at end of file diff --git a/kotlin-libraries/build.gradle b/kotlin-libraries/build.gradle new file mode 100644 index 0000000000..b244df34b0 --- /dev/null +++ b/kotlin-libraries/build.gradle @@ -0,0 +1,57 @@ + + +group 'com.baeldung.ktor' +version '1.0-SNAPSHOT' + + +buildscript { + ext.kotlin_version = '1.2.41' + ext.ktor_version = '0.9.2' + + repositories { + mavenCentral() + } + dependencies { + + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +apply plugin: 'java' +apply plugin: 'kotlin' +apply plugin: 'application' + +mainClassName = 'APIServer.kt' + +sourceCompatibility = 1.8 +compileKotlin { kotlinOptions.jvmTarget = "1.8" } +compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } + +kotlin { experimental { coroutines "enable" } } + +repositories { + mavenCentral() + jcenter() + maven { url "https://dl.bintray.com/kotlin/ktor" } +} +sourceSets { + main{ + kotlin{ + srcDirs 'com/baeldung/ktor' + } + } + +} + +dependencies { + compile "io.ktor:ktor-server-netty:$ktor_version" + compile "ch.qos.logback:logback-classic:1.2.1" + compile "io.ktor:ktor-gson:$ktor_version" + testCompile group: 'junit', name: 'junit', version: '4.12' + implementation 'com.beust:klaxon:3.0.1' + +} +task runServer(type: JavaExec) { + main = 'APIServer' + classpath = sourceSets.main.runtimeClasspath +} \ No newline at end of file diff --git a/kotlin-libraries/gradle/wrapper/gradle-wrapper.jar b/kotlin-libraries/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..01b8bf6b1f Binary files /dev/null and b/kotlin-libraries/gradle/wrapper/gradle-wrapper.jar differ diff --git a/kotlin-libraries/gradle/wrapper/gradle-wrapper.properties b/kotlin-libraries/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..933b6473ce --- /dev/null +++ b/kotlin-libraries/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip diff --git a/kotlin-libraries/gradlew b/kotlin-libraries/gradlew new file mode 100644 index 0000000000..cccdd3d517 --- /dev/null +++ b/kotlin-libraries/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# 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 + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# 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 +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +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" -a "$nonstop" = "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 + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/kotlin-libraries/gradlew.bat b/kotlin-libraries/gradlew.bat new file mode 100644 index 0000000000..f9553162f1 --- /dev/null +++ b/kotlin-libraries/gradlew.bat @@ -0,0 +1,84 @@ +@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 + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@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= + +@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 + +: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=%* + +: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/kotlin-libraries/pom.xml b/kotlin-libraries/pom.xml new file mode 100644 index 0000000000..c5b7fed951 --- /dev/null +++ b/kotlin-libraries/pom.xml @@ -0,0 +1,105 @@ + + + 4.0.0 + kotlin-libraries + jar + + + com.baeldung + parent-kotlin + 1.0.0-SNAPSHOT + ../parent-kotlin + + + + + exposed + exposed + https://dl.bintray.com/kotlin/exposed + + + + + + org.jetbrains.spek + spek-api + 1.1.5 + test + + + org.jetbrains.spek + spek-subject-extension + 1.1.5 + test + + + org.jetbrains.spek + spek-junit-platform-engine + 1.1.5 + test + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + khttp + khttp + ${khttp.version} + + + com.nhaarman + mockito-kotlin + ${mockito-kotlin.version} + test + + + com.github.salomonbrys.kodein + kodein + ${kodein.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + com.beust + klaxon + ${klaxon.version} + + + org.jetbrains.exposed + exposed + ${exposed.version} + + + com.h2database + h2 + ${h2database.version} + + + + + 1.5.0 + 4.1.0 + 3.0.4 + 0.1.0 + 3.6.1 + 1.1.1 + 5.2.0 + 3.10.0 + 1.4.197 + 0.10.4 + + + \ No newline at end of file diff --git a/kotlin-libraries/resources/logback.xml b/kotlin-libraries/resources/logback.xml new file mode 100644 index 0000000000..9452207268 --- /dev/null +++ b/kotlin-libraries/resources/logback.xml @@ -0,0 +1,11 @@ + + + + %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + \ No newline at end of file diff --git a/kotlin-libraries/settings.gradle b/kotlin-libraries/settings.gradle new file mode 100644 index 0000000000..c91c993971 --- /dev/null +++ b/kotlin-libraries/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'KtorWithKotlin' + diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/CustomProduct.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/CustomProduct.kt new file mode 100644 index 0000000000..cc46c65f96 --- /dev/null +++ b/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/CustomProduct.kt @@ -0,0 +1,9 @@ +package com.baeldung.klaxon + +import com.beust.klaxon.Json + +class CustomProduct( + @Json(name = "productName") + val name: String, + @Json(ignored = true) + val id: Int) \ No newline at end of file diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/Product.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/Product.kt new file mode 100644 index 0000000000..09bcbc8722 --- /dev/null +++ b/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/Product.kt @@ -0,0 +1,3 @@ +package com.baeldung.klaxon + +class Product(val name: String) \ No newline at end of file diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/ProductData.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/ProductData.kt new file mode 100644 index 0000000000..1f30f26ce9 --- /dev/null +++ b/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/ProductData.kt @@ -0,0 +1,3 @@ +package com.baeldung.klaxon + +data class ProductData(val name: String, val capacityInGb: Int) \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/Controller.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Controller.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/Controller.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Controller.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/Dao.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Dao.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/Dao.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Dao.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/JdbcDao.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/JdbcDao.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/JdbcDao.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/JdbcDao.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/MongoDao.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/MongoDao.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/MongoDao.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/MongoDao.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/Service.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Service.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/Service.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Service.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/mockito/BookService.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/mockito/BookService.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/mockito/BookService.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/mockito/BookService.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/mockito/LendBookManager.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/mockito/LendBookManager.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/mockito/LendBookManager.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/mockito/LendBookManager.kt diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/ktor/APIServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/ktor/APIServer.kt new file mode 100755 index 0000000000..a12182ccc8 --- /dev/null +++ b/kotlin-libraries/src/main/kotlin/com/baeldung/ktor/APIServer.kt @@ -0,0 +1,73 @@ +@file:JvmName("APIServer") + + +import io.ktor.application.call +import io.ktor.application.install +import io.ktor.features.CallLogging +import io.ktor.features.ContentNegotiation +import io.ktor.features.DefaultHeaders +import io.ktor.gson.gson +import io.ktor.request.path +import io.ktor.request.receive +import io.ktor.response.respond +import io.ktor.routing.* +import io.ktor.server.engine.embeddedServer +import io.ktor.server.netty.Netty +import org.slf4j.event.Level + +data class Author(val name: String, val website: String) +data class ToDo(var id: Int, val name: String, val description: String, val completed: Boolean) + +fun main(args: Array) { + + val toDoList = ArrayList(); + val jsonResponse = """{ + "id": 1, + "task": "Pay waterbill", + "description": "Pay water bill today", + }""" + + + embeddedServer(Netty, 8080) { + install(DefaultHeaders) { + header("X-Developer", "Baeldung") + } + install(CallLogging) { + level = Level.DEBUG + filter { call -> call.request.path().startsWith("/todo") } + filter { call -> call.request.path().startsWith("/author") } + } + install(ContentNegotiation) { + gson { + setPrettyPrinting() + } + } + routing() { + route("/todo") { + post { + var toDo = call.receive(); + toDo.id = toDoList.size; + toDoList.add(toDo); + call.respond("Added") + + } + delete("/{id}") { + call.respond(toDoList.removeAt(call.parameters["id"]!!.toInt())); + } + get("/{id}") { + + call.respond(toDoList[call.parameters["id"]!!.toInt()]); + } + get { + call.respond(toDoList); + } + } + get("/author"){ + call.respond(Author("Baeldung","baeldung.com")); + + } + + + } + }.start(wait = true) +} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/klaxon/KlaxonUnitTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/klaxon/KlaxonUnitTest.kt new file mode 100644 index 0000000000..2a7d44a163 --- /dev/null +++ b/kotlin-libraries/src/test/kotlin/com/baeldung/klaxon/KlaxonUnitTest.kt @@ -0,0 +1,163 @@ +package com.baeldung.klaxon + +import com.beust.klaxon.JsonArray +import com.beust.klaxon.JsonObject +import com.beust.klaxon.JsonReader +import com.beust.klaxon.Klaxon +import com.beust.klaxon.Parser +import com.beust.klaxon.PathMatcher +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.SoftAssertions.assertSoftly +import org.junit.Assert +import org.junit.jupiter.api.Test +import java.io.StringReader +import java.util.regex.Pattern + +class KlaxonUnitTest { + + @Test + fun giveProduct_whenSerialize_thenGetJsonString() { + val product = Product("HDD") + val result = Klaxon().toJsonString(product) + + assertThat(result).isEqualTo("""{"name" : "HDD"}""") + } + + @Test + fun giveJsonString_whenDeserialize_thenGetProduct() { + val result = Klaxon().parse(""" + { + "name" : "RAM" + } + """) + + assertThat(result?.name).isEqualTo("RAM") + } + + @Test + fun giveCustomProduct_whenSerialize_thenGetJsonString() { + val product = CustomProduct("HDD", 1) + val result = Klaxon().toJsonString(product) + + assertThat(result).isEqualTo("""{"productName" : "HDD"}""") + } + + @Test + fun giveJsonArray_whenStreaming_thenGetProductArray() { + val jsonArray = """ + [ + { "name" : "HDD", "capacityInGb" : 512 }, + { "name" : "RAM", "capacityInGb" : 16 } + ]""" + val expectedArray = arrayListOf(ProductData("HDD", 512), + ProductData("RAM", 16)) + val klaxon = Klaxon() + val productArray = arrayListOf() + JsonReader(StringReader(jsonArray)).use { reader -> + reader.beginArray { + while (reader.hasNext()) { + val product = klaxon.parse(reader) + productArray.add(product!!) + } + } + } + + assertThat(productArray).hasSize(2).isEqualTo(expectedArray) + } + + @Test + fun giveJsonString_whenParser_thenGetJsonObject() { + val jsonString = StringBuilder(""" + { + "name" : "HDD", + "capacityInGb" : 512, + "sizeInInch" : 2.5 + } + """) + val parser = Parser() + val json = parser.parse(jsonString) as JsonObject + + assertThat(json).hasSize(3).containsEntry("name", "HDD").containsEntry("capacityInGb", 512).containsEntry("sizeInInch", 2.5) + } + + @Suppress("UNCHECKED_CAST") + @Test + fun giveJsonStringArray_whenParser_thenGetJsonArray() { + val jsonString = StringBuilder(""" + [ + { "name" : "SDD" }, + { "madeIn" : "Taiwan" }, + { "warrantyInYears" : 5 } + ]""") + val parser = Parser() + val json = parser.parse(jsonString) as JsonArray + + assertSoftly({ softly -> + softly.assertThat(json).hasSize(3) + softly.assertThat(json[0]["name"]).isEqualTo("SDD") + softly.assertThat(json[1]["madeIn"]).isEqualTo("Taiwan") + softly.assertThat(json[2]["warrantyInYears"]).isEqualTo(5) + }) + } + + @Test + fun givenJsonString_whenStreaming_thenProcess() { + val jsonString = """ + { + "name" : "HDD", + "madeIn" : "Taiwan", + "warrantyInYears" : 5 + "hasStock" : true + "capacitiesInTb" : [ 1, 2 ], + "features" : { "cacheInMb" : 64, "speedInRpm" : 7200 } + }""" + + JsonReader(StringReader(jsonString)).use { reader -> + reader.beginObject { + while (reader.hasNext()) { + val readName = reader.nextName() + when (readName) { + "name" -> assertThat(reader.nextString()).isEqualTo("HDD") + "madeIn" -> assertThat(reader.nextString()).isEqualTo("Taiwan") + "warrantyInYears" -> assertThat(reader.nextInt()).isEqualTo(5) + "hasStock" -> assertThat(reader.nextBoolean()).isEqualTo(true) + "capacitiesInTb" -> assertThat(reader.nextArray()).contains(1, 2) + "features" -> assertThat(reader.nextObject()).containsEntry("cacheInMb", 64).containsEntry("speedInRpm", 7200) + else -> Assert.fail("Unexpected name: $readName") + } + } + } + } + + } + + @Test + fun givenDiskInventory_whenRegexMatches_thenGetTypes() { + val jsonString = """ + { + "inventory" : { + "disks" : [ + { + "type" : "HDD", + "sizeInGb" : 1000 + }, + { + "type" : "SDD", + "sizeInGb" : 512 + } + ] + } + }""" + val pathMatcher = object : PathMatcher { + override fun pathMatches(path: String) = Pattern.matches(".*inventory.*disks.*type.*", path) + + override fun onMatch(path: String, value: Any) { + when (path) { + "$.inventory.disks[0].type" -> assertThat(value).isEqualTo("HDD") + "$.inventory.disks[1].type" -> assertThat(value).isEqualTo("SDD") + } + } + } + Klaxon().pathMatcher(pathMatcher).parseJsonObject(StringReader(jsonString)) + } +} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/exposed/ExposedTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/exposed/ExposedTest.kt new file mode 100644 index 0000000000..29fa18ef7a --- /dev/null +++ b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/exposed/ExposedTest.kt @@ -0,0 +1,333 @@ +package com.baeldung.kotlin.exposed + +import org.jetbrains.exposed.dao.* +import org.jetbrains.exposed.sql.* +import org.jetbrains.exposed.sql.transactions.TransactionManager +import org.jetbrains.exposed.sql.transactions.transaction +import org.junit.Test +import java.sql.DriverManager +import kotlin.test.* + +class ExposedTest { + + @Test + fun whenH2Database_thenConnectionSuccessful() { + val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") + transaction { + assertEquals(1.4.toBigDecimal(), database.version) + assertEquals("h2", database.vendor) + } + } + + @Test + fun whenH2DatabaseWithCredentials_thenConnectionSuccessful() { + Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver", user = "myself", password = "secret") + } + + @Test + fun whenH2DatabaseWithManualConnection_thenConnectionSuccessful() { + var connected = false + Database.connect({ connected = true; DriverManager.getConnection("jdbc:h2:mem:test;MODE=MySQL") }) + assertEquals(false, connected) + transaction { + addLogger(StdOutSqlLogger) + assertEquals(false, connected) + SchemaUtils.create(Cities) + assertEquals(true, connected) + } + } + + @Test + fun whenManualCommit_thenOk() { + Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") + transaction { + assertTrue(this is Transaction) + commit() + commit() + commit() + } + } + + @Test + fun whenInsert_thenGeneratedKeys() { + Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") + transaction { + SchemaUtils.create(StarWarsFilms) + val id = StarWarsFilms.insertAndGetId { + it[name] = "The Last Jedi" + it[sequelId] = 8 + it[director] = "Rian Johnson" + } + assertEquals(1, id.value) + val insert = StarWarsFilms.insert { + it[name] = "The Force Awakens" + it[sequelId] = 7 + it[director] = "J.J. Abrams" + } + assertEquals(2, insert[StarWarsFilms.id]?.value) + val selectAll = StarWarsFilms.selectAll() + selectAll.forEach { + assertTrue { it[StarWarsFilms.sequelId] >= 7 } + } + StarWarsFilms.slice(StarWarsFilms.name, StarWarsFilms.director).selectAll() + .forEach { + assertTrue { it[StarWarsFilms.name].startsWith("The") } + } + val select = StarWarsFilms.select { (StarWarsFilms.director like "J.J.%") and (StarWarsFilms.sequelId eq 7) } + assertEquals(1, select.count()) + StarWarsFilms.update ({ StarWarsFilms.sequelId eq 8 }) { + it[name] = "Episode VIII – The Last Jedi" + with(SqlExpressionBuilder) { + it.update(StarWarsFilms.sequelId, StarWarsFilms.sequelId + 1) + } + } + } + } + + @Test + fun whenForeignKey_thenAutoJoin() { + Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") + transaction { + addLogger(StdOutSqlLogger) + SchemaUtils.create(StarWarsFilms, Players) + StarWarsFilms.insert { + it[name] = "The Last Jedi" + it[sequelId] = 8 + it[director] = "Rian Johnson" + } + StarWarsFilms.insert { + it[name] = "The Force Awakens" + it[sequelId] = 7 + it[director] = "J.J. Abrams" + } + Players.insert { + it[name] = "Mark Hamill" + it[sequelId] = 7 + } + Players.insert { + it[name] = "Mark Hamill" + it[sequelId] = 8 + } + val simpleInnerJoin = (StarWarsFilms innerJoin Players).selectAll() + assertEquals(2, simpleInnerJoin.count()) + simpleInnerJoin.forEach { + assertNotNull(it[StarWarsFilms.name]) + assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId]) + assertEquals("Mark Hamill", it[Players.name]) + } + val innerJoinWithCondition = (StarWarsFilms innerJoin Players) + .select { StarWarsFilms.sequelId eq Players.sequelId } + assertEquals(2, innerJoinWithCondition.count()) + innerJoinWithCondition.forEach { + assertNotNull(it[StarWarsFilms.name]) + assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId]) + assertEquals("Mark Hamill", it[Players.name]) + } + val complexInnerJoin = Join(StarWarsFilms, Players, joinType = JoinType.INNER, onColumn = StarWarsFilms.sequelId, otherColumn = Players.sequelId, additionalConstraint = { + StarWarsFilms.sequelId eq 8 + }).selectAll() + assertEquals(1, complexInnerJoin.count()) + complexInnerJoin.forEach { + assertNotNull(it[StarWarsFilms.name]) + assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId]) + assertEquals("Mark Hamill", it[Players.name]) + } + + } + } + + @Test + fun whenJoinWithAlias_thenFun() { + Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") + transaction { + addLogger(StdOutSqlLogger) + SchemaUtils.create(StarWarsFilms, Players) + StarWarsFilms.insert { + it[name] = "The Last Jedi" + it[sequelId] = 8 + it[director] = "Rian Johnson" + } + StarWarsFilms.insert { + it[name] = "The Force Awakens" + it[sequelId] = 7 + it[director] = "J.J. Abrams" + } + val sequel = StarWarsFilms.alias("sequel") + Join(StarWarsFilms, sequel, + additionalConstraint = { sequel[StarWarsFilms.sequelId] eq StarWarsFilms.sequelId + 1 }) + .selectAll().forEach { + assertEquals(it[sequel[StarWarsFilms.sequelId]], it[StarWarsFilms.sequelId] + 1) + } + } + } + + @Test + fun whenEntity_thenDAO() { + val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") + val connection = database.connector.invoke() //Keep a connection open so the DB is not destroyed after the first transaction + val inserted = transaction { + addLogger(StdOutSqlLogger) + SchemaUtils.create(StarWarsFilms, Players) + val theLastJedi = StarWarsFilm.new { + name = "The Last Jedi" + sequelId = 8 + director = "Rian Johnson" + } + assertFalse(TransactionManager.current().entityCache.inserts.isEmpty()) + assertEquals(1, theLastJedi.id.value) //Reading this causes a flush + assertTrue(TransactionManager.current().entityCache.inserts.isEmpty()) + theLastJedi + } + transaction { + val theLastJedi = StarWarsFilm.findById(1) + assertNotNull(theLastJedi) + assertEquals(inserted.id, theLastJedi?.id) + } + connection.close() + } + + @Test + fun whenManyToOne_thenNavigation() { + val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") + val connection = database.connector.invoke() + transaction { + addLogger(StdOutSqlLogger) + SchemaUtils.create(StarWarsFilms, Players, Users, UserRatings) + val theLastJedi = StarWarsFilm.new { + name = "The Last Jedi" + sequelId = 8 + director = "Rian Johnson" + } + val someUser = User.new { + name = "Some User" + } + val rating = UserRating.new { + value = 9 + user = someUser + film = theLastJedi + } + assertEquals(theLastJedi, rating.film) + assertEquals(someUser, rating.user) + assertEquals(rating, theLastJedi.ratings.first()) + } + transaction { + val theLastJedi = StarWarsFilm.find { StarWarsFilms.sequelId eq 8 }.first() + val ratings = UserRating.find { UserRatings.film eq theLastJedi.id } + assertEquals(1, ratings.count()) + val rating = ratings.first() + assertEquals("Some User", rating.user.name) + assertEquals(rating, theLastJedi.ratings.first()) + UserRating.new { + value = 8 + user = rating.user + film = theLastJedi + } + assertEquals(2, theLastJedi.ratings.count()) + } + connection.close() + } + + @Test + fun whenManyToMany_thenAssociation() { + val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") + val connection = database.connector.invoke() + val film = transaction { + SchemaUtils.create(StarWarsFilms) + StarWarsFilm.new { + name = "The Last Jedi" + sequelId = 8 + director = "Rian Johnson" + } + } + + val actor = transaction { + SchemaUtils.create(Actors) + Actor.new { + firstname = "Daisy" + lastname = "Ridley" + } + } + + transaction { + SchemaUtils.create(StarWarsFilmActors) + film.actors = SizedCollection(listOf(actor)) + } + connection.close() + } + +} + +object Cities: IntIdTable() { + val name = varchar("name", 50) +} + +object StarWarsFilms_Simple : Table() { + val id = integer("id").autoIncrement().primaryKey() + val sequelId = integer("sequel_id").uniqueIndex() + val name = varchar("name", 50) + val director = varchar("director", 50) +} + +object StarWarsFilms : IntIdTable() { + val sequelId = integer("sequel_id").uniqueIndex() + val name = varchar("name", 50) + val director = varchar("director", 50) +} + +object Players : Table() { + //val sequelId = integer("sequel_id").uniqueIndex().references(StarWarsFilms.sequelId) + val sequelId = reference("sequel_id", StarWarsFilms.sequelId).uniqueIndex() + //val filmId = reference("film_id", StarWarsFilms).nullable() + val name = varchar("name", 50) +} + +class StarWarsFilm(id: EntityID) : Entity(id) { + companion object : EntityClass(StarWarsFilms) + + var sequelId by StarWarsFilms.sequelId + var name by StarWarsFilms.name + var director by StarWarsFilms.director + var actors by Actor via StarWarsFilmActors + val ratings by UserRating referrersOn UserRatings.film +} + +object Users: IntIdTable() { + val name = varchar("name", 50) +} + +object UserRatings: IntIdTable() { + val value = long("value") + val film = reference("film", StarWarsFilms) + val user = reference("user", Users) +} + +class User(id: EntityID): IntEntity(id) { + companion object : IntEntityClass(Users) + + var name by Users.name +} + +class UserRating(id: EntityID): IntEntity(id) { + companion object : IntEntityClass(UserRatings) + + var value by UserRatings.value + var film by StarWarsFilm referencedOn UserRatings.film + var user by User referencedOn UserRatings.user +} + +object Actors: IntIdTable() { + val firstname = varchar("firstname", 50) + val lastname = varchar("lastname", 50) +} + +class Actor(id: EntityID): IntEntity(id) { + companion object : IntEntityClass(Actors) + + var firstname by Actors.firstname + var lastname by Actors.lastname +} + +object StarWarsFilmActors : Table() { + val starWarsFilm = reference("starWarsFilm", StarWarsFilms).primaryKey(0) + val actor = reference("actor", Actors).primaryKey(1) +} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/junit5/Calculator.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/junit5/Calculator.kt new file mode 100644 index 0000000000..1b61c05887 --- /dev/null +++ b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/junit5/Calculator.kt @@ -0,0 +1,17 @@ +package com.baeldung.kotlin.junit5 + +class Calculator { + fun add(a: Int, b: Int) = a + b + + fun divide(a: Int, b: Int) = if (b == 0) { + throw DivideByZeroException(a) + } else { + a / b + } + + fun square(a: Int) = a * a + + fun squareRoot(a: Int) = Math.sqrt(a.toDouble()) + + fun log(base: Int, value: Int) = Math.log(value.toDouble()) / Math.log(base.toDouble()) +} diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/junit5/DivideByZeroException.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/junit5/DivideByZeroException.kt new file mode 100644 index 0000000000..60bc4e2944 --- /dev/null +++ b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/junit5/DivideByZeroException.kt @@ -0,0 +1,3 @@ +package com.baeldung.kotlin.junit5 + +class DivideByZeroException(val numerator: Int) : Exception() diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/khttp/KhttpLiveTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/khttp/KhttpLiveTest.kt new file mode 100644 index 0000000000..4deb576b9f --- /dev/null +++ b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/khttp/KhttpLiveTest.kt @@ -0,0 +1,153 @@ +package com.baeldung.kotlin.khttp + +import khttp.structures.files.FileLike +import org.json.JSONObject +import org.junit.Test +import java.beans.ExceptionListener +import java.beans.XMLEncoder +import java.io.* +import java.lang.Exception +import java.net.ConnectException +import kotlin.test.assertEquals +import kotlin.test.assertTrue +import kotlin.test.fail + +class KhttpLiveTest { + + @Test + fun whenHttpGetRequestIsMade_thenArgsAreReturned() { + val response = khttp.get( + url = "http://httpbin.org/get", + params = mapOf("p1" to "1", "p2" to "2")) + val args = response.jsonObject.getJSONObject("args") + + assertEquals("1", args["p1"]) + assertEquals("2", args["p2"]) + } + + @Test + fun whenAlternateHttpGetRequestIsMade_thenArgsAreReturned() { + val response = khttp.request( + method = "GET", + url = "http://httpbin.org/get", + params = mapOf("p1" to "1", "p2" to "2")) + val args = response.jsonObject.getJSONObject("args") + + assertEquals("1", args["p1"]) + assertEquals("2", args["p2"]) + } + + @Test + fun whenHeadersAreSet_thenHeadersAreSent() { + val response = khttp.get( + url = "http://httpbin.org/get", + headers = mapOf("header1" to "1", "header2" to "2")) + val headers = response.jsonObject.getJSONObject("headers") + + assertEquals("1", headers["Header1"]) + assertEquals("2", headers["Header2"]) + } + + @Test + fun whenHttpPostRequestIsMadeWithJson_thenBodyIsReturned() { + val response = khttp.post( + url = "http://httpbin.org/post", + params = mapOf("p1" to "1", "p2" to "2"), + json = mapOf("pr1" to "1", "pr2" to "2")) + + val args = response.jsonObject.getJSONObject("args") + + assertEquals("1", args["p1"]) + assertEquals("2", args["p2"]) + + val json = response.jsonObject.getJSONObject("json") + + assertEquals("1", json["pr1"]) + assertEquals("2", json["pr2"]) + } + + @Test + fun whenHttpPostRequestIsMadeWithMapData_thenBodyIsReturned() { + val response = khttp.post( + url = "http://httpbin.org/post", + params = mapOf("p1" to "1", "p2" to "2"), + data = mapOf("pr1" to "1", "pr2" to "2")) + + val args = response.jsonObject.getJSONObject("args") + + assertEquals("1", args["p1"]) + assertEquals("2", args["p2"]) + + val form = response.jsonObject.getJSONObject("form") + + assertEquals("1", form["pr1"]) + assertEquals("2", form["pr2"]) + } + + @Test + fun whenHttpPostRequestIsMadeWithFiles_thenBodyIsReturned() { + val response = khttp.post( + url = "http://httpbin.org/post", + params = mapOf("p1" to "1", "p2" to "2"), + files = listOf( + FileLike("file1", "content1"), + FileLike("file2", javaClass.getResource("KhttpTest.class").openStream().readBytes()))) + + val args = response.jsonObject.getJSONObject("args") + + assertEquals("1", args["p1"]) + assertEquals("2", args["p2"]) + + val files = response.jsonObject.getJSONObject("files") + + assertEquals("content1", files["file1"]) + } + + @Test + fun whenHttpPostRequestIsMadeWithInputStream_thenBodyIsReturned() { + val response = khttp.post( + url = "http://httpbin.org/post", + params = mapOf("p1" to "1", "p2" to "2"), + data = ByteArrayInputStream("content!".toByteArray())) + + val args = response.jsonObject.getJSONObject("args") + + assertEquals("1", args["p1"]) + assertEquals("2", args["p2"]) + + assertEquals("content!", response.jsonObject["data"]) + } + + @Test + fun whenHttpPostStreamingRequestIsMade_thenBodyIsReturnedInChunks() { + val response = khttp.post( + url = "http://httpbin.org/post", + stream = true, + json = mapOf("pr1" to "1", "pr2" to "2")) + + val baos = ByteArrayOutputStream() + response.contentIterator(chunkSize = 10).forEach { arr : ByteArray -> baos.write(arr) } + val json = JSONObject(String(baos.toByteArray())).getJSONObject("json") + + assertEquals("1", json["pr1"]) + assertEquals("2", json["pr2"]) + } + + @Test + fun whenHttpRequestFails_thenExceptionIsThrown() { + try { + khttp.get(url = "http://localhost/nothing/to/see/here") + + fail("Should have thrown an exception") + } catch (e : ConnectException) { + //Ok + } + } + + @Test + fun whenHttpNotFound_thenExceptionIsThrown() { + val response = khttp.get(url = "http://httpbin.org/nothing/to/see/here") + + assertEquals(404, response.statusCode) + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/kodein/KodeinUnitTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/kodein/KodeinUnitTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/kodein/KodeinUnitTest.kt rename to kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/kodein/KodeinUnitTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTest.kt rename to kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTestMockitoKotlin.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTestMockitoKotlin.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTestMockitoKotlin.kt rename to kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTestMockitoKotlin.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorSubjectTest5.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorSubjectTest5.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorSubjectTest5.kt rename to kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorSubjectTest5.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorTest5.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorTest5.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorTest5.kt rename to kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorTest5.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/DataDrivenTest5.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/DataDrivenTest5.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/DataDrivenTest5.kt rename to kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/DataDrivenTest5.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/GroupTest5.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/GroupTest5.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/GroupTest5.kt rename to kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/GroupTest5.kt diff --git a/lagom/greeting-api/src/main/resources/logback.xml b/lagom/greeting-api/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/lagom/greeting-api/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/lagom/greeting-impl/src/main/resources/logback.xml b/lagom/greeting-impl/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/lagom/greeting-impl/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/lagom/weather-api/src/main/resources/logback.xml b/lagom/weather-api/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/lagom/weather-api/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/lagom/weather-impl/src/main/resources/logback.xml b/lagom/weather-impl/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/lagom/weather-impl/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/libraries-data/README.md b/libraries-data/README.md index 718f38d703..652ae0e04c 100644 --- a/libraries-data/README.md +++ b/libraries-data/README.md @@ -8,4 +8,6 @@ - [Introduction to HikariCP](http://www.baeldung.com/hikaricp) - [Introduction to JCache](http://www.baeldung.com/jcache) - [A Guide to Apache Ignite](http://www.baeldung.com/apache-ignite) -- [Apache Ignite with Spring Data](http://www.baeldung.com/apache-ignite-spring-data) \ No newline at end of file +- [Apache Ignite with Spring Data](http://www.baeldung.com/apache-ignite-spring-data) +- [Guide to JMapper](https://www.baeldung.com/jmapper) +- [A Guide to Apache Crunch](https://www.baeldung.com/apache-crunch) diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index f1531a8eae..2b83328295 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 libraries-data libraries-data @@ -87,48 +87,48 @@ gson ${gson.version} - + com.zaxxer HikariCP - 2.7.2 + ${HikariCP.version} compile org.datanucleus javax.jdo - 3.2.0-m7 + ${javax.jdo.version} org.datanucleus datanucleus-core - 5.1.1 + ${datanucleus.version} org.datanucleus datanucleus-api-jdo - 5.1.1 + ${datanucleus.version} org.datanucleus datanucleus-rdbms - 5.1.1 + ${datanucleus.version} org.datanucleus datanucleus-maven-plugin - 5.0.2 + ${datanucleus-maven-plugin.version} org.datanucleus datanucleus-xml - 5.0.0-release + ${datanucleus-xml.version} org.datanucleus datanucleus-jdo-query - 5.0.4 + ${datanucleus-jdo-query.version} @@ -141,6 +141,51 @@ hazelcast ${hazelcast.version} + + + com.googlecode.jmapper-framework + jmapper-core + ${jmapper.version} + + + + + org.apache.crunch + crunch-core + ${org.apache.crunch.crunch-core.version} + + + org.apache.hadoop + hadoop-client + ${org.apache.hadoop.hadoop-client} + provided + + + + commons-cli + commons-cli + 1.2 + provided + + + commons-io + commons-io + 2.1 + provided + + + commons-httpclient + commons-httpclient + 3.0.1 + provided + + + commons-codec + commons-codec + + + + @@ -159,24 +204,16 @@ - - - + + + - - + + - + @@ -234,7 +271,7 @@ org.datanucleus datanucleus-maven-plugin - 5.0.2 + ${datanucleus-maven-plugin.version} JDO ${basedir}/datanucleus.properties @@ -253,6 +290,31 @@ + + org.apache.maven.plugins + maven-assembly-plugin + 2.3 + + + src/main/assembly/hadoop-job.xml + + + + com.baeldung.crunch.WordCount + + + + + + make-assembly + package + + single + + + + + @@ -274,9 +336,18 @@ 2.4.0 2.8.2 1.1.0 - 3.8.4 + 3.8.4 1.8 3.0.0 + 2.7.2 + 3.2.0-m7 + 5.1.1 + 5.0.2 + 5.0.0-release + 5.0.4 + 1.6.0.1 + 0.15.0 + 2.2.0 diff --git a/libraries-data/src/main/assembly/hadoop-job.xml b/libraries-data/src/main/assembly/hadoop-job.xml new file mode 100644 index 0000000000..1917e1e5a3 --- /dev/null +++ b/libraries-data/src/main/assembly/hadoop-job.xml @@ -0,0 +1,28 @@ + + + + + job + + jar + + false + + + false + runtime + lib + + ${groupId}:${artifactId} + + + + true + + ${groupId}:${artifactId} + + + + diff --git a/libraries-data/src/main/java/com/baeldung/crunch/StopWordFilter.java b/libraries-data/src/main/java/com/baeldung/crunch/StopWordFilter.java new file mode 100644 index 0000000000..bdd606e179 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/crunch/StopWordFilter.java @@ -0,0 +1,25 @@ +package com.baeldung.crunch; + +import java.util.Set; + +import org.apache.crunch.FilterFn; + +import com.google.common.collect.ImmutableSet; + +/** + * A filter that removes known stop words. + */ +public class StopWordFilter extends FilterFn { + + // English stop words, borrowed from Lucene. + private static final Set STOP_WORDS = ImmutableSet + .copyOf(new String[] { "a", "and", "are", "as", "at", "be", "but", "by", + "for", "if", "in", "into", "is", "it", "no", "not", "of", "on", + "or", "s", "such", "t", "that", "the", "their", "then", "there", + "these", "they", "this", "to", "was", "will", "with" }); + + @Override + public boolean accept(String word) { + return !STOP_WORDS.contains(word); + } +} diff --git a/libraries-data/src/main/java/com/baeldung/crunch/ToUpperCaseFn.java b/libraries-data/src/main/java/com/baeldung/crunch/ToUpperCaseFn.java new file mode 100644 index 0000000000..a277883ad3 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/crunch/ToUpperCaseFn.java @@ -0,0 +1,11 @@ +package com.baeldung.crunch; + +import org.apache.crunch.MapFn; + +public class ToUpperCaseFn extends MapFn { + + @Override + public String map(String input) { + return input != null ? input.toUpperCase() : input; + } +} diff --git a/libraries-data/src/main/java/com/baeldung/crunch/ToUpperCaseWithCounterFn.java b/libraries-data/src/main/java/com/baeldung/crunch/ToUpperCaseWithCounterFn.java new file mode 100644 index 0000000000..f753f98866 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/crunch/ToUpperCaseWithCounterFn.java @@ -0,0 +1,20 @@ +package com.baeldung.crunch; + +import org.apache.crunch.MapFn; + +@SuppressWarnings("serial") +public class ToUpperCaseWithCounterFn extends MapFn { + + @Override + public String map(String input) { + if (input == null) { + return input; + } else { + String output = input.toUpperCase(); + if (!input.equals(output)) { + increment("UpperCase", "modified"); + } + return output; + } + } +} diff --git a/libraries-data/src/main/java/com/baeldung/crunch/Tokenizer.java b/libraries-data/src/main/java/com/baeldung/crunch/Tokenizer.java new file mode 100644 index 0000000000..9523634be1 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/crunch/Tokenizer.java @@ -0,0 +1,23 @@ +package com.baeldung.crunch; + +import org.apache.crunch.DoFn; +import org.apache.crunch.Emitter; + +import com.google.common.base.Splitter; + +/** + * Splits a line of text, filtering known stop words. + */ +public class Tokenizer extends DoFn { + private static final Splitter SPLITTER = Splitter + .onPattern("\\s+") + .omitEmptyStrings(); + + @Override + public void process(String line, + Emitter emitter) { + for (String word : SPLITTER.split(line)) { + emitter.emit(word); + } + } +} diff --git a/libraries-data/src/main/java/com/baeldung/crunch/WordCount.java b/libraries-data/src/main/java/com/baeldung/crunch/WordCount.java new file mode 100644 index 0000000000..c49abec68a --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/crunch/WordCount.java @@ -0,0 +1,62 @@ +package com.baeldung.crunch; + +import org.apache.crunch.PCollection; +import org.apache.crunch.PTable; +import org.apache.crunch.Pipeline; +import org.apache.crunch.PipelineResult; +import org.apache.crunch.impl.mr.MRPipeline; +import org.apache.crunch.types.writable.Writables; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.conf.Configured; +import org.apache.hadoop.util.GenericOptionsParser; +import org.apache.hadoop.util.Tool; +import org.apache.hadoop.util.ToolRunner; + +/** + * A word count example for Apache Crunch, based on Crunch's example projects. + */ +public class WordCount extends Configured implements Tool { + + public static void main(String[] args) throws Exception { + ToolRunner.run(new Configuration(), new WordCount(), args); + } + + public int run(String[] args) throws Exception { + + if (args.length != 2) { + System.err.println("Usage: hadoop jar crunch-1.0.0-SNAPSHOT-job.jar" + " [generic options] input output"); + System.err.println(); + GenericOptionsParser.printGenericCommandUsage(System.err); + return 1; + } + + String inputPath = args[0]; + String outputPath = args[1]; + + // Create an object to coordinate pipeline creation and execution. + Pipeline pipeline = new MRPipeline(WordCount.class, getConf()); + + // Reference a given text file as a collection of Strings. + PCollection lines = pipeline.readTextFile(inputPath); + + // Define a function that splits each line in a PCollection of Strings into + // a PCollection made up of the individual words in the file. + // The second argument sets the serialization format. + PCollection words = lines.parallelDo(new Tokenizer(), Writables.strings()); + + // Take the collection of words and remove known stop words. + PCollection noStopWords = words.filter(new StopWordFilter()); + + // The count method applies a series of Crunch primitives and returns + // a map of the unique words in the input PCollection to their counts. + PTable counts = noStopWords.count(); + + // Instruct the pipeline to write the resulting counts to a text file. + pipeline.writeTextFile(counts, outputPath); + + // Execute the pipeline as a MapReduce. + PipelineResult result = pipeline.done(); + + return result.succeeded() ? 0 : 1; + } +} diff --git a/libraries-data/src/main/java/com/baeldung/jmapper/User.java b/libraries-data/src/main/java/com/baeldung/jmapper/User.java new file mode 100644 index 0000000000..9f99157183 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/jmapper/User.java @@ -0,0 +1,56 @@ +package com.baeldung.jmapper; + +import java.time.LocalDate; + + +public class User { + + private long id; + private String email; + private LocalDate birthDate; + + // constructors + + public User() { + super(); + } + + public User(long id, String email, LocalDate birthDate) { + super(); + this.id = id; + this.email = email; + this.birthDate = birthDate; + } + + // getters and setters + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public LocalDate getBirthDate() { + return birthDate; + } + + public void setBirthDate(LocalDate birthDate) { + this.birthDate = birthDate; + } + + @Override + public String toString() { + return "User [id=" + id + ", email=" + email + ", birthDate=" + birthDate + "]"; + } + +} diff --git a/libraries-data/src/main/java/com/baeldung/jmapper/UserDto.java b/libraries-data/src/main/java/com/baeldung/jmapper/UserDto.java new file mode 100644 index 0000000000..326e8f3cd5 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/jmapper/UserDto.java @@ -0,0 +1,69 @@ +package com.baeldung.jmapper; + +import java.time.LocalDate; +import java.time.Period; + +import com.googlecode.jmapper.annotations.JMap; +import com.googlecode.jmapper.annotations.JMapConversion; + +public class UserDto { + + @JMap + private long id; + + @JMap("email") + private String username; + + @JMap("birthDate") + private int age; + + @JMapConversion(from={"birthDate"}, to={"age"}) + public int conversion(LocalDate birthDate){ + return Period.between(birthDate, LocalDate.now()).getYears(); + } + + // constructors + + public UserDto() { + super(); + } + + public UserDto(long id, String username, int age) { + super(); + this.id = id; + this.username = username; + this.age = age; + } + + // getters and setters + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + @Override + public String toString() { + return "UserDto [id=" + id + ", username=" + username + ", age=" + age + "]"; + } + +} diff --git a/libraries-data/src/main/java/com/baeldung/jmapper/UserDto1.java b/libraries-data/src/main/java/com/baeldung/jmapper/UserDto1.java new file mode 100644 index 0000000000..99247c56f6 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/jmapper/UserDto1.java @@ -0,0 +1,47 @@ +package com.baeldung.jmapper; + +import com.googlecode.jmapper.annotations.JGlobalMap; + +@JGlobalMap +public class UserDto1 { + + private long id; + private String email; + + + // constructors + + public UserDto1() { + super(); + } + + public UserDto1(long id, String email) { + super(); + this.id = id; + this.email = email; + } + + // getters and setters + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String toString() { + return "UserDto [id=" + id + ", email=" + email + "]"; + } + +} diff --git a/libraries-data/src/main/java/com/baeldung/jmapper/relational/User.java b/libraries-data/src/main/java/com/baeldung/jmapper/relational/User.java new file mode 100644 index 0000000000..1238a82684 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/jmapper/relational/User.java @@ -0,0 +1,49 @@ +package com.baeldung.jmapper.relational; + +import com.googlecode.jmapper.annotations.JMap; + + +public class User { + + @JMap(classes = {UserDto1.class, UserDto2.class}) + private long id; + + @JMap(attributes = {"username", "email"}, classes = {UserDto1.class, UserDto2.class}) + private String email; + + // constructors + + public User() { + super(); + } + + public User(long id, String email) { + super(); + this.id = id; + this.email = email; + } + + // getters and setters + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String toString() { + return "User [id=" + id + ", email=" + email + "]"; + } + +} diff --git a/libraries-data/src/main/java/com/baeldung/jmapper/relational/UserDto1.java b/libraries-data/src/main/java/com/baeldung/jmapper/relational/UserDto1.java new file mode 100644 index 0000000000..375fd267a0 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/jmapper/relational/UserDto1.java @@ -0,0 +1,44 @@ +package com.baeldung.jmapper.relational; + + +public class UserDto1 { + + private long id; + private String username; + + // constructors + + public UserDto1() { + super(); + } + + public UserDto1(long id, String username) { + super(); + this.id = id; + this.username = username; + } + + // getters and setters + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + @Override + public String toString() { + return "UserDto [id=" + id + ", username=" + username + "]"; + } + +} diff --git a/libraries-data/src/main/java/com/baeldung/jmapper/relational/UserDto2.java b/libraries-data/src/main/java/com/baeldung/jmapper/relational/UserDto2.java new file mode 100644 index 0000000000..d0858c7d8e --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/jmapper/relational/UserDto2.java @@ -0,0 +1,44 @@ +package com.baeldung.jmapper.relational; + + +public class UserDto2 { + + private long id; + private String email; + + // constructors + + public UserDto2() { + super(); + } + + public UserDto2(long id, String email) { + super(); + this.id = id; + this.email = email; + } + + // getters and setters + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String toString() { + return "UserDto2 [id=" + id + ", email=" + email + "]"; + } + +} diff --git a/libraries-data/src/main/resources/db.sql b/libraries-data/src/main/resources/db.sql index 1dac59307b..e6a9ed3fc2 100644 --- a/libraries-data/src/main/resources/db.sql +++ b/libraries-data/src/main/resources/db.sql @@ -1,3 +1,7 @@ +drop table if exists emp; +drop table if exists dept; + + create table dept( deptno numeric, dname varchar(14), diff --git a/libraries-data/src/main/resources/logback.xml b/libraries-data/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/libraries-data/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/libraries-data/src/main/resources/user_jmapper.xml b/libraries-data/src/main/resources/user_jmapper.xml new file mode 100644 index 0000000000..f007de9f0a --- /dev/null +++ b/libraries-data/src/main/resources/user_jmapper.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/libraries-data/src/main/resources/user_jmapper1.xml b/libraries-data/src/main/resources/user_jmapper1.xml new file mode 100644 index 0000000000..abcfd77e1c --- /dev/null +++ b/libraries-data/src/main/resources/user_jmapper1.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/libraries-data/src/main/resources/user_jmapper2.xml b/libraries-data/src/main/resources/user_jmapper2.xml new file mode 100644 index 0000000000..1e708e14bf --- /dev/null +++ b/libraries-data/src/main/resources/user_jmapper2.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/libraries-data/src/test/java/com/baeldung/crunch/MemPipelineUnitTest.java b/libraries-data/src/test/java/com/baeldung/crunch/MemPipelineUnitTest.java new file mode 100644 index 0000000000..3ee2bb6836 --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/crunch/MemPipelineUnitTest.java @@ -0,0 +1,89 @@ +package com.baeldung.crunch; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertIterableEquals; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Calendar; + +import org.apache.crunch.PCollection; +import org.apache.crunch.Pipeline; +import org.apache.crunch.Source; +import org.apache.crunch.Target; +import org.apache.crunch.impl.mem.MemPipeline; +import org.apache.crunch.io.From; +import org.apache.crunch.io.To; +import org.junit.Ignore; +import org.junit.Test; + +public class MemPipelineUnitTest { + + private static final String INPUT_FILE_PATH = "src/test/resources/crunch/input.txt"; + + @Test + public void givenPipeLineAndSource_whenSourceRead_thenExpectedNumberOfRecordsRead() { + Pipeline pipeline = MemPipeline.getInstance(); + Source source = From.textFile(INPUT_FILE_PATH); + + PCollection lines = pipeline.read(source); + + assertEquals(21, lines.asCollection() + .getValue() + .size()); + } + + @Test + public void givenPipeLine_whenTextFileRead_thenExpectedNumberOfRecordsRead() { + Pipeline pipeline = MemPipeline.getInstance(); + + PCollection lines = pipeline.readTextFile(INPUT_FILE_PATH); + + assertEquals(21, lines.asCollection() + .getValue() + .size()); + } + + private String createOutputPath() throws IOException { + Path path = Files.createTempDirectory("test"); + final String outputFilePath = path.toString() + File.separatorChar + + "output.text"; + return outputFilePath; + } + + @Test + @Ignore("Requires Hadoop binaries") + public void givenCollection_whenWriteCalled_fileWrittenSuccessfully() + throws IOException { + PCollection inputStrings = MemPipeline.collectionOf("Hello", + "Apache", "Crunch", Calendar.getInstance() + .toString()); + final String outputFilePath = createOutputPath(); + Target target = To.textFile(outputFilePath); + + inputStrings.write(target); + + Pipeline pipeline = MemPipeline.getInstance(); + PCollection lines = pipeline.readTextFile(outputFilePath); + assertIterableEquals(inputStrings.materialize(), lines.materialize()); + } + + @Test + @Ignore("Requires Hadoop binaries") + public void givenPipeLine_whenWriteTextFileCalled_fileWrittenSuccessfully() + throws IOException { + Pipeline pipeline = MemPipeline.getInstance(); + PCollection inputStrings = MemPipeline.collectionOf("Hello", + "Apache", "Crunch", Calendar.getInstance() + .toString()); + final String outputFilePath = createOutputPath(); + + pipeline.writeTextFile(inputStrings, outputFilePath); + + PCollection lines = pipeline.readTextFile(outputFilePath); + assertIterableEquals(inputStrings.materialize(), lines.materialize()); + } + +} diff --git a/libraries-data/src/test/java/com/baeldung/crunch/StopWordFilterUnitTest.java b/libraries-data/src/test/java/com/baeldung/crunch/StopWordFilterUnitTest.java new file mode 100644 index 0000000000..fffefc2bfb --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/crunch/StopWordFilterUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.crunch; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.apache.crunch.FilterFn; +import org.apache.crunch.PCollection; +import org.apache.crunch.impl.mem.MemPipeline; +import org.junit.Test; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; + +public class StopWordFilterUnitTest { + + @Test + public void givenFilter_whenStopWordPassed_thenFalseReturned() { + FilterFn filter = new StopWordFilter(); + + assertFalse(filter.accept("the")); + } + + @Test + public void givenFilter_whenNonStopWordPassed_thenTrueReturned() { + FilterFn filter = new StopWordFilter(); + + assertTrue(filter.accept("Hello")); + } + + @Test + public void givenWordCollection_whenFiltered_thenStopWordsRemoved() { + PCollection words = MemPipeline.collectionOf("This", "is", "a", + "test", "sentence"); + + PCollection noStopWords = words.filter(new StopWordFilter()); + + assertEquals(ImmutableList.of("This", "test", "sentence"), + Lists.newArrayList(noStopWords.materialize())); + } +} diff --git a/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseFnUnitTest.java b/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseFnUnitTest.java new file mode 100644 index 0000000000..09fb9fba85 --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseFnUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.crunch; + +import static org.junit.Assert.assertEquals; + +import org.apache.crunch.impl.mem.emit.InMemoryEmitter; +import org.junit.Test; + +import com.google.common.collect.ImmutableList; + +public class ToUpperCaseFnUnitTest { + + @Test + public void givenString_whenToUpperCaseFnCalled_UpperCaseStringReturned() { + InMemoryEmitter emitter = new InMemoryEmitter(); + + new ToUpperCaseFn().process("input", emitter); + + assertEquals(ImmutableList.of("INPUT"), emitter.getOutput()); + } + +} diff --git a/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseWithCounterFnUnitTest.java b/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseWithCounterFnUnitTest.java new file mode 100644 index 0000000000..76294d273d --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseWithCounterFnUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.crunch; + +import static org.junit.Assert.assertEquals; + +import org.apache.crunch.PCollection; +import org.apache.crunch.impl.mem.MemPipeline; +import org.apache.crunch.types.writable.Writables; +import org.junit.Before; +import org.junit.Test; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; + +public class ToUpperCaseWithCounterFnUnitTest { + + @Before + public void setUp() throws Exception { + MemPipeline.clearCounters(); + } + + @Test + public void whenFunctionCalled_counterIncementendForChangedValues() { + PCollection inputStrings = MemPipeline.collectionOf("This", "is", "a", "TEST", "string"); + PCollection upperCaseStrings = inputStrings.parallelDo(new ToUpperCaseWithCounterFn(), Writables.strings()); + + assertEquals(ImmutableList.of("THIS", "IS", "A", "TEST", "STRING"), Lists.newArrayList(upperCaseStrings.materialize())); + assertEquals(4L, MemPipeline.getCounters() + .findCounter("UpperCase", "modified") + .getValue()); + } +} diff --git a/libraries-data/src/test/java/com/baeldung/crunch/TokenizerUnitTest.java b/libraries-data/src/test/java/com/baeldung/crunch/TokenizerUnitTest.java new file mode 100644 index 0000000000..1e85826d17 --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/crunch/TokenizerUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.crunch; + +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +import org.apache.crunch.Emitter; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class TokenizerUnitTest { + @Mock + private Emitter emitter; + + @Test + public void givenTokenizer_whenLineProcessed_thenOnlyExpectedWordsEmitted() { + Tokenizer splitter = new Tokenizer(); + + splitter.process(" hello world ", emitter); + + verify(emitter).emit("hello"); + verify(emitter).emit("world"); + verifyNoMoreInteractions(emitter); + } +} diff --git a/libraries-data/src/test/java/com/baeldung/jcache/CacheLoaderIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jcache/CacheLoaderIntegrationTest.java new file mode 100644 index 0000000000..8017418eba --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/jcache/CacheLoaderIntegrationTest.java @@ -0,0 +1,43 @@ +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 CacheLoaderIntegrationTest { + + private static final String CACHE_NAME = "SimpleCache"; + + private Cache cache; + + @Before + public void setup() { + // Adding fully qualified class name because of multiple Cache Provider (Ignite and Hazelcast) + CachingProvider cachingProvider = Caching.getCachingProvider("com.hazelcast.cache.HazelcastCachingProvider"); + 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("com.hazelcast.cache.HazelcastCachingProvider").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-data/src/test/java/com/baeldung/jcache/CacheLoaderTest.java b/libraries-data/src/test/java/com/baeldung/jcache/CacheLoaderTest.java deleted file mode 100644 index 93ff3f09a3..0000000000 --- a/libraries-data/src/test/java/com/baeldung/jcache/CacheLoaderTest.java +++ /dev/null @@ -1,43 +0,0 @@ -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() { - // Adding fully qualified class name because of multiple Cache Provider (Ignite and Hazelcast) - CachingProvider cachingProvider = Caching.getCachingProvider("com.hazelcast.cache.HazelcastCachingProvider"); - 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("com.hazelcast.cache.HazelcastCachingProvider").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-data/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java index 61c98d0126..fd1e9c29a9 100644 --- a/libraries-data/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java +++ b/libraries-data/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java @@ -15,12 +15,13 @@ import static org.junit.Assert.assertEquals; public class EntryProcessorIntegrationTest { private static final String CACHE_NAME = "MyCache"; + private static final String CACHE_PROVIDER_NAME = "com.hazelcast.cache.HazelcastCachingProvider"; private Cache cache; @Before public void instantiateCache() { - CachingProvider cachingProvider = Caching.getCachingProvider(); + CachingProvider cachingProvider = Caching.getCachingProvider(CACHE_PROVIDER_NAME); CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration config = new MutableConfiguration<>(); this.cache = cacheManager.createCache(CACHE_NAME, config); @@ -29,7 +30,7 @@ public class EntryProcessorIntegrationTest { @After public void tearDown() { - Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME); + Caching.getCachingProvider(CACHE_PROVIDER_NAME).getCacheManager().destroyCache(CACHE_NAME); } @Test diff --git a/libraries-data/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java index fcbfbe6111..512a75ec61 100644 --- a/libraries-data/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java +++ b/libraries-data/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java @@ -17,6 +17,7 @@ import static org.junit.Assert.assertEquals; public class EventListenerIntegrationTest { private static final String CACHE_NAME = "MyCache"; + private static final String CACHE_PROVIDER_NAME = "com.hazelcast.cache.HazelcastCachingProvider"; private Cache cache; private SimpleCacheEntryListener listener; @@ -24,7 +25,7 @@ public class EventListenerIntegrationTest { @Before public void setup() { - CachingProvider cachingProvider = Caching.getCachingProvider(); + CachingProvider cachingProvider = Caching.getCachingProvider(CACHE_PROVIDER_NAME); CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration config = new MutableConfiguration(); this.cache = cacheManager.createCache("MyCache", config); @@ -33,7 +34,7 @@ public class EventListenerIntegrationTest { @After public void tearDown() { - Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME); + Caching.getCachingProvider(CACHE_PROVIDER_NAME).getCacheManager().destroyCache(CACHE_NAME); } @Test diff --git a/libraries-data/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java index fac3d32bcb..33521469fa 100644 --- a/libraries-data/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java +++ b/libraries-data/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java @@ -14,7 +14,7 @@ public class JCacheIntegrationTest { @Test public void instantiateCache() { - CachingProvider cachingProvider = Caching.getCachingProvider(); + CachingProvider cachingProvider = Caching.getCachingProvider("com.hazelcast.cache.HazelcastCachingProvider"); CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration config = new MutableConfiguration<>(); Cache cache = cacheManager.createCache("simpleCache", config); diff --git a/libraries-data/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java index 03e63c2580..e8c69d67b7 100644 --- a/libraries-data/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java +++ b/libraries-data/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java @@ -1,17 +1,18 @@ package com.baeldung.jdo; -import org.datanucleus.api.jdo.JDOPersistenceManagerFactory; -import org.datanucleus.metadata.PersistenceUnitMetaData; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.util.List; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.jdo.Query; import javax.jdo.Transaction; -import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import org.datanucleus.api.jdo.JDOPersistenceManagerFactory; +import org.datanucleus.metadata.PersistenceUnitMetaData; +import org.junit.Test; public class GuideToJDOIntegrationTest { @Test @@ -24,6 +25,7 @@ public class GuideToJDOIntegrationTest { pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa"); pumd.addProperty("javax.jdo.option.ConnectionPassword", ""); pumd.addProperty("datanucleus.autoCreateSchema", "true"); + pumd.addProperty("datanucleus.schema.autoCreateTables", "true"); PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManager pm = pmf.getPersistenceManager(); @@ -58,6 +60,7 @@ public class GuideToJDOIntegrationTest { pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa"); pumd.addProperty("javax.jdo.option.ConnectionPassword", ""); pumd.addProperty("datanucleus.autoCreateSchema", "true"); + pumd.addProperty("datanucleus.schema.autoCreateTables", "true"); PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManager pm = pmf.getPersistenceManager(); diff --git a/libraries-data/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java new file mode 100644 index 0000000000..96ed090482 --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java @@ -0,0 +1,114 @@ +package com.baeldung.jmapper; + +import static com.googlecode.jmapper.api.JMapperAPI.attribute; +import static com.googlecode.jmapper.api.JMapperAPI.global; +import static com.googlecode.jmapper.api.JMapperAPI.mappedClass; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.time.LocalDate; + +import org.junit.Test; + +import com.googlecode.jmapper.JMapper; +import com.googlecode.jmapper.api.JMapperAPI; + +public class JMapperIntegrationTest { + + + @Test + public void givenUser_whenUseAnnotation_thenConverted(){ + JMapper userMapper = new JMapper<>(UserDto.class, User.class); + + User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); + UserDto result = userMapper.getDestination(user); + + System.out.println(result); + assertEquals(user.getId(), result.getId()); + assertEquals(user.getEmail(), result.getUsername()); + } + + @Test + public void givenUser_whenUseGlobalMapAnnotation_thenConverted(){ + JMapper userMapper= new JMapper<>(UserDto1.class, User.class); + + User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); + UserDto1 result = userMapper.getDestination(user); + + System.out.println(result); + assertEquals(user.getId(), result.getId()); + assertEquals(user.getEmail(), result.getEmail()); + } + + @Test + public void givenUser_whenUseAnnotationExplicitConversion_thenConverted(){ + JMapper userMapper = new JMapper<>(UserDto.class, User.class); + + User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); + UserDto result = userMapper.getDestination(user); + + System.out.println(result); + assertEquals(user.getId(), result.getId()); + assertEquals(user.getEmail(), result.getUsername()); + assertTrue(result.getAge() > 0); + } + + //======================= XML + + @Test + public void givenUser_whenUseXml_thenConverted(){ + JMapper userMapper = new JMapper<>(UserDto.class, User.class,"user_jmapper.xml"); + + User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); + UserDto result = userMapper.getDestination(user); + + System.out.println(result); + assertEquals(user.getId(), result.getId()); + assertEquals(user.getEmail(), result.getUsername()); + } + + @Test + public void givenUser_whenUseXmlGlobal_thenConverted(){ + JMapper userMapper = new JMapper<>(UserDto1.class, User.class,"user_jmapper1.xml"); + + User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); + UserDto1 result = userMapper.getDestination(user); + + System.out.println(result); + assertEquals(user.getId(), result.getId()); + assertEquals(user.getEmail(), result.getEmail()); + } + + // ===== API + + @Test + public void givenUser_whenUseApi_thenConverted(){ + JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class) + .add(attribute("id").value("id")) + .add(attribute("username").value("email")) + ) ; + JMapper userMapper = new JMapper<>(UserDto.class, User.class, jmapperApi); + + User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); + UserDto result = userMapper.getDestination(user); + + System.out.println(result); + assertEquals(user.getId(), result.getId()); + assertEquals(user.getEmail(), result.getUsername()); + } + + @Test + public void givenUser_whenUseApiGlobal_thenConverted(){ + JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class) + .add(global()) + ) ; + JMapper userMapper1 = new JMapper<>(UserDto1.class, User.class,jmapperApi); + + User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); + UserDto1 result = userMapper1.getDestination(user); + + System.out.println(result); + assertEquals(user.getId(), result.getId()); + assertEquals(user.getEmail(), result.getEmail()); + } +} diff --git a/libraries-data/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java new file mode 100644 index 0000000000..6af2865159 --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java @@ -0,0 +1,76 @@ +package com.baeldung.jmapper; + +import static com.googlecode.jmapper.api.JMapperAPI.attribute; +import static com.googlecode.jmapper.api.JMapperAPI.mappedClass; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.jmapper.relational.User; +import com.baeldung.jmapper.relational.UserDto1; +import com.baeldung.jmapper.relational.UserDto2; +import com.googlecode.jmapper.RelationalJMapper; +import com.googlecode.jmapper.api.JMapperAPI; + +public class JMapperRelationalIntegrationTest { + + + @Test + public void givenUser_whenUseAnnotation_thenConverted(){ + RelationalJMapper relationalMapper = new RelationalJMapper<>(User.class); + + User user = new User(1L,"john@test.com"); + UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user); + UserDto2 result2= relationalMapper.oneToMany(UserDto2.class, user); + + System.out.println(result1); + System.out.println(result2); + assertEquals(user.getId(), result1.getId()); + assertEquals(user.getEmail(), result1.getUsername()); + assertEquals(user.getId(), result2.getId()); + assertEquals(user.getEmail(), result2.getEmail()); + } + + //======================= XML + + @Test + public void givenUser_whenUseXml_thenConverted(){ + RelationalJMapper relationalMapper = new RelationalJMapper<>(User.class,"user_jmapper2.xml"); + + User user = new User(1L,"john@test.com"); + UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user); + UserDto2 result2 = relationalMapper.oneToMany(UserDto2.class, user); + + System.out.println(result1); + System.out.println(result2); + assertEquals(user.getId(), result1.getId()); + assertEquals(user.getEmail(), result1.getUsername()); + assertEquals(user.getId(), result2.getId()); + assertEquals(user.getEmail(), result2.getEmail()); + } + + + // ===== API + + @Test + public void givenUser_whenUseApi_thenConverted(){ + JMapperAPI jmapperApi = new JMapperAPI() + .add(mappedClass(User.class) + .add(attribute("id").value("id").targetClasses(UserDto1.class,UserDto2.class)) + .add(attribute("email").targetAttributes("username","email").targetClasses(UserDto1.class,UserDto2.class)) ) + ; + RelationalJMapper relationalMapper = new RelationalJMapper<>(User.class,jmapperApi); + + User user = new User(1L,"john@test.com"); + UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user); + UserDto2 result2 = relationalMapper.oneToMany(UserDto2.class, user); + + System.out.println(result1); + System.out.println(result2); + assertEquals(user.getId(), result1.getId()); + assertEquals(user.getEmail(), result1.getUsername()); + assertEquals(user.getId(), result2.getId()); + assertEquals(user.getEmail(), result2.getEmail()); + } + +} diff --git a/libraries-data/src/test/resources/crunch/input.txt b/libraries-data/src/test/resources/crunch/input.txt new file mode 100644 index 0000000000..cb78ea5351 --- /dev/null +++ b/libraries-data/src/test/resources/crunch/input.txt @@ -0,0 +1,21 @@ +An an valley indeed so no wonder future nature vanity. Debating all she mistaken indulged believed provided declared. He many kept on draw lain song as same. Whether at dearest certain spirits is entered in to. Rich fine bred real use too many good. She compliment unaffected expression favourable any. Unknown chiefly showing to conduct no. Hung as love evil able to post at as. + + + +Is he staying arrival address earnest. To preference considered it themselves inquietude collecting estimating. View park for why gay knew face. Next than near to four so hand. Times so do he downs me would. Witty abode party her found quiet law. They door four bed fail now have. + +Tolerably earnestly middleton extremely distrusts she boy now not. Add and offered prepare how cordial two promise. Greatly who affixed suppose but enquire compact prepare all put. Added forth chief trees but rooms think may. Wicket do manner others seemed enable rather in. Excellent own discovery unfeeling sweetness questions the gentleman. Chapter shyness matters mr parlors if mention thought. + +Extended kindness trifling remember he confined outlived if. Assistance sentiments yet unpleasing say. Open they an busy they my such high. An active dinner wishes at unable hardly no talked on. Immediate him her resolving his favourite. Wished denote abroad at branch at. + +Village did removed enjoyed explain nor ham saw calling talking. Securing as informed declared or margaret. Joy horrible moreover man feelings own shy. Request norland neither mistake for yet. Between the for morning assured country believe. On even feet time have an no at. Relation so in confined smallest children unpacked delicate. Why sir end believe uncivil respect. Always get adieus nature day course for common. My little garret repair to desire he esteem. + +You vexed shy mirth now noise. Talked him people valley add use her depend letter. Allowance too applauded now way something recommend. Mrs age men and trees jokes fancy. Gay pretended engrossed eagerness continued ten. Admitting day him contained unfeeling attention mrs out. + +Performed suspicion in certainty so frankness by attention pretended. Newspaper or in tolerably education enjoyment. Extremity excellent certainty discourse sincerity no he so resembled. Joy house worse arise total boy but. Elderly up chicken do at feeling is. Like seen drew no make fond at on rent. Behaviour extremely her explained situation yet september gentleman are who. Is thought or pointed hearing he. + +If wandered relation no surprise of screened doubtful. Overcame no insisted ye of trifling husbands. Might am order hours on found. Or dissimilar companions friendship impossible at diminution. Did yourself carriage learning she man its replying. Sister piqued living her you enable mrs off spirit really. Parish oppose repair is me misery. Quick may saw style after money mrs. + +Effects present letters inquiry no an removed or friends. Desire behind latter me though in. Supposing shameless am he engrossed up additions. My possible peculiar together to. Desire so better am cannot he up before points. Remember mistaken opinions it pleasure of debating. Court front maids forty if aware their at. Chicken use are pressed removed. + +To sorry world an at do spoil along. Incommode he depending do frankness remainder to. Edward day almost active him friend thirty piqued. People as period twenty my extent as. Set was better abroad ham plenty secure had horses. Admiration has sir decisively excellence say everything inhabiting acceptance. Sooner settle add put you sudden him. diff --git a/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml b/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml index a1951f09b7..6e5d212fb8 100644 --- a/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml +++ b/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml @@ -2,6 +2,6 @@ - + \ No newline at end of file diff --git a/libraries-server/.gitignore b/libraries-server/.gitignore new file mode 100644 index 0000000000..e594daf27a --- /dev/null +++ b/libraries-server/.gitignore @@ -0,0 +1,9 @@ +*.class + +# Folders # +/gensrc +/target + +# Packaged files # +*.jar +/bin/ diff --git a/libraries-server/README.md b/libraries-server/README.md new file mode 100644 index 0000000000..28f963ade8 --- /dev/null +++ b/libraries-server/README.md @@ -0,0 +1,9 @@ +### Relevant articles + +- [Embedded Jetty Server in Java](http://www.baeldung.com/jetty-embedded) +- [Introduction to Netty](http://www.baeldung.com/netty) +- [Exceptions in Netty](http://www.baeldung.com/netty-exception-handling) +- [Programatically Create, Configure, and Run a Tomcat Server](http://www.baeldung.com/tomcat-programmatic-setup) +- [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic) +- [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel) +- [MQTT Client in Java](https://www.baeldung.com/java-mqtt-client) diff --git a/libraries-server/pom.xml b/libraries-server/pom.xml new file mode 100644 index 0000000000..6fca09faf4 --- /dev/null +++ b/libraries-server/pom.xml @@ -0,0 +1,86 @@ + + 4.0.0 + com.baeldung + libraries-server + 0.0.1-SNAPSHOT + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + org.eclipse.paho + org.eclipse.paho.client.mqttv3 + 1.2.0 + + + + org.assertj + assertj-core + ${assertj.version} + + + org.eclipse.jetty + jetty-server + ${jetty.version} + + + org.eclipse.jetty + jetty-servlet + ${jetty.version} + + + org.eclipse.jetty + jetty-webapp + ${jetty.version} + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + commons-logging + commons-logging + + + + + commons-io + commons-io + ${commons.io.version} + + + io.netty + netty-all + ${netty.version} + + + junit + junit + ${junit.version} + test + + + + + org.apache.tomcat + tomcat-catalina + ${tomcat.version} + + + + + 3.6.2 + 4.5.3 + 2.5 + 9.4.8.v20171121 + 4.1.20.Final + 4.1 + 4.12 + 8.5.24 + + + \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/jetty/AsyncServlet.java b/libraries-server/src/main/java/com/baeldung/jetty/AsyncServlet.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jetty/AsyncServlet.java rename to libraries-server/src/main/java/com/baeldung/jetty/AsyncServlet.java diff --git a/libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java b/libraries-server/src/main/java/com/baeldung/jetty/BlockingServlet.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java rename to libraries-server/src/main/java/com/baeldung/jetty/BlockingServlet.java diff --git a/libraries/src/main/java/com/baeldung/jetty/JettyServer.java b/libraries-server/src/main/java/com/baeldung/jetty/JettyServer.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jetty/JettyServer.java rename to libraries-server/src/main/java/com/baeldung/jetty/JettyServer.java diff --git a/libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java b/libraries-server/src/main/java/com/baeldung/jetty/JettyServerFactory.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java rename to libraries-server/src/main/java/com/baeldung/jetty/JettyServerFactory.java diff --git a/libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java b/libraries-server/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java rename to libraries-server/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java diff --git a/libraries-server/src/main/java/com/baeldung/mqtt/EngineTemperatureSensor.java b/libraries-server/src/main/java/com/baeldung/mqtt/EngineTemperatureSensor.java new file mode 100644 index 0000000000..98111edb94 --- /dev/null +++ b/libraries-server/src/main/java/com/baeldung/mqtt/EngineTemperatureSensor.java @@ -0,0 +1,49 @@ +package com.baeldung.mqtt; + +import java.util.Random; +import java.util.concurrent.Callable; + +import org.eclipse.paho.client.mqttv3.IMqttClient; +import org.eclipse.paho.client.mqttv3.MqttMessage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class EngineTemperatureSensor implements Callable { + + private static final Logger log = LoggerFactory.getLogger(EngineTemperatureSensor.class); + public static final String TOPIC = "engine/temperature"; + + private IMqttClient client; + private Random rnd = new Random(); + + public EngineTemperatureSensor(IMqttClient client) { + this.client = client; + } + + @Override + public Void call() throws Exception { + + if ( !client.isConnected()) { + log.info("[I31] Client not connected."); + return null; + } + + MqttMessage msg = readEngineTemp(); + msg.setQos(0); + msg.setRetained(true); + client.publish(TOPIC,msg); + + return null; + } + + /** + * This method simulates reading the engine temperature + * @return + */ + private MqttMessage readEngineTemp() { + double temp = 80 + rnd.nextDouble() * 20.0; + byte[] payload = String.format("T:%04.2f",temp).getBytes(); + MqttMessage msg = new MqttMessage(payload); + return msg; + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/netty/CalculatorOperationHandler.java b/libraries-server/src/main/java/com/baeldung/netty/CalculatorOperationHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/CalculatorOperationHandler.java rename to libraries-server/src/main/java/com/baeldung/netty/CalculatorOperationHandler.java diff --git a/libraries/src/main/java/com/baeldung/netty/ChannelHandlerA.java b/libraries-server/src/main/java/com/baeldung/netty/ChannelHandlerA.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ChannelHandlerA.java rename to libraries-server/src/main/java/com/baeldung/netty/ChannelHandlerA.java diff --git a/libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java b/libraries-server/src/main/java/com/baeldung/netty/ChannelHandlerB.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java rename to libraries-server/src/main/java/com/baeldung/netty/ChannelHandlerB.java diff --git a/libraries/src/main/java/com/baeldung/netty/ClientHandler.java b/libraries-server/src/main/java/com/baeldung/netty/ClientHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ClientHandler.java rename to libraries-server/src/main/java/com/baeldung/netty/ClientHandler.java diff --git a/libraries/src/main/java/com/baeldung/netty/HttpMessageHandler.java b/libraries-server/src/main/java/com/baeldung/netty/HttpMessageHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/HttpMessageHandler.java rename to libraries-server/src/main/java/com/baeldung/netty/HttpMessageHandler.java diff --git a/libraries/src/main/java/com/baeldung/netty/NettyClient.java b/libraries-server/src/main/java/com/baeldung/netty/NettyClient.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/NettyClient.java rename to libraries-server/src/main/java/com/baeldung/netty/NettyClient.java diff --git a/libraries/src/main/java/com/baeldung/netty/NettyServer.java b/libraries-server/src/main/java/com/baeldung/netty/NettyServer.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/NettyServer.java rename to libraries-server/src/main/java/com/baeldung/netty/NettyServer.java diff --git a/libraries/src/main/java/com/baeldung/netty/NettyServerB.java b/libraries-server/src/main/java/com/baeldung/netty/NettyServerB.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/NettyServerB.java rename to libraries-server/src/main/java/com/baeldung/netty/NettyServerB.java diff --git a/libraries/src/main/java/com/baeldung/netty/Operation.java b/libraries-server/src/main/java/com/baeldung/netty/Operation.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/Operation.java rename to libraries-server/src/main/java/com/baeldung/netty/Operation.java diff --git a/libraries/src/main/java/com/baeldung/netty/ProcessingHandler.java b/libraries-server/src/main/java/com/baeldung/netty/ProcessingHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ProcessingHandler.java rename to libraries-server/src/main/java/com/baeldung/netty/ProcessingHandler.java diff --git a/libraries/src/main/java/com/baeldung/netty/RequestData.java b/libraries-server/src/main/java/com/baeldung/netty/RequestData.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/RequestData.java rename to libraries-server/src/main/java/com/baeldung/netty/RequestData.java diff --git a/libraries/src/main/java/com/baeldung/netty/RequestDataEncoder.java b/libraries-server/src/main/java/com/baeldung/netty/RequestDataEncoder.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/RequestDataEncoder.java rename to libraries-server/src/main/java/com/baeldung/netty/RequestDataEncoder.java diff --git a/libraries/src/main/java/com/baeldung/netty/RequestDecoder.java b/libraries-server/src/main/java/com/baeldung/netty/RequestDecoder.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/RequestDecoder.java rename to libraries-server/src/main/java/com/baeldung/netty/RequestDecoder.java diff --git a/libraries/src/main/java/com/baeldung/netty/ResponseData.java b/libraries-server/src/main/java/com/baeldung/netty/ResponseData.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ResponseData.java rename to libraries-server/src/main/java/com/baeldung/netty/ResponseData.java diff --git a/libraries/src/main/java/com/baeldung/netty/ResponseDataDecoder.java b/libraries-server/src/main/java/com/baeldung/netty/ResponseDataDecoder.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ResponseDataDecoder.java rename to libraries-server/src/main/java/com/baeldung/netty/ResponseDataDecoder.java diff --git a/libraries/src/main/java/com/baeldung/netty/ResponseDataEncoder.java b/libraries-server/src/main/java/com/baeldung/netty/ResponseDataEncoder.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ResponseDataEncoder.java rename to libraries-server/src/main/java/com/baeldung/netty/ResponseDataEncoder.java diff --git a/libraries/src/main/java/com/baeldung/netty/SimpleProcessingHandler.java b/libraries-server/src/main/java/com/baeldung/netty/SimpleProcessingHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/SimpleProcessingHandler.java rename to libraries-server/src/main/java/com/baeldung/netty/SimpleProcessingHandler.java diff --git a/libraries/src/main/java/com/baeldung/tomcat/MyFilter.java b/libraries-server/src/main/java/com/baeldung/tomcat/MyFilter.java similarity index 100% rename from libraries/src/main/java/com/baeldung/tomcat/MyFilter.java rename to libraries-server/src/main/java/com/baeldung/tomcat/MyFilter.java diff --git a/libraries/src/main/java/com/baeldung/tomcat/MyServlet.java b/libraries-server/src/main/java/com/baeldung/tomcat/MyServlet.java similarity index 100% rename from libraries/src/main/java/com/baeldung/tomcat/MyServlet.java rename to libraries-server/src/main/java/com/baeldung/tomcat/MyServlet.java diff --git a/libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java b/libraries-server/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java similarity index 100% rename from libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java rename to libraries-server/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java diff --git a/libraries-server/src/main/resources/logback.xml b/libraries-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/libraries-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java b/libraries-server/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java rename to libraries-server/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java diff --git a/libraries/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java b/libraries-server/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java rename to libraries-server/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java diff --git a/libraries-server/src/test/java/com/baeldung/mqtt/EngineTemperatureSensorLiveTest.java b/libraries-server/src/test/java/com/baeldung/mqtt/EngineTemperatureSensorLiveTest.java new file mode 100644 index 0000000000..b1c0002888 --- /dev/null +++ b/libraries-server/src/test/java/com/baeldung/mqtt/EngineTemperatureSensorLiveTest.java @@ -0,0 +1,109 @@ +package com.baeldung.mqtt; + + + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttConnectOptions; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class EngineTemperatureSensorLiveTest { + + private static Logger log = LoggerFactory.getLogger(EngineTemperatureSensorLiveTest.class); + + @Test + public void whenSendSingleMessage_thenSuccess() throws Exception { + + String publisherId = UUID.randomUUID().toString(); + MqttClient publisher = new MqttClient("tcp://iot.eclipse.org:1883",publisherId); + + String subscriberId = UUID.randomUUID().toString(); + MqttClient subscriber = new MqttClient("tcp://iot.eclipse.org:1883",subscriberId); + + MqttConnectOptions options = new MqttConnectOptions(); + options.setAutomaticReconnect(true); + options.setCleanSession(true); + options.setConnectionTimeout(10); + + + subscriber.connect(options); + publisher.connect(options); + + CountDownLatch receivedSignal = new CountDownLatch(1); + + subscriber.subscribe(EngineTemperatureSensor.TOPIC, (topic, msg) -> { + byte[] payload = msg.getPayload(); + log.info("[I46] Message received: topic={}, payload={}", topic, new String(payload)); + receivedSignal.countDown(); + }); + + + Callable target = new EngineTemperatureSensor(publisher); + target.call(); + + receivedSignal.await(1, TimeUnit.MINUTES); + + log.info("[I56] Success !"); + } + + @Test + public void whenSendMultipleMessages_thenSuccess() throws Exception { + + String publisherId = UUID.randomUUID().toString(); + MqttClient publisher = new MqttClient("tcp://iot.eclipse.org:1883",publisherId); + + String subscriberId = UUID.randomUUID().toString(); + MqttClient subscriber = new MqttClient("tcp://iot.eclipse.org:1883",subscriberId); + + + MqttConnectOptions options = new MqttConnectOptions(); + options.setAutomaticReconnect(true); + options.setCleanSession(true); + options.setConnectionTimeout(10); + + + publisher.connect(options); + subscriber.connect(options); + + CountDownLatch receivedSignal = new CountDownLatch(10); + + subscriber.subscribe(EngineTemperatureSensor.TOPIC, (topic, msg) -> { + byte[] payload = msg.getPayload(); + log.info("[I82] Message received: topic={}, payload={}", topic, new String(payload)); + receivedSignal.countDown(); + }); + + + Callable target = new EngineTemperatureSensor(publisher); + + ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); + executor.scheduleAtFixedRate(() -> { + try { + target.call(); + } + catch(Exception ex) { + throw new RuntimeException(ex); + } + }, 1, 1, TimeUnit.SECONDS); + + + receivedSignal.await(1, TimeUnit.MINUTES); + executor.shutdown(); + + assertTrue(receivedSignal.getCount() == 0 , "Countdown should be zero"); + + log.info("[I105] Success !"); + } + + +} diff --git a/libraries/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java b/libraries-server/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java rename to libraries-server/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatIntegrationTest.java b/libraries-server/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatIntegrationTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatIntegrationTest.java rename to libraries-server/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatIntegrationTest.java diff --git a/libraries/src/test/resources/jetty-embedded-demo-app.war b/libraries-server/src/test/resources/jetty-embedded-demo-app.war similarity index 100% rename from libraries/src/test/resources/jetty-embedded-demo-app.war rename to libraries-server/src/test/resources/jetty-embedded-demo-app.war diff --git a/libraries/.gitignore b/libraries/.gitignore new file mode 100644 index 0000000000..e594daf27a --- /dev/null +++ b/libraries/.gitignore @@ -0,0 +1,9 @@ +*.class + +# Folders # +/gensrc +/target + +# Packaged files # +*.jar +/bin/ diff --git a/libraries/README.md b/libraries/README.md index bde13401e9..c2c4b2718a 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -5,13 +5,11 @@ - [String Processing with Apache Commons Lang 3](http://www.baeldung.com/string-processing-commons-lang) - [Introduction to Javatuples](http://www.baeldung.com/java-tuples) - [Introduction to Javassist](http://www.baeldung.com/javassist) -- [Embedded Jetty Server in Java](http://www.baeldung.com/jetty-embedded) - [Introduction to Apache Flink with Java](http://www.baeldung.com/apache-flink) - [Introduction to JSONassert](http://www.baeldung.com/jsonassert) - [Intro to JaVers](http://www.baeldung.com/javers) - [Introduction to Apache Commons Math](http://www.baeldung.com/apache-commons-math) - [Intro to Serenity BDD](http://www.baeldung.com/serenity-bdd) -- [Introduction to Netty](http://www.baeldung.com/netty) - [Merging Streams in Java](http://www.baeldung.com/java-merge-streams) - [Serenity BDD and Screenplay](http://www.baeldung.com/serenity-screenplay) - [Introduction to Quartz](http://www.baeldung.com/quartz) @@ -35,7 +33,6 @@ - [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) - [Apache Commons IO](http://www.baeldung.com/apache-commons-io) - [Introduction to Conflict-Free Replicated Data Types](http://www.baeldung.com/java-conflict-free-replicated-data-types) @@ -55,10 +52,7 @@ - [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle) - [Guide to google-http-client](http://www.baeldung.com/google-http-client) - [Interact with Google Sheets from Java](http://www.baeldung.com/google-sheets-java-client) -- [Programatically Create, Configure, and Run a Tomcat Server](http://www.baeldung.com/tomcat-programmatic-setup) - [A Docker Guide for Java](http://www.baeldung.com/docker-java-api) -- [Exceptions in Netty](http://www.baeldung.com/netty-exception-handling) -- [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic) - [Introduction To OpenCSV](http://www.baeldung.com/opencsv) - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) - [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client) @@ -78,8 +72,15 @@ - [Publish and Receive Messages with Nats Java Client](http://www.baeldung.com/nats-java-client) - [Java Concurrency Utility with JCTools](http://www.baeldung.com/java-concurrency-jc-tools) - [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils) -- [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel) - +- [Creating REST Microservices with Javalin](http://www.baeldung.com/javalin-rest-microservices) +- [Introduction to JavaPoet](http://www.baeldung.com/java-poet) +- [Introduction to Joda-Time](http://www.baeldung.com/joda-time) +- [Implementing a FTP-Client in Java](http://www.baeldung.com/java-ftp-client) +- [Convert String to Date in Java](http://www.baeldung.com/java-string-to-date) +- [Histograms with Apache Commons Frequency](http://www.baeldung.com/apache-commons-frequency) +- [Guide to Resilience4j](http://www.baeldung.com/resilience4j) +- [Parsing YAML with SnakeYAML](http://www.baeldung.com/java-snake-yaml) +- [Guide to JMapper](http://www.baeldung.com/jmapper) 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 678ba3279c..1a88acfb7b 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -1,5 +1,6 @@ - + 4.0.0 libraries libraries @@ -67,7 +68,7 @@ tec.units unit-ri - 1.0.3 + ${unit-ri.version} org.apache.commons @@ -105,21 +106,6 @@ javers-core ${javers.version} - - org.eclipse.jetty - jetty-server - ${jetty.version} - - - org.eclipse.jetty - jetty-servlet - ${jetty.version} - - - org.eclipse.jetty - jetty-webapp - ${jetty.version} - io.nats @@ -135,7 +121,7 @@ io.specto hoverfly-java - 0.8.1 + ${hoverfly-java.version} org.apache.httpcomponents @@ -168,6 +154,17 @@ commons-dbutils ${commons.dbutils.version} + + org.apache.flink + flink-connector-kafka-0.11_2.11 + ${flink.version} + + + org.apache.flink + flink-streaming-java_2.11 + ${flink.version} + + org.apache.flink flink-core @@ -192,20 +189,26 @@ org.apache.flink - flink-test-utils_2.10 + flink-test-utils_2.11 ${flink.version} test org.apache.commons commons-math3 - 3.6.1 + ${common-math3.version} net.serenity-bdd serenity-core ${serenity.version} test + + + org.asciidoctor + asciidoctorj + + net.serenity-bdd @@ -236,46 +239,51 @@ jackson-databind ${jackson.version} + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson.version} + org.datanucleus javax.jdo - 3.2.0-m7 + ${javax.jdo.version} org.datanucleus datanucleus-core - 5.1.1 + ${datanucleus.version} org.datanucleus datanucleus-api-jdo - 5.1.1 + ${datanucleus.version} org.datanucleus datanucleus-rdbms - 5.1.1 + ${datanucleus.version} org.datanucleus datanucleus-maven-plugin - 5.0.2 + ${datanucleus-maven-plugin.version} org.datanucleus datanucleus-xml - 5.0.0-release + ${datanucleus-xml.version} org.datanucleus datanucleus-jdo-query - 5.0.2 + ${datanucleus-jdo-query.version} net.openhft chronicle - 3.6.4 + ${chronicle.version} com.sun.java @@ -286,7 +294,7 @@ org.springframework spring-web - 4.3.8.RELEASE + ${spring.version} net.serenity-bdd @@ -322,7 +330,7 @@ io.rest-assured spring-mock-mvc - 3.0.3 + ${spring-mock-mvc.version} test @@ -333,7 +341,7 @@ com.zaxxer HikariCP - 2.6.3 + ${HikariCP.version} compile @@ -350,7 +358,7 @@ org.quartz-scheduler quartz - 2.3.0 + ${quartz.version} one.util @@ -360,22 +368,17 @@ org.jooq jool - 0.9.12 + ${jool.version} org.openjdk.jmh jmh-core - 1.19 + ${jmh.version} org.openjdk.jmh jmh-generator-annprocess - 1.19 - - - io.netty - netty-all - ${netty.version} + ${jmh.version} junit @@ -397,7 +400,7 @@ org.codehaus.groovy groovy-all - 2.4.10 + ${groovy.version} org.awaitility @@ -440,7 +443,7 @@ com.machinezoo.noexception noexception - 1.1.0 + ${noexception.version} org.eclipse.collections @@ -472,18 +475,7 @@ com.squareup.okhttp3 logging-interceptor - 3.9.0 - - - com.darwinsys - hirondelle-date4j - RELEASE - test - - - joda-time - joda-time - ${joda-time.version} + ${logging-interceptor.version} com.darwinsys @@ -493,17 +485,17 @@ com.haulmont.yarg yarg - 2.0.4 + ${yarg.version} net.engio mbassador - 1.3.1 + ${mbassador.version} org.jdeferred jdeferred-core - 1.2.6 + ${jdeferred.version} com.codepoetics @@ -513,22 +505,22 @@ org.functionaljava functionaljava - 4.7 + ${functionaljava.version} org.functionaljava functionaljava-java8 - 4.7 + ${functionaljava.version} org.functionaljava functionaljava-quickcheck - 4.7 + ${functionaljava.version} org.functionaljava functionaljava-java-core - 4.7 + ${functionaljava.version} javax.cache @@ -543,7 +535,7 @@ org.jgrapht jgrapht-core - 1.0.1 + ${jgrapht.version} com.netopyr.wurmloch @@ -553,12 +545,12 @@ org.docx4j docx4j - 3.3.5 + ${docx4j.version} javax.xml.bind jaxb-api - 2.1 + ${jaxb-api.version} com.github.ben-manes.caffeine @@ -568,12 +560,12 @@ org.bouncycastle bcprov-jdk15on - 1.58 + ${bouncycastle.version} org.bouncycastle bcpkix-jdk15on - 1.58 + ${bouncycastle.version} com.google.http-client @@ -619,7 +611,7 @@ com.sun.jersey jersey-client - 1.19.4 + ${jersey.version} @@ -662,13 +654,7 @@ test test - - - - org.apache.tomcat - tomcat-catalina - ${tomcat.version} - + org.milyn milyn-smooks-all @@ -684,13 +670,13 @@ io.javalin javalin - 1.6.0 + ${javalin.version} io.atlassian.fugue fugue - 4.5.1 + ${fugue.version} @@ -698,6 +684,74 @@ jctools-core ${jctools.version} + + + + io.github.resilience4j + resilience4j-circuitbreaker + ${resilience4j.version} + + + io.github.resilience4j + resilience4j-ratelimiter + ${resilience4j.version} + + + io.github.resilience4j + resilience4j-bulkhead + ${resilience4j.version} + + + io.github.resilience4j + resilience4j-retry + ${resilience4j.version} + + + io.github.resilience4j + resilience4j-cache + ${resilience4j.version} + + + io.github.resilience4j + resilience4j-timelimiter + ${resilience4j.version} + + + org.knowm.xchart + xchart + ${xchart-version} + + + + commons-net + commons-net + ${commons-net.version} + + + org.mockftpserver + MockFtpServer + ${mockftpserver.version} + test + + + + com.squareup + javapoet + ${javapoet.version} + + + org.hamcrest + hamcrest-all + ${hamcrest-all.version} + test + + + + org.yaml + snakeyaml + ${snakeyaml.version} + + @@ -723,19 +777,6 @@ - - org.apache.maven.plugins - maven-dependency-plugin - - - org.apache.felix - maven-bundle-plugin - 3.3.0 - maven-plugin - - - true - maven-failsafe-plugin ${maven-failsafe-plugin.version} @@ -763,7 +804,7 @@ org.datanucleus datanucleus-maven-plugin - 5.0.2 + ${datanucleus-maven-plugin.version} JDO ${basedir}/datanucleus.properties @@ -785,7 +826,7 @@ org.apache.maven.plugins maven-jar-plugin - 3.0.2 + ${maven-jar-plugin.version} **/log4j.properties @@ -818,10 +859,7 @@ - + *:* META-INF/*.SF @@ -838,10 +876,11 @@ + 1.21 1.23.0 0.1.0 0.7.0 - 3.2.4 + 3.2.7 3.6 1.1 1.9.3 @@ -857,20 +896,18 @@ 2.5 1.6 1.4.196 - 9.4.8.v20171121 1.0 4.5.3 2.5 - 1.2.0 + 1.5.0 2.8.5 2.92 - 1.4.0 - 1.24.0 - 1.1.3-rc.5 - 1.4.0 + 1.9.26 + 1.41.0 + 1.9.0 + 1.9.27 1.1.0 - 4.1.20.Final 4.1 4.12 0.10 @@ -885,22 +922,20 @@ 0.6.5 0.9.0 15.2 - 2.9.9 1.5.1 2.3.0 - 2.9.9 + 2.10 1.5.1 - 1.14 + 1.15 1.0.3 1.0.0 - 3.8.4 + 3.10.2 2.5.5 1.23.0 v4-rev493-1.21.0 1.0.0 1.7.0 3.0.14 - 8.5.24 2.2.0 9.1.5.Final 4.1 @@ -910,6 +945,42 @@ 0.9.4.0006L 2.1.2 2.5.11 + 0.12.1 + 3.5.2 + 3.6 + 2.7.1 + 1.10.0 + 1.3 + 0.8.1 + 3.6.1 + 3.2.0-m7 + 5.1.1 + 5.0.2 + 5.0.0-release + 5.0.2 + 3.6.4 + 4.3.8.RELEASE + 3.0.3 + 2.6.3 + 2.3.0 + 0.9.12 + 1.19 + 2.4.10 + 1.1.0 + 3.9.0 + 2.0.4 + 1.3.1 + 1.2.6 + 4.7 + 1.0.1 + 3.3.5 + 2.1 + 1.58 + 1.19.4 + 1.6.0 + 4.5.1 + 3.3.0 + 3.0.2 - \ No newline at end of file + diff --git a/libraries/src/main/java/com/baeldung/commons/math3/Histogram.java b/libraries/src/main/java/com/baeldung/commons/math3/Histogram.java new file mode 100644 index 0000000000..a8c15887be --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/math3/Histogram.java @@ -0,0 +1,97 @@ +package com.baeldung.commons.math3; + +import org.apache.commons.math3.stat.Frequency; +import org.knowm.xchart.CategoryChart; +import org.knowm.xchart.CategoryChartBuilder; +import org.knowm.xchart.SwingWrapper; +import org.knowm.xchart.style.Styler; + +import java.util.*; + +public class Histogram { + + private Map distributionMap; + private int classWidth; + + public Histogram() { + + distributionMap = new TreeMap(); + classWidth = 10; + Map distributionMap = processRawData(); + List yData = new ArrayList(); + yData.addAll(distributionMap.values()); + List xData = Arrays.asList(distributionMap.keySet().toArray()); + + CategoryChart chart = buildChart(xData, yData); + new SwingWrapper<>(chart).displayChart(); + + } + + private CategoryChart buildChart(List xData, List yData) { + + // Create Chart + CategoryChart chart = new CategoryChartBuilder().width(800).height(600) + .title("Age Distribution") + .xAxisTitle("Age Group") + .yAxisTitle("Frequency") + .build(); + + chart.getStyler().setLegendPosition(Styler.LegendPosition.InsideNW); + chart.getStyler().setAvailableSpaceFill(0.99); + chart.getStyler().setOverlapped(true); + + chart.addSeries("age group", xData, yData); + + return chart; + } + + private Map processRawData() { + + List datasetList = Arrays.asList( + 36, 25, 38, 46, 55, 68, 72, + 55, 36, 38, 67, 45, 22, 48, + 91, 46, 52, 61, 58, 55); + Frequency frequency = new Frequency(); + datasetList.forEach(d -> frequency.addValue(Double.parseDouble(d.toString()))); + + datasetList.stream() + .map(d -> Double.parseDouble(d.toString())) + .distinct() + .forEach(observation -> { + long observationFrequency = frequency.getCount(observation); + int upperBoundary = (observation > classWidth) + ? Math.multiplyExact( (int) Math.ceil(observation / classWidth), classWidth) + : classWidth; + int lowerBoundary = (upperBoundary > classWidth) + ? Math.subtractExact(upperBoundary, classWidth) + : 0; + String bin = lowerBoundary + "-" + upperBoundary; + + updateDistributionMap(lowerBoundary, bin, observationFrequency); + + }); + + return distributionMap; + } + + private void updateDistributionMap(int lowerBoundary, String bin, long observationFrequency) { + + int prevLowerBoundary = (lowerBoundary > classWidth) ? lowerBoundary - classWidth : 0; + String prevBin = prevLowerBoundary + "-" + lowerBoundary; + if(!distributionMap.containsKey(prevBin)) + distributionMap.put(prevBin, 0); + + if(!distributionMap.containsKey(bin)) { + distributionMap.put(bin, observationFrequency); + } + else { + long oldFrequency = Long.parseLong(distributionMap.get(bin).toString()); + distributionMap.replace(bin, oldFrequency + observationFrequency); + } + } + + public static void main(String[] args) { + new Histogram(); + } + +} diff --git a/libraries/src/main/java/com/baeldung/flink/FlinkDataPipeline.java b/libraries/src/main/java/com/baeldung/flink/FlinkDataPipeline.java new file mode 100644 index 0000000000..d02b1bcb83 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/FlinkDataPipeline.java @@ -0,0 +1,82 @@ +package com.baeldung.flink; + + +import com.baeldung.flink.model.Backup; +import com.baeldung.flink.model.InputMessage; +import com.baeldung.flink.operator.BackupAggregator; +import com.baeldung.flink.operator.InputMessageTimestampAssigner; +import com.baeldung.flink.operator.WordsCapitalizer; +import org.apache.flink.streaming.api.TimeCharacteristic; +import org.apache.flink.streaming.api.datastream.DataStream; +import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; +import org.apache.flink.streaming.api.windowing.time.Time; +import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer011; +import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer011; + +import static com.baeldung.flink.connector.Consumers.*; +import static com.baeldung.flink.connector.Producers.*; + +public class FlinkDataPipeline { + + public static void capitalize() throws Exception { + String inputTopic = "flink_input"; + String outputTopic = "flink_output"; + String consumerGroup = "baeldung"; + String address = "localhost:9092"; + + StreamExecutionEnvironment environment = + StreamExecutionEnvironment.getExecutionEnvironment(); + + FlinkKafkaConsumer011 flinkKafkaConsumer = + createStringConsumerForTopic(inputTopic, address, consumerGroup); + flinkKafkaConsumer.setStartFromEarliest(); + + DataStream stringInputStream = + environment.addSource(flinkKafkaConsumer); + + FlinkKafkaProducer011 flinkKafkaProducer = + createStringProducer(outputTopic, address); + + stringInputStream + .map(new WordsCapitalizer()) + .addSink(flinkKafkaProducer); + + environment.execute(); + } + +public static void createBackup () throws Exception { + String inputTopic = "flink_input"; + String outputTopic = "flink_output"; + String consumerGroup = "baeldung"; + String kafkaAddress = "localhost:9092"; + + StreamExecutionEnvironment environment = + StreamExecutionEnvironment.getExecutionEnvironment(); + + environment.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); + + FlinkKafkaConsumer011 flinkKafkaConsumer = + createInputMessageConsumer(inputTopic, kafkaAddress, consumerGroup); + flinkKafkaConsumer.setStartFromEarliest(); + + flinkKafkaConsumer + .assignTimestampsAndWatermarks(new InputMessageTimestampAssigner()); + FlinkKafkaProducer011 flinkKafkaProducer = + createBackupProducer(outputTopic, kafkaAddress); + + DataStream inputMessagesStream = + environment.addSource(flinkKafkaConsumer); + + inputMessagesStream + .timeWindowAll(Time.hours(24)) + .aggregate(new BackupAggregator()) + .addSink(flinkKafkaProducer); + + environment.execute(); +} + + public static void main(String[] args) throws Exception { + createBackup(); + } + +} diff --git a/libraries/src/main/java/com/baeldung/flink/connector/Consumers.java b/libraries/src/main/java/com/baeldung/flink/connector/Consumers.java new file mode 100644 index 0000000000..514085f9c4 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/connector/Consumers.java @@ -0,0 +1,32 @@ +package com.baeldung.flink.connector; + +import com.baeldung.flink.model.InputMessage; +import com.baeldung.flink.schema.InputMessageDeserializationSchema; +import org.apache.flink.api.common.serialization.SimpleStringSchema; +import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer011; + +import java.util.Properties; + +public class Consumers { + +public static FlinkKafkaConsumer011 createStringConsumerForTopic( + String topic, String kafkaAddress, String kafkaGroup ) { + Properties props = new Properties(); + props.setProperty("bootstrap.servers", kafkaAddress); + props.setProperty("group.id",kafkaGroup); + FlinkKafkaConsumer011 consumer = + new FlinkKafkaConsumer011<>(topic, new SimpleStringSchema(),props); + + return consumer; +} + + public static FlinkKafkaConsumer011 createInputMessageConsumer(String topic, String kafkaAddress, String kafkaGroup ) { + Properties properties = new Properties(); + properties.setProperty("bootstrap.servers", kafkaAddress); + properties.setProperty("group.id",kafkaGroup); + FlinkKafkaConsumer011 consumer = new FlinkKafkaConsumer011( + topic, new InputMessageDeserializationSchema(),properties); + + return consumer; + } +} diff --git a/libraries/src/main/java/com/baeldung/flink/connector/Producers.java b/libraries/src/main/java/com/baeldung/flink/connector/Producers.java new file mode 100644 index 0000000000..8e6f3f8f37 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/connector/Producers.java @@ -0,0 +1,17 @@ +package com.baeldung.flink.connector; + +import com.baeldung.flink.model.Backup; +import com.baeldung.flink.schema.BackupSerializationSchema; +import org.apache.flink.api.common.serialization.SimpleStringSchema; +import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer011; + +public class Producers { + + public static FlinkKafkaProducer011 createStringProducer(String topic, String kafkaAddress) { + return new FlinkKafkaProducer011<>(kafkaAddress, topic, new SimpleStringSchema()); + } + + public static FlinkKafkaProducer011 createBackupProducer(String topic, String kafkaAddress) { + return new FlinkKafkaProducer011(kafkaAddress, topic, new BackupSerializationSchema()); + } +} diff --git a/libraries/src/main/java/com/baeldung/flink/model/Backup.java b/libraries/src/main/java/com/baeldung/flink/model/Backup.java new file mode 100644 index 0000000000..268ceec7f3 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/model/Backup.java @@ -0,0 +1,27 @@ +package com.baeldung.flink.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.UUID; + +public class Backup { + + @JsonProperty("inputMessages") + List inputMessages; + @JsonProperty("backupTimestamp") + LocalDateTime backupTimestamp; + @JsonProperty("uuid") + UUID uuid; + + public Backup(List inputMessages, LocalDateTime backupTimestamp) { + this.inputMessages = inputMessages; + this.backupTimestamp = backupTimestamp; + this.uuid = UUID.randomUUID(); + } + + public List getInputMessages() { + return inputMessages; + } +} diff --git a/libraries/src/main/java/com/baeldung/flink/model/InputMessage.java b/libraries/src/main/java/com/baeldung/flink/model/InputMessage.java new file mode 100644 index 0000000000..183fa69c11 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/model/InputMessage.java @@ -0,0 +1,72 @@ +package com.baeldung.flink.model; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.google.common.base.Objects; + +import java.time.LocalDateTime; + +@JsonSerialize +public class InputMessage { + String sender; + String recipient; + LocalDateTime sentAt; + String message; + + public InputMessage() { + } + + public String getSender() { + return sender; + } + + public void setSender(String sender) { + this.sender = sender; + } + + public String getRecipient() { + return recipient; + } + + public void setRecipient(String recipient) { + this.recipient = recipient; + } + + public LocalDateTime getSentAt() { + return sentAt; + } + + public void setSentAt(LocalDateTime sentAt) { + this.sentAt = sentAt; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public InputMessage(String sender, String recipient, LocalDateTime sentAt, String message) { + this.sender = sender; + this.recipient = recipient; + this.sentAt = sentAt; + this.message = message; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + InputMessage message1 = (InputMessage) o; + return Objects.equal(sender, message1.sender) && + Objects.equal(recipient, message1.recipient) && + Objects.equal(sentAt, message1.sentAt) && + Objects.equal(message, message1.message); + } + + @Override + public int hashCode() { + return Objects.hashCode(sender, recipient, sentAt, message); + } +} diff --git a/libraries/src/main/java/com/baeldung/flink/operator/BackupAggregator.java b/libraries/src/main/java/com/baeldung/flink/operator/BackupAggregator.java new file mode 100644 index 0000000000..c39b8413d1 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/operator/BackupAggregator.java @@ -0,0 +1,34 @@ +package com.baeldung.flink.operator; + +import com.baeldung.flink.model.Backup; +import com.baeldung.flink.model.InputMessage; +import org.apache.flink.api.common.functions.AggregateFunction; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + + public class BackupAggregator implements AggregateFunction, Backup> { + @Override + public List createAccumulator() { + return new ArrayList<>(); + } + + @Override + public List add(InputMessage inputMessage, List inputMessages) { + inputMessages.add(inputMessage); + return inputMessages; + } + + @Override + public Backup getResult(List inputMessages) { + Backup backup = new Backup(inputMessages, LocalDateTime.now()); + return backup; + } + + @Override + public List merge(List inputMessages, List acc1) { + inputMessages.addAll(acc1); + return inputMessages; + } + } diff --git a/libraries/src/main/java/com/baeldung/flink/operator/InputMessageTimestampAssigner.java b/libraries/src/main/java/com/baeldung/flink/operator/InputMessageTimestampAssigner.java new file mode 100644 index 0000000000..05828d9588 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/operator/InputMessageTimestampAssigner.java @@ -0,0 +1,23 @@ +package com.baeldung.flink.operator; + +import com.baeldung.flink.model.InputMessage; +import org.apache.flink.streaming.api.functions.AssignerWithPunctuatedWatermarks; +import org.apache.flink.streaming.api.watermark.Watermark; + +import javax.annotation.Nullable; +import java.time.ZoneId; + +public class InputMessageTimestampAssigner implements AssignerWithPunctuatedWatermarks { + + @Override + public long extractTimestamp(InputMessage element, long previousElementTimestamp) { + ZoneId zoneId = ZoneId.systemDefault(); + return element.getSentAt().atZone(zoneId).toEpochSecond() * 1000; + } + + @Nullable + @Override + public Watermark checkAndGetNextWatermark(InputMessage lastElement, long extractedTimestamp) { + return new Watermark(extractedTimestamp - 15); + } +} diff --git a/libraries/src/main/java/com/baeldung/flink/operator/WordsCapitalizer.java b/libraries/src/main/java/com/baeldung/flink/operator/WordsCapitalizer.java new file mode 100644 index 0000000000..f9103d225c --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/operator/WordsCapitalizer.java @@ -0,0 +1,11 @@ +package com.baeldung.flink.operator; + +import org.apache.flink.api.common.functions.MapFunction; + +public class WordsCapitalizer implements MapFunction { + + @Override + public String map(String s) { + return s.toUpperCase(); + } +} diff --git a/libraries/src/main/java/com/baeldung/flink/schema/BackupSerializationSchema.java b/libraries/src/main/java/com/baeldung/flink/schema/BackupSerializationSchema.java new file mode 100644 index 0000000000..967b266bb6 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/schema/BackupSerializationSchema.java @@ -0,0 +1,33 @@ +package com.baeldung.flink.schema; + +import com.baeldung.flink.model.Backup; +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.apache.flink.api.common.serialization.SerializationSchema; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class BackupSerializationSchema + implements SerializationSchema { + + static ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()); + + Logger logger = LoggerFactory.getLogger(BackupSerializationSchema.class); + + @Override + public byte[] serialize(Backup backupMessage) { + if(objectMapper == null) { + objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); + objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()); + } + try { + String json = objectMapper.writeValueAsString(backupMessage); + return json.getBytes(); + } catch (com.fasterxml.jackson.core.JsonProcessingException e) { + logger.error("Failed to parse JSON", e); + } + return new byte[0]; + } +} diff --git a/libraries/src/main/java/com/baeldung/flink/schema/InputMessageDeserializationSchema.java b/libraries/src/main/java/com/baeldung/flink/schema/InputMessageDeserializationSchema.java new file mode 100644 index 0000000000..1df456bbe5 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/flink/schema/InputMessageDeserializationSchema.java @@ -0,0 +1,34 @@ +package com.baeldung.flink.schema; + +import com.baeldung.flink.model.InputMessage; +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.apache.flink.api.common.serialization.DeserializationSchema; +import org.apache.flink.api.common.typeinfo.TypeInformation; + +import java.io.IOException; + +public class InputMessageDeserializationSchema implements + DeserializationSchema { + + static ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()); + + + @Override + public InputMessage deserialize(byte[] bytes) throws IOException { + + return objectMapper.readValue(bytes, InputMessage.class); + } + + @Override + public boolean isEndOfStream(InputMessage inputMessage) { + return false; + } + + @Override + public TypeInformation getProducedType() { + return TypeInformation.of(InputMessage.class); + } +} diff --git a/libraries/src/main/java/com/baeldung/ftp/FtpClient.java b/libraries/src/main/java/com/baeldung/ftp/FtpClient.java new file mode 100644 index 0000000000..209bed35f0 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/ftp/FtpClient.java @@ -0,0 +1,63 @@ +package com.baeldung.ftp; + +import org.apache.commons.net.PrintCommandListener; +import org.apache.commons.net.ftp.FTPClient; +import org.apache.commons.net.ftp.FTPFile; +import org.apache.commons.net.ftp.FTPReply; + +import java.io.*; +import java.util.Arrays; +import java.util.Collection; +import java.util.stream.Collectors; + +class FtpClient { + + private final String server; + private final int port; + private final String user; + private final String password; + private FTPClient ftp; + + FtpClient(String server, int port, String user, String password) { + this.server = server; + this.port = port; + this.user = user; + this.password = password; + } + + void open() throws IOException { + ftp = new FTPClient(); + + ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); + + ftp.connect(server, port); + int reply = ftp.getReplyCode(); + if (!FTPReply.isPositiveCompletion(reply)) { + ftp.disconnect(); + throw new IOException("Exception in connecting to FTP Server"); + } + + ftp.login(user, password); + } + + void close() throws IOException { + ftp.disconnect(); + } + + Collection listFiles(String path) throws IOException { + FTPFile[] files = ftp.listFiles(path); + + return Arrays.stream(files) + .map(FTPFile::getName) + .collect(Collectors.toList()); + } + + void putFileToPath(File file, String path) throws IOException { + ftp.storeFile(path, new FileInputStream(file)); + } + + void downloadFile(String source, String destination) throws IOException { + FileOutputStream out = new FileOutputStream(destination); + ftp.retrieveFile(source, out); + } +} diff --git a/libraries/src/main/java/com/baeldung/javalin/User/UserController.java b/libraries/src/main/java/com/baeldung/javalin/User/UserController.java index fd713606cf..685890c6d7 100644 --- a/libraries/src/main/java/com/baeldung/javalin/User/UserController.java +++ b/libraries/src/main/java/com/baeldung/javalin/User/UserController.java @@ -14,7 +14,7 @@ public class UserController { public static Handler fetchById = ctx -> { int id = Integer.parseInt(Objects.requireNonNull(ctx.param("id"))); UserDao dao = UserDao.instance(); - User user = dao.getUserById(id); + User user = dao.getUserById(id).get(); if (user == null) { ctx.html("Not Found"); } else { diff --git a/libraries/src/main/java/com/baeldung/javapoet/PersonGenerator.java b/libraries/src/main/java/com/baeldung/javapoet/PersonGenerator.java new file mode 100644 index 0000000000..6dd41cc0bd --- /dev/null +++ b/libraries/src/main/java/com/baeldung/javapoet/PersonGenerator.java @@ -0,0 +1,183 @@ +package com.baeldung.javapoet; + +import com.squareup.javapoet.ClassName; +import com.squareup.javapoet.CodeBlock; +import com.squareup.javapoet.FieldSpec; +import com.squareup.javapoet.JavaFile; +import com.squareup.javapoet.MethodSpec; +import com.squareup.javapoet.ParameterSpec; +import com.squareup.javapoet.ParameterizedTypeName; +import com.squareup.javapoet.TypeName; +import com.squareup.javapoet.TypeSpec; + +import javax.lang.model.element.Modifier; +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.stream.IntStream; + +public class PersonGenerator { + + private static final String FOUR_WHITESPACES = " "; + private static final String PERSON_PACKAGE_NAME = "com.baeldung.javapoet.test.person"; + + private File outputFile; + + public PersonGenerator() { + outputFile = new File(getOutputPath().toUri()); + } + + public static String getPersonPackageName() { + return PERSON_PACKAGE_NAME; + } + + public Path getOutputPath() { + return Paths.get(new File(".").getAbsolutePath() + "/gensrc"); + } + + public FieldSpec getDefaultNameField() { + return FieldSpec + .builder(String.class, "DEFAULT_NAME") + .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL) + .initializer("$S", "Alice") + .build(); + } + + public MethodSpec getSortByLengthMethod() { + return MethodSpec + .methodBuilder("sortByLength") + .addModifiers(Modifier.PUBLIC, Modifier.STATIC) + .addParameter(ParameterSpec + .builder(ParameterizedTypeName.get(ClassName.get(List.class), TypeName.get(String.class)), "strings") + .build()) + .addStatement("$T.sort($N, $L)", Collections.class, "strings", getComparatorAnonymousClass()) + .build(); + } + + public MethodSpec getPrintNameMultipleTimesMethod() { + return MethodSpec + .methodBuilder("printNameMultipleTimes") + .addModifiers(Modifier.PUBLIC) + .addCode(getPrintNameMultipleTimesLambdaImpl()) + .build(); + } + + public CodeBlock getPrintNameMultipleTimesImpl() { + return CodeBlock + .builder() + .beginControlFlow("for (int i = $L; i < $L; i++)") + .addStatement("System.out.println(name)") + .endControlFlow() + .build(); + } + + public CodeBlock getPrintNameMultipleTimesLambdaImpl() { + return CodeBlock + .builder() + .addStatement("$T<$T> names = new $T<>()", List.class, String.class, ArrayList.class) + .addStatement("$T.range($L, $L).forEach(i -> names.add(name))", IntStream.class, 0, 10) + .addStatement("names.forEach(System.out::println)") + .build(); + } + + public TypeSpec getGenderEnum() { + return TypeSpec + .enumBuilder("Gender") + .addModifiers(Modifier.PUBLIC) + .addEnumConstant("MALE") + .addEnumConstant("FEMALE") + .addEnumConstant("UNSPECIFIED") + .build(); + } + + public TypeSpec getPersonInterface() { + return TypeSpec + .interfaceBuilder("Person") + .addModifiers(Modifier.PUBLIC) + .addField(getDefaultNameField()) + .addMethod(MethodSpec + .methodBuilder("getName") + .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) + .returns(String.class) + .build()) + .addMethod(MethodSpec + .methodBuilder("getDefaultName") + .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT) + .returns(String.class) + .addCode(CodeBlock + .builder() + .addStatement("return DEFAULT_NAME") + .build()) + .build()) + .build(); + } + + public TypeSpec getStudentClass() { + return TypeSpec + .classBuilder("Student") + .addSuperinterface(ClassName.get(PERSON_PACKAGE_NAME, "Person")) + .addModifiers(Modifier.PUBLIC) + .addField(FieldSpec + .builder(String.class, "name") + .addModifiers(Modifier.PRIVATE) + .build()) + .addMethod(MethodSpec + .methodBuilder("getName") + .addAnnotation(Override.class) + .addModifiers(Modifier.PUBLIC) + .returns(String.class) + .addStatement("return this.name") + .build()) + .addMethod(MethodSpec + .methodBuilder("setName") + .addParameter(String.class, "name") + .addModifiers(Modifier.PUBLIC) + .addStatement("this.name = name") + .build()) + .addMethod(getPrintNameMultipleTimesMethod()) + .addMethod(getSortByLengthMethod()) + .build(); + } + + public TypeSpec getComparatorAnonymousClass() { + return TypeSpec + .anonymousClassBuilder("") + .addSuperinterface(ParameterizedTypeName.get(Comparator.class, String.class)) + .addMethod(MethodSpec + .methodBuilder("compare") + .addModifiers(Modifier.PUBLIC) + .addAnnotation(Override.class) + .addParameter(String.class, "a") + .addParameter(String.class, "b") + .returns(int.class) + .addStatement("return a.length() - b.length()") + .build()) + .build(); + } + + public void generateGenderEnum() throws IOException { + writeToOutputFile(getPersonPackageName(), getGenderEnum()); + } + + public void generatePersonInterface() throws IOException { + writeToOutputFile(getPersonPackageName(), getPersonInterface()); + } + + public void generateStudentClass() throws IOException { + writeToOutputFile(getPersonPackageName(), getStudentClass()); + } + + private void writeToOutputFile(String packageName, TypeSpec typeSpec) throws IOException { + JavaFile javaFile = JavaFile + .builder(packageName, typeSpec) + .indent(FOUR_WHITESPACES) + .build(); + javaFile.writeTo(outputFile); + } + +} diff --git a/libraries/src/main/java/com/baeldung/snakeyaml/Address.java b/libraries/src/main/java/com/baeldung/snakeyaml/Address.java new file mode 100644 index 0000000000..83c327a4ed --- /dev/null +++ b/libraries/src/main/java/com/baeldung/snakeyaml/Address.java @@ -0,0 +1,41 @@ +package com.baeldung.snakeyaml; + +public class Address { + private String line; + private String city; + private String state; + private Integer zip; + + public String getLine() { + return line; + } + + public void setLine(String line) { + this.line = line; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public Integer getZip() { + return zip; + } + + public void setZip(Integer zip) { + this.zip = zip; + } + +} diff --git a/libraries/src/main/java/com/baeldung/snakeyaml/Contact.java b/libraries/src/main/java/com/baeldung/snakeyaml/Contact.java new file mode 100644 index 0000000000..a808747786 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/snakeyaml/Contact.java @@ -0,0 +1,26 @@ +package com.baeldung.snakeyaml; + +public class Contact { + + private String type; + + private int number; + + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public int getNumber() { + return number; + } + + public void setNumber(int number) { + this.number = number; + } + +} diff --git a/libraries/src/main/java/com/baeldung/snakeyaml/Customer.java b/libraries/src/main/java/com/baeldung/snakeyaml/Customer.java new file mode 100644 index 0000000000..c741f6dc85 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/snakeyaml/Customer.java @@ -0,0 +1,53 @@ +package com.baeldung.snakeyaml; + +import java.util.List; + +public class Customer { + + private String firstName; + private String lastName; + private int age; + private List contactDetails; + private Address homeAddress; + + 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 int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public List getContactDetails() { + return contactDetails; + } + + public void setContactDetails(List contactDetails) { + this.contactDetails = contactDetails; + } + + public Address getHomeAddress() { + return homeAddress; + } + + public void setHomeAddress(Address homeAddress) { + this.homeAddress = homeAddress; + } + +} diff --git a/libraries/src/main/resources/logback.xml b/libraries/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/libraries/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/atlassian/fugue/FugueTest.java b/libraries/src/test/java/com/baeldung/atlassian/fugue/FugueTest.java deleted file mode 100644 index 2ba1086226..0000000000 --- a/libraries/src/test/java/com/baeldung/atlassian/fugue/FugueTest.java +++ /dev/null @@ -1,231 +0,0 @@ -package com.baeldung.atlassian.fugue; - -import io.atlassian.fugue.*; -import org.junit.Assert; -import org.junit.Test; - -import java.util.*; -import java.util.function.Function; - -import static org.junit.Assert.*; -import static io.atlassian.fugue.Unit.Unit; - -public class FugueTest { - - @Test - public void whenSome_thenDefined() { - Option some = Option.some("value"); - - assertTrue(some.isDefined()); - assertEquals("value", some.get()); - } - - @Test - public void whenNone_thenNotDefined() { - Option none = Option.none(); - - assertFalse(none.isDefined()); - assertEquals(1, none.getOrElse(1)); - } - - @Test - public void whenSomeNull_thenException() { - try { - Option.some(null); - - fail("some(null) should throw"); - } catch (NullPointerException e) { - //Expected - } - } - - @Test - public void whenNullOption_thenSome() { - Option some = Option.some("value") .map(String::toUpperCase); - - assertEquals("VALUE", some.get()); - - some = some.map(x -> null); - - assertNull(some.get()); - some.forEach(Assert::assertNull); - for(Object value : some) { - assertNull(value); - } - assertEquals(1, some.toStream().count()); - - Option none = Option.some("value").flatMap(x -> Option.none()); - - assertFalse(none.isDefined()); - - none = Option.some("value").flatMap(Options.nullSafe(x -> null)); - - assertFalse(none.isDefined()); - } - - @Test - public void whenNone_thenEmptyOptional() { - Optional optional = Option.none().toOptional(); - - assertFalse(optional.isPresent()); - assertTrue(Option.fromOptional(optional).isEmpty()); - } - - @Test - public void whenOption_thenIterable() { - Option some = Option.some("value"); - Iterable strings = Iterables.concat(some, Arrays.asList("a", "b", "c")); - List stringList = new ArrayList<>(); - Iterables.addAll(stringList, strings); - - assertEquals(4, stringList.size()); - } - - @Test - public void whenOption_thenStream() { - assertEquals(0, Option.none().toStream().count()); - assertEquals(1, Option.some("value").toStream().count()); - } - - @Test - public void whenLift_thenPartialFunction() { - Function f = (Integer x) -> x > 0 ? x + 1 : null; - Function, Option> lifted = Options.lift(f); - - assertEquals(2, (long) lifted.apply(Option.some(1)).get()); - assertTrue(lifted.apply(Option.none()).isEmpty()); - assertEquals(null, lifted.apply(Option.some(0)).get()); - } - - @Test - - public void whenLeft_thenEither() { - Either right = Either.right("value"); - Either left = Either.left(-1); - if(right.isLeft()) { - fail(); - } - if(left.isRight()) { - fail(); - } - - String s = right.map(String::toUpperCase).getOrNull(); - - assertEquals("VALUE", s); - - Either either = right.left().map(x -> decodeSQLErrorCode(x)); - - assertTrue(either.isRight()); - assertEquals("value", either.right().get()); - - either.right().forEach(x -> assertEquals("value", x)); - } - - private static String decodeSQLErrorCode(Integer x) { - return "error"; - } - - @Test - public void whenTryIsFailure_thenIsFailureReturnsTrue() { - assertTrue(Try.failure(new Exception("Fail!")).isFailure()); - } - - @Test - public void whenTryIsSuccess_thenIsSuccessReturnsTrue() { - assertTrue(Try.successful("OK").isSuccess()); - } - - @Test - public void givenFunctionReturning_whenCheckedOf_thenSuccess() { - assertTrue(Checked.of(() -> "ok").isSuccess()); - } - - @Test - public void givenFunctionThrowing_whenCheckedOf_thenFailure() { - assertTrue(Checked.of(() -> { throw new Exception("ko"); }).isFailure()); - } - - @Test - public void givenFunctionThrowing_whenCheckedLift_thenFailure() { - Checked.Function throwException = (String x) -> { - throw new Exception(x); - }; - - assertTrue(Checked.lift(throwException).apply("ko").isFailure()); - } - - @Test - public void whenRecover_thenSuccessfulTry() { - Try recover = Try. - failure(new Exception("boo!")). - recover((Exception e) -> e.getMessage() + " recovered."); - - assertTrue(recover.isSuccess()); - assertEquals("boo! recovered.", recover.getOrElse(() -> null)); - - recover = Try. - failure(new Exception("boo!")). - recoverWith((Exception e) -> Try.successful("recovered again!")); - - assertTrue(recover.isSuccess()); - assertEquals("recovered again!", recover.getOrElse(() -> null)); - } - - - @Test - public void whenFailure_thenMapNotCalled() { - Try recover = Try.failure(new Exception("boo!")).map(x -> { - fail("Oh, no!"); - return null; - }).recover(Function.identity()); - Exception exception = (Exception) recover.toOption().get(); - - assertTrue(recover.isSuccess()); - assertEquals("boo!", exception.getMessage()); - } - - @Test - public void whenException_thenTryThrows() { - Try checked = Checked.of(() -> { - throw new Exception("Aaargh!"); - }); - Either either = checked.toEither(); - - assertTrue(checked.isFailure()); - assertTrue(either.isLeft()); - assertEquals(42, checked.getOrElse(() -> 42)); - - try { - checked.getOrElse(() -> { - throw new NoSuchElementException("fail"); - }); - - fail("Was expecting exception"); - } catch (Exception e) { - assertEquals("fail", e.getMessage()); - } - } - - @Test - public void whenRecoverThrows_thenFailure() { - Try failure = Try.failure(new Exception("boo!")).recover(x -> { - throw new RuntimeException(x); - }); - - assertTrue(failure.isFailure()); - } - - Unit doSomething() { - System.out.println("Hello! Side effect"); - return Unit(); - } - - @Test - public void whenPair_thenLeftAndRight() { - Pair pair = Pair.pair(1, "a"); - - assertEquals(1, (int) pair.left()); - assertEquals("a", pair.right()); - } - -} diff --git a/libraries/src/test/java/com/baeldung/atlassian/fugue/FugueUnitTest.java b/libraries/src/test/java/com/baeldung/atlassian/fugue/FugueUnitTest.java new file mode 100644 index 0000000000..773e39b76a --- /dev/null +++ b/libraries/src/test/java/com/baeldung/atlassian/fugue/FugueUnitTest.java @@ -0,0 +1,231 @@ +package com.baeldung.atlassian.fugue; + +import io.atlassian.fugue.*; +import org.junit.Assert; +import org.junit.Test; + +import java.util.*; +import java.util.function.Function; + +import static org.junit.Assert.*; +import static io.atlassian.fugue.Unit.Unit; + +public class FugueUnitTest { + + @Test + public void whenSome_thenDefined() { + Option some = Option.some("value"); + + assertTrue(some.isDefined()); + assertEquals("value", some.get()); + } + + @Test + public void whenNone_thenNotDefined() { + Option none = Option.none(); + + assertFalse(none.isDefined()); + assertEquals(1, none.getOrElse(1)); + } + + @Test + public void whenSomeNull_thenException() { + try { + Option.some(null); + + fail("some(null) should throw"); + } catch (NullPointerException e) { + //Expected + } + } + + @Test + public void whenNullOption_thenSome() { + Option some = Option.some("value") .map(String::toUpperCase); + + assertEquals("VALUE", some.get()); + + some = some.map(x -> null); + + assertNull(some.get()); + some.forEach(Assert::assertNull); + for(Object value : some) { + assertNull(value); + } + assertEquals(1, some.toStream().count()); + + Option none = Option.some("value").flatMap(x -> Option.none()); + + assertFalse(none.isDefined()); + + none = Option.some("value").flatMap(Options.nullSafe(x -> null)); + + assertFalse(none.isDefined()); + } + + @Test + public void whenNone_thenEmptyOptional() { + Optional optional = Option.none().toOptional(); + + assertFalse(optional.isPresent()); + assertTrue(Option.fromOptional(optional).isEmpty()); + } + + @Test + public void whenOption_thenIterable() { + Option some = Option.some("value"); + Iterable strings = Iterables.concat(some, Arrays.asList("a", "b", "c")); + List stringList = new ArrayList<>(); + Iterables.addAll(stringList, strings); + + assertEquals(4, stringList.size()); + } + + @Test + public void whenOption_thenStream() { + assertEquals(0, Option.none().toStream().count()); + assertEquals(1, Option.some("value").toStream().count()); + } + + @Test + public void whenLift_thenPartialFunction() { + Function f = (Integer x) -> x > 0 ? x + 1 : null; + Function, Option> lifted = Options.lift(f); + + assertEquals(2, (long) lifted.apply(Option.some(1)).get()); + assertTrue(lifted.apply(Option.none()).isEmpty()); + assertEquals(null, lifted.apply(Option.some(0)).get()); + } + + @Test + + public void whenLeft_thenEither() { + Either right = Either.right("value"); + Either left = Either.left(-1); + if(right.isLeft()) { + fail(); + } + if(left.isRight()) { + fail(); + } + + String s = right.map(String::toUpperCase).getOrNull(); + + assertEquals("VALUE", s); + + Either either = right.left().map(x -> decodeSQLErrorCode(x)); + + assertTrue(either.isRight()); + assertEquals("value", either.right().get()); + + either.right().forEach(x -> assertEquals("value", x)); + } + + private static String decodeSQLErrorCode(Integer x) { + return "error"; + } + + @Test + public void whenTryIsFailure_thenIsFailureReturnsTrue() { + assertTrue(Try.failure(new Exception("Fail!")).isFailure()); + } + + @Test + public void whenTryIsSuccess_thenIsSuccessReturnsTrue() { + assertTrue(Try.successful("OK").isSuccess()); + } + + @Test + public void givenFunctionReturning_whenCheckedOf_thenSuccess() { + assertTrue(Checked.of(() -> "ok").isSuccess()); + } + + @Test + public void givenFunctionThrowing_whenCheckedOf_thenFailure() { + assertTrue(Checked.of(() -> { throw new Exception("ko"); }).isFailure()); + } + + @Test + public void givenFunctionThrowing_whenCheckedLift_thenFailure() { + Checked.Function throwException = (String x) -> { + throw new Exception(x); + }; + + assertTrue(Checked.lift(throwException).apply("ko").isFailure()); + } + + @Test + public void whenRecover_thenSuccessfulTry() { + Try recover = Try. + failure(new Exception("boo!")). + recover((Exception e) -> e.getMessage() + " recovered."); + + assertTrue(recover.isSuccess()); + assertEquals("boo! recovered.", recover.getOrElse(() -> null)); + + recover = Try. + failure(new Exception("boo!")). + recoverWith((Exception e) -> Try.successful("recovered again!")); + + assertTrue(recover.isSuccess()); + assertEquals("recovered again!", recover.getOrElse(() -> null)); + } + + + @Test + public void whenFailure_thenMapNotCalled() { + Try recover = Try.failure(new Exception("boo!")).map(x -> { + fail("Oh, no!"); + return null; + }).recover(Function.identity()); + Exception exception = (Exception) recover.toOption().get(); + + assertTrue(recover.isSuccess()); + assertEquals("boo!", exception.getMessage()); + } + + @Test + public void whenException_thenTryThrows() { + Try checked = Checked.of(() -> { + throw new Exception("Aaargh!"); + }); + Either either = checked.toEither(); + + assertTrue(checked.isFailure()); + assertTrue(either.isLeft()); + assertEquals(42, checked.getOrElse(() -> 42)); + + try { + checked.getOrElse(() -> { + throw new NoSuchElementException("fail"); + }); + + fail("Was expecting exception"); + } catch (Exception e) { + assertEquals("fail", e.getMessage()); + } + } + + @Test + public void whenRecoverThrows_thenFailure() { + Try failure = Try.failure(new Exception("boo!")).recover(x -> { + throw new RuntimeException(x); + }); + + assertTrue(failure.isFailure()); + } + + Unit doSomething() { + System.out.println("Hello! Side effect"); + return Unit(); + } + + @Test + public void whenPair_thenLeftAndRight() { + Pair pair = Pair.pair(1, "a"); + + assertEquals(1, (int) pair.left()); + assertEquals("a", pair.right()); + } + +} diff --git a/libraries/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueTest.java b/libraries/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueTest.java deleted file mode 100644 index 9f670af03c..0000000000 --- a/libraries/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueTest.java +++ /dev/null @@ -1,159 +0,0 @@ -package com.baeldung.circularfifoqueue; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.collections4.queue.CircularFifoQueue; -import org.junit.Assert; -import org.junit.Test; - -public class CircularFifoQueueTest { - - private static final int DEFAULT_SIZE = 32; - - private static final int FIXED_SIZE = 5; - - private static final int COLLECTION_SIZE = 7; - - private static final String TEST_COLOR = "Red"; - - private static final String TEST_COLOR_BY_INDEX = "Blue"; - - @Test - public void whenUsingDefualtConstructor_correctSizeQueue() { - CircularFifoQueue bits = new CircularFifoQueue<>(); - - Assert.assertEquals(DEFAULT_SIZE, bits.maxSize()); - } - - @Test - public void givenAddElements_whenUsingIntConstructor_correctSizeQueue() { - CircularFifoQueue colors = new CircularFifoQueue<>(5); - colors.add("Red"); - colors.add("Blue"); - colors.add("Green"); - colors.offer("White"); - colors.offer("Black"); - - Assert.assertEquals(FIXED_SIZE, colors.maxSize()); - } - - @Test - public void whenUsingCollectionConstructor_correctSizeQueue() { - List days = new ArrayList<>(); - days.add("Monday"); - days.add("Tuesday"); - days.add("Wednesday"); - days.add("Thursday"); - days.add("Friday"); - days.add("Saturday"); - days.add("Sunday"); - - CircularFifoQueue daysOfWeek = new CircularFifoQueue<>(days); - - Assert.assertEquals(COLLECTION_SIZE, daysOfWeek.maxSize()); - } - - @Test - public void givenAddElements_whenGetElement_correctElement() { - CircularFifoQueue colors = new CircularFifoQueue<>(5); - colors.add("Red"); - colors.add("Blue"); - colors.add("Green"); - colors.offer("White"); - colors.offer("Black"); - - Assert.assertEquals(TEST_COLOR_BY_INDEX, colors.get(1)); - } - - @Test - public void givenAddElements_whenPollElement_correctElement() { - CircularFifoQueue colors = new CircularFifoQueue<>(5); - colors.add("Red"); - colors.add("Blue"); - colors.add("Green"); - colors.offer("White"); - colors.offer("Black"); - - Assert.assertEquals(TEST_COLOR, colors.poll()); - } - - @Test - public void givenAddElements_whenPeekQueue_correctElement() { - CircularFifoQueue colors = new CircularFifoQueue<>(5); - colors.add("Red"); - colors.add("Blue"); - colors.add("Green"); - colors.offer("White"); - colors.offer("Black"); - - Assert.assertEquals(TEST_COLOR, colors.peek()); - } - - @Test - public void givenAddElements_whenElementQueue_correctElement() { - CircularFifoQueue colors = new CircularFifoQueue<>(5); - colors.add("Red"); - colors.add("Blue"); - colors.add("Green"); - colors.offer("White"); - colors.offer("Black"); - - Assert.assertEquals(TEST_COLOR, colors.element()); - } - - @Test - public void givenAddElements_whenRemoveElement_correctElement() { - CircularFifoQueue colors = new CircularFifoQueue<>(5); - colors.add("Red"); - colors.add("Blue"); - colors.add("Green"); - colors.offer("White"); - colors.offer("Black"); - - Assert.assertEquals(TEST_COLOR, colors.remove()); - } - - @Test - public void givenFullQueue_whenClearQueue_getIsEmpty() { - CircularFifoQueue colors = new CircularFifoQueue<>(5); - colors.add("Red"); - colors.add("Blue"); - colors.add("Green"); - colors.offer("White"); - colors.offer("Black"); - - colors.clear(); - - Assert.assertEquals(true, colors.isEmpty()); - } - - @Test - public void givenFullQueue_whenCheckFull_getIsFull() { - CircularFifoQueue colors = new CircularFifoQueue<>(5); - colors.add("Red"); - colors.add("Blue"); - colors.add("Green"); - colors.offer("White"); - colors.offer("Black"); - - Assert.assertEquals(false, colors.isFull()); - } - - @Test - public void givenFullQueue_whenAddMoreElements_getIsAtFullCapacity() { - CircularFifoQueue colors = new CircularFifoQueue<>(5); - colors.add("Red"); - colors.add("Blue"); - colors.add("Green"); - colors.offer("White"); - colors.offer("Black"); - - colors.add("Orange"); - colors.add("Violet"); - colors.add("Pink"); - - Assert.assertEquals(true, colors.isAtFullCapacity()); - } - -} diff --git a/libraries/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueUnitTest.java b/libraries/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueUnitTest.java new file mode 100644 index 0000000000..39384a7442 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueUnitTest.java @@ -0,0 +1,159 @@ +package com.baeldung.circularfifoqueue; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.collections4.queue.CircularFifoQueue; +import org.junit.Assert; +import org.junit.Test; + +public class CircularFifoQueueUnitTest { + + private static final int DEFAULT_SIZE = 32; + + private static final int FIXED_SIZE = 5; + + private static final int COLLECTION_SIZE = 7; + + private static final String TEST_COLOR = "Red"; + + private static final String TEST_COLOR_BY_INDEX = "Blue"; + + @Test + public void whenUsingDefualtConstructor_correctSizeQueue() { + CircularFifoQueue bits = new CircularFifoQueue<>(); + + Assert.assertEquals(DEFAULT_SIZE, bits.maxSize()); + } + + @Test + public void givenAddElements_whenUsingIntConstructor_correctSizeQueue() { + CircularFifoQueue colors = new CircularFifoQueue<>(5); + colors.add("Red"); + colors.add("Blue"); + colors.add("Green"); + colors.offer("White"); + colors.offer("Black"); + + Assert.assertEquals(FIXED_SIZE, colors.maxSize()); + } + + @Test + public void whenUsingCollectionConstructor_correctSizeQueue() { + List days = new ArrayList<>(); + days.add("Monday"); + days.add("Tuesday"); + days.add("Wednesday"); + days.add("Thursday"); + days.add("Friday"); + days.add("Saturday"); + days.add("Sunday"); + + CircularFifoQueue daysOfWeek = new CircularFifoQueue<>(days); + + Assert.assertEquals(COLLECTION_SIZE, daysOfWeek.maxSize()); + } + + @Test + public void givenAddElements_whenGetElement_correctElement() { + CircularFifoQueue colors = new CircularFifoQueue<>(5); + colors.add("Red"); + colors.add("Blue"); + colors.add("Green"); + colors.offer("White"); + colors.offer("Black"); + + Assert.assertEquals(TEST_COLOR_BY_INDEX, colors.get(1)); + } + + @Test + public void givenAddElements_whenPollElement_correctElement() { + CircularFifoQueue colors = new CircularFifoQueue<>(5); + colors.add("Red"); + colors.add("Blue"); + colors.add("Green"); + colors.offer("White"); + colors.offer("Black"); + + Assert.assertEquals(TEST_COLOR, colors.poll()); + } + + @Test + public void givenAddElements_whenPeekQueue_correctElement() { + CircularFifoQueue colors = new CircularFifoQueue<>(5); + colors.add("Red"); + colors.add("Blue"); + colors.add("Green"); + colors.offer("White"); + colors.offer("Black"); + + Assert.assertEquals(TEST_COLOR, colors.peek()); + } + + @Test + public void givenAddElements_whenElementQueue_correctElement() { + CircularFifoQueue colors = new CircularFifoQueue<>(5); + colors.add("Red"); + colors.add("Blue"); + colors.add("Green"); + colors.offer("White"); + colors.offer("Black"); + + Assert.assertEquals(TEST_COLOR, colors.element()); + } + + @Test + public void givenAddElements_whenRemoveElement_correctElement() { + CircularFifoQueue colors = new CircularFifoQueue<>(5); + colors.add("Red"); + colors.add("Blue"); + colors.add("Green"); + colors.offer("White"); + colors.offer("Black"); + + Assert.assertEquals(TEST_COLOR, colors.remove()); + } + + @Test + public void givenFullQueue_whenClearQueue_getIsEmpty() { + CircularFifoQueue colors = new CircularFifoQueue<>(5); + colors.add("Red"); + colors.add("Blue"); + colors.add("Green"); + colors.offer("White"); + colors.offer("Black"); + + colors.clear(); + + Assert.assertEquals(true, colors.isEmpty()); + } + + @Test + public void givenFullQueue_whenCheckFull_getIsFull() { + CircularFifoQueue colors = new CircularFifoQueue<>(5); + colors.add("Red"); + colors.add("Blue"); + colors.add("Green"); + colors.offer("White"); + colors.offer("Black"); + + Assert.assertEquals(false, colors.isFull()); + } + + @Test + public void givenFullQueue_whenAddMoreElements_getIsAtFullCapacity() { + CircularFifoQueue colors = new CircularFifoQueue<>(5); + colors.add("Red"); + colors.add("Blue"); + colors.add("Green"); + colors.offer("White"); + colors.offer("Black"); + + colors.add("Orange"); + colors.add("Violet"); + colors.add("Pink"); + + Assert.assertEquals(true, colors.isAtFullCapacity()); + } + +} diff --git a/libraries/src/test/java/com/baeldung/commons/chain/AtmChainTest.java b/libraries/src/test/java/com/baeldung/commons/chain/AtmChainTest.java deleted file mode 100644 index cd9a7baaf3..0000000000 --- a/libraries/src/test/java/com/baeldung/commons/chain/AtmChainTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.commons.chain; - -import org.apache.commons.chain.Catalog; -import org.apache.commons.chain.Command; -import org.apache.commons.chain.Context; -import org.junit.Assert; -import org.junit.Test; - -import static com.baeldung.commons.chain.AtmConstants.*; - -public class AtmChainTest { - - public static final int EXPECTED_TOTAL_AMOUNT_TO_BE_WITHDRAWN = 460; - public static final int EXPECTED_AMOUNT_LEFT_TO_BE_WITHDRAWN = 0; - public static final int EXPECTED_NO_OF_HUNDREDS_DISPENSED = 4; - public static final int EXPECTED_NO_OF_FIFTIES_DISPENSED = 1; - public static final int EXPECTED_NO_OF_TENS_DISPENSED = 1; - - @Test - public void givenInputsToContext_whenAppliedChain_thenExpectedContext() { - Context context = new AtmRequestContext(); - context.put(TOTAL_AMOUNT_TO_BE_WITHDRAWN, 460); - context.put(AMOUNT_LEFT_TO_BE_WITHDRAWN, 460); - Catalog catalog = new AtmCatalog(); - Command atmWithdrawalChain = catalog.getCommand(ATM_WITHDRAWAL_CHAIN); - try { - atmWithdrawalChain.execute(context); - } catch (Exception e) { - e.printStackTrace(); - } - Assert.assertEquals(EXPECTED_TOTAL_AMOUNT_TO_BE_WITHDRAWN, (int) context.get(TOTAL_AMOUNT_TO_BE_WITHDRAWN)); - Assert.assertEquals(EXPECTED_AMOUNT_LEFT_TO_BE_WITHDRAWN, (int) context.get(AMOUNT_LEFT_TO_BE_WITHDRAWN)); - Assert.assertEquals(EXPECTED_NO_OF_HUNDREDS_DISPENSED, (int) context.get(NO_OF_HUNDREDS_DISPENSED)); - Assert.assertEquals(EXPECTED_NO_OF_FIFTIES_DISPENSED, (int) context.get(NO_OF_FIFTIES_DISPENSED)); - Assert.assertEquals(EXPECTED_NO_OF_TENS_DISPENSED, (int) context.get(NO_OF_TENS_DISPENSED)); - } -} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/commons/chain/AtmChainUnitTest.java b/libraries/src/test/java/com/baeldung/commons/chain/AtmChainUnitTest.java new file mode 100644 index 0000000000..3d12662968 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/chain/AtmChainUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.commons.chain; + +import org.apache.commons.chain.Catalog; +import org.apache.commons.chain.Command; +import org.apache.commons.chain.Context; +import org.junit.Assert; +import org.junit.Test; + +import static com.baeldung.commons.chain.AtmConstants.*; + +public class AtmChainUnitTest { + + public static final int EXPECTED_TOTAL_AMOUNT_TO_BE_WITHDRAWN = 460; + public static final int EXPECTED_AMOUNT_LEFT_TO_BE_WITHDRAWN = 0; + public static final int EXPECTED_NO_OF_HUNDREDS_DISPENSED = 4; + public static final int EXPECTED_NO_OF_FIFTIES_DISPENSED = 1; + public static final int EXPECTED_NO_OF_TENS_DISPENSED = 1; + + @Test + public void givenInputsToContext_whenAppliedChain_thenExpectedContext() { + Context context = new AtmRequestContext(); + context.put(TOTAL_AMOUNT_TO_BE_WITHDRAWN, 460); + context.put(AMOUNT_LEFT_TO_BE_WITHDRAWN, 460); + Catalog catalog = new AtmCatalog(); + Command atmWithdrawalChain = catalog.getCommand(ATM_WITHDRAWAL_CHAIN); + try { + atmWithdrawalChain.execute(context); + } catch (Exception e) { + e.printStackTrace(); + } + Assert.assertEquals(EXPECTED_TOTAL_AMOUNT_TO_BE_WITHDRAWN, (int) context.get(TOTAL_AMOUNT_TO_BE_WITHDRAWN)); + Assert.assertEquals(EXPECTED_AMOUNT_LEFT_TO_BE_WITHDRAWN, (int) context.get(AMOUNT_LEFT_TO_BE_WITHDRAWN)); + Assert.assertEquals(EXPECTED_NO_OF_HUNDREDS_DISPENSED, (int) context.get(NO_OF_HUNDREDS_DISPENSED)); + Assert.assertEquals(EXPECTED_NO_OF_FIFTIES_DISPENSED, (int) context.get(NO_OF_FIFTIES_DISPENSED)); + Assert.assertEquals(EXPECTED_NO_OF_TENS_DISPENSED, (int) context.get(NO_OF_TENS_DISPENSED)); + } +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java b/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java deleted file mode 100644 index f34f431d8e..0000000000 --- a/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.baeldung.commons.collections; - -import com.baeldung.commons.collectionutil.Address; -import com.baeldung.commons.collectionutil.Customer; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.collections4.Predicate; -import org.apache.commons.collections4.Transformer; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class CollectionUtilsGuideTest { - - Customer customer1 = new Customer(1, "Daniel", 123456l, "locality1", "city1", "1234"); - Customer customer4 = new Customer(4, "Bob", 456789l, "locality4", "city4", "4567"); - List list1, list2, list3, linkedList1; - - @Before - public void setup() { - Customer customer2 = new Customer(2, "Fredrik", 234567l, "locality2", "city2", "2345"); - Customer customer3 = new Customer(3, "Kyle", 345678l, "locality3", "city3", "3456"); - Customer customer5 = new Customer(5, "Cat", 567890l, "locality5", "city5", "5678"); - Customer customer6 = new Customer(6, "John", 678901l, "locality6", "city6", "6789"); - - list1 = Arrays.asList(customer1, customer2, customer3); - list2 = Arrays.asList(customer4, customer5, customer6); - list3 = Arrays.asList(customer1, customer2); - - linkedList1 = new LinkedList<>(list1); - } - - @Test - public void givenList_whenAddIgnoreNull_thenNoNullAdded() { - CollectionUtils.addIgnoreNull(list1, null); - assertFalse(list1.contains(null)); - } - - @Test - public void givenTwoSortedLists_whenCollated_thenSorted() { - List sortedList = CollectionUtils.collate(list1, list2); - - assertEquals(6, sortedList.size()); - assertTrue(sortedList.get(0).getName().equals("Bob")); - assertTrue(sortedList.get(2).getName().equals("Daniel")); - } - - @Test - public void givenListOfCustomers_whenTransformed_thenListOfAddress() { - Collection
    addressCol = CollectionUtils.collect(list1, new Transformer() { - public Address transform(Customer customer) { - return new Address(customer.getLocality(), customer.getCity(), customer.getZip()); - } - }); - - List
    addressList = new ArrayList<>(addressCol); - assertTrue(addressList.size() == 3); - assertTrue(addressList.get(0).getLocality().equals("locality1")); - } - - @Test - public void givenCustomerList_whenFiltered_thenCorrectSize() { - - boolean isModified = CollectionUtils.filter(linkedList1, new Predicate() { - public boolean evaluate(Customer customer) { - return Arrays.asList("Daniel", "Kyle").contains(customer.getName()); - } - }); - - // filterInverse does the opposite. It removes the element from the list if the Predicate returns true - // select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection - - assertTrue(isModified && linkedList1.size() == 2); - } - - @Test - public void givenNonEmptyList_whenCheckedIsNotEmpty_thenTrue() { - List emptyList = new ArrayList<>(); - List nullList = null; - - // Very handy at times where we want to check if a collection is not null and not empty too. - // isNotEmpty does the opposite. Handy because using ! operator on isEmpty makes it missable while reading - assertTrue(CollectionUtils.isNotEmpty(list1)); - assertTrue(CollectionUtils.isEmpty(nullList)); - assertTrue(CollectionUtils.isEmpty(emptyList)); - } - - @Test - public void givenCustomerListAndASubcollection_whenChecked_thenTrue() { - assertTrue(CollectionUtils.isSubCollection(list3, list1)); - } - - @Test - public void givenTwoLists_whenIntersected_thenCheckSize() { - Collection intersection = CollectionUtils.intersection(list1, list3); - assertTrue(intersection.size() == 2); - } - - @Test - public void givenTwoLists_whenSubtracted_thenCheckElementNotPresentInA() { - Collection result = CollectionUtils.subtract(list1, list3); - assertFalse(result.contains(customer1)); - } - - @Test - public void givenTwoLists_whenUnioned_thenCheckElementPresentInResult() { - Collection union = CollectionUtils.union(list1, list2); - assertTrue(union.contains(customer1)); - assertTrue(union.contains(customer4)); - } - -} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideUnitTest.java b/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideUnitTest.java new file mode 100644 index 0000000000..448c5b0729 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideUnitTest.java @@ -0,0 +1,120 @@ +package com.baeldung.commons.collections; + +import com.baeldung.commons.collectionutil.Address; +import com.baeldung.commons.collectionutil.Customer; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.Predicate; +import org.apache.commons.collections4.Transformer; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class CollectionUtilsGuideUnitTest { + + Customer customer1 = new Customer(1, "Daniel", 123456l, "locality1", "city1", "1234"); + Customer customer4 = new Customer(4, "Bob", 456789l, "locality4", "city4", "4567"); + List list1, list2, list3, linkedList1; + + @Before + public void setup() { + Customer customer2 = new Customer(2, "Fredrik", 234567l, "locality2", "city2", "2345"); + Customer customer3 = new Customer(3, "Kyle", 345678l, "locality3", "city3", "3456"); + Customer customer5 = new Customer(5, "Cat", 567890l, "locality5", "city5", "5678"); + Customer customer6 = new Customer(6, "John", 678901l, "locality6", "city6", "6789"); + + list1 = Arrays.asList(customer1, customer2, customer3); + list2 = Arrays.asList(customer4, customer5, customer6); + list3 = Arrays.asList(customer1, customer2); + + linkedList1 = new LinkedList<>(list1); + } + + @Test + public void givenList_whenAddIgnoreNull_thenNoNullAdded() { + CollectionUtils.addIgnoreNull(list1, null); + assertFalse(list1.contains(null)); + } + + @Test + public void givenTwoSortedLists_whenCollated_thenSorted() { + List sortedList = CollectionUtils.collate(list1, list2); + + assertEquals(6, sortedList.size()); + assertTrue(sortedList.get(0).getName().equals("Bob")); + assertTrue(sortedList.get(2).getName().equals("Daniel")); + } + + @Test + public void givenListOfCustomers_whenTransformed_thenListOfAddress() { + Collection
    addressCol = CollectionUtils.collect(list1, new Transformer() { + public Address transform(Customer customer) { + return new Address(customer.getLocality(), customer.getCity(), customer.getZip()); + } + }); + + List
    addressList = new ArrayList<>(addressCol); + assertTrue(addressList.size() == 3); + assertTrue(addressList.get(0).getLocality().equals("locality1")); + } + + @Test + public void givenCustomerList_whenFiltered_thenCorrectSize() { + + boolean isModified = CollectionUtils.filter(linkedList1, new Predicate() { + public boolean evaluate(Customer customer) { + return Arrays.asList("Daniel", "Kyle").contains(customer.getName()); + } + }); + + // filterInverse does the opposite. It removes the element from the list if the Predicate returns true + // select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection + + assertTrue(isModified && linkedList1.size() == 2); + } + + @Test + public void givenNonEmptyList_whenCheckedIsNotEmpty_thenTrue() { + List emptyList = new ArrayList<>(); + List nullList = null; + + // Very handy at times where we want to check if a collection is not null and not empty too. + // isNotEmpty does the opposite. Handy because using ! operator on isEmpty makes it missable while reading + assertTrue(CollectionUtils.isNotEmpty(list1)); + assertTrue(CollectionUtils.isEmpty(nullList)); + assertTrue(CollectionUtils.isEmpty(emptyList)); + } + + @Test + public void givenCustomerListAndASubcollection_whenChecked_thenTrue() { + assertTrue(CollectionUtils.isSubCollection(list3, list1)); + } + + @Test + public void givenTwoLists_whenIntersected_thenCheckSize() { + Collection intersection = CollectionUtils.intersection(list1, list3); + assertTrue(intersection.size() == 2); + } + + @Test + public void givenTwoLists_whenSubtracted_thenCheckElementNotPresentInA() { + Collection result = CollectionUtils.subtract(list1, list3); + assertFalse(result.contains(customer1)); + } + + @Test + public void givenTwoLists_whenUnioned_thenCheckElementPresentInResult() { + Collection union = CollectionUtils.union(list1, list2); + assertTrue(union.contains(customer1)); + assertTrue(union.contains(customer4)); + } + +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java deleted file mode 100644 index 988335b7d1..0000000000 --- a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.baeldung.commons.collections; - -import org.apache.commons.collections4.MapUtils; -import org.apache.commons.collections4.PredicateUtils; -import org.apache.commons.collections4.TransformerUtils; -import org.assertj.core.api.Assertions; -import org.junit.Before; -import org.junit.Test; - -import java.util.HashMap; -import java.util.Map; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.collection.IsMapContaining.hasEntry; -import static org.hamcrest.collection.IsMapWithSize.aMapWithSize; -import static org.hamcrest.collection.IsMapWithSize.anEmptyMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -public class MapUtilsTest { - - private String[][] color2DArray = new String[][] { { "RED", "#FF0000" }, { "GREEN", "#00FF00" }, { "BLUE", "#0000FF" } }; - private String[] color1DArray = new String[] { "RED", "#FF0000", "GREEN", "#00FF00", "BLUE", "#0000FF" }; - private Map colorMap; - - @Before - public void createMap() { - this.colorMap = MapUtils.putAll(new HashMap(), this.color2DArray); - } - - @Test - public void whenCreateMapFrom2DArray_theMapIsCreated() { - this.colorMap = MapUtils.putAll(new HashMap(), this.color2DArray); - - assertThat(this.colorMap, is(aMapWithSize(this.color2DArray.length))); - - assertThat(this.colorMap, hasEntry("RED", "#FF0000")); - assertThat(this.colorMap, hasEntry("GREEN", "#00FF00")); - assertThat(this.colorMap, hasEntry("BLUE", "#0000FF")); - } - - @Test - public void whenCreateMapFrom1DArray_theMapIsCreated() { - this.colorMap = MapUtils.putAll(new HashMap(), this.color1DArray); - - assertThat(this.colorMap, is(aMapWithSize(this.color1DArray.length / 2))); - - assertThat(this.colorMap, hasEntry("RED", "#FF0000")); - assertThat(this.colorMap, hasEntry("GREEN", "#00FF00")); - assertThat(this.colorMap, hasEntry("BLUE", "#0000FF")); - } - - @Test - public void whenVerbosePrintMap_thenMustPrintFormattedMap() { - MapUtils.verbosePrint(System.out, "Optional Label", this.colorMap); - } - - @Test - public void whenGetKeyNotPresent_thenMustReturnDefaultValue() { - String defaultColorStr = "COLOR_NOT_FOUND"; - String color = MapUtils.getString(this.colorMap, "BLACK", defaultColorStr); - - assertEquals(color, defaultColorStr); - } - - @Test - public void whenGetOnNullMap_thenMustReturnDefaultValue() { - String defaultColorStr = "COLOR_NOT_FOUND"; - String color = MapUtils.getString(null, "RED", defaultColorStr); - - assertEquals(color, defaultColorStr); - } - - @Test - public void whenInvertMap_thenMustReturnInvertedMap() { - Map invColorMap = MapUtils.invertMap(this.colorMap); - - int size = invColorMap.size(); - Assertions.assertThat(invColorMap).hasSameSizeAs(colorMap).containsKeys(this.colorMap.values().toArray(new String[size])).containsValues(this.colorMap.keySet().toArray(new String[size])); - } - - @Test(expected = IllegalArgumentException.class) - public void whenCreateFixedSizedMapAndAdd_thenMustThrowException() { - Map rgbMap = MapUtils.fixedSizeMap(MapUtils.putAll(new HashMap(), this.color1DArray)); - - rgbMap.put("ORANGE", "#FFA500"); - } - - @Test(expected = IllegalArgumentException.class) - public void whenAddDuplicateToUniqueValuesPredicateMap_thenMustThrowException() { - Map uniqValuesMap = MapUtils.predicatedMap(this.colorMap, null, PredicateUtils.uniquePredicate()); - - uniqValuesMap.put("NEW_RED", "#FF0000"); - } - - @Test - public void whenCreateLazyMap_theMapIsCreated() { - Map intStrMap = MapUtils.lazyMap(new HashMap(), TransformerUtils.stringValueTransformer()); - - assertThat(intStrMap, is(anEmptyMap())); - - intStrMap.get(1); - intStrMap.get(2); - intStrMap.get(3); - - assertThat(intStrMap, is(aMapWithSize(3))); - } -} diff --git a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsUnitTest.java new file mode 100644 index 0000000000..bad4d823a0 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsUnitTest.java @@ -0,0 +1,108 @@ +package com.baeldung.commons.collections; + +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.collections4.PredicateUtils; +import org.apache.commons.collections4.TransformerUtils; +import org.assertj.core.api.Assertions; +import org.junit.Before; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.collection.IsMapContaining.hasEntry; +import static org.hamcrest.collection.IsMapWithSize.aMapWithSize; +import static org.hamcrest.collection.IsMapWithSize.anEmptyMap; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +public class MapUtilsUnitTest { + + private String[][] color2DArray = new String[][] { { "RED", "#FF0000" }, { "GREEN", "#00FF00" }, { "BLUE", "#0000FF" } }; + private String[] color1DArray = new String[] { "RED", "#FF0000", "GREEN", "#00FF00", "BLUE", "#0000FF" }; + private Map colorMap; + + @Before + public void createMap() { + this.colorMap = MapUtils.putAll(new HashMap(), this.color2DArray); + } + + @Test + public void whenCreateMapFrom2DArray_theMapIsCreated() { + this.colorMap = MapUtils.putAll(new HashMap(), this.color2DArray); + + assertThat(this.colorMap, is(aMapWithSize(this.color2DArray.length))); + + assertThat(this.colorMap, hasEntry("RED", "#FF0000")); + assertThat(this.colorMap, hasEntry("GREEN", "#00FF00")); + assertThat(this.colorMap, hasEntry("BLUE", "#0000FF")); + } + + @Test + public void whenCreateMapFrom1DArray_theMapIsCreated() { + this.colorMap = MapUtils.putAll(new HashMap(), this.color1DArray); + + assertThat(this.colorMap, is(aMapWithSize(this.color1DArray.length / 2))); + + assertThat(this.colorMap, hasEntry("RED", "#FF0000")); + assertThat(this.colorMap, hasEntry("GREEN", "#00FF00")); + assertThat(this.colorMap, hasEntry("BLUE", "#0000FF")); + } + + @Test + public void whenVerbosePrintMap_thenMustPrintFormattedMap() { + MapUtils.verbosePrint(System.out, "Optional Label", this.colorMap); + } + + @Test + public void whenGetKeyNotPresent_thenMustReturnDefaultValue() { + String defaultColorStr = "COLOR_NOT_FOUND"; + String color = MapUtils.getString(this.colorMap, "BLACK", defaultColorStr); + + assertEquals(color, defaultColorStr); + } + + @Test + public void whenGetOnNullMap_thenMustReturnDefaultValue() { + String defaultColorStr = "COLOR_NOT_FOUND"; + String color = MapUtils.getString(null, "RED", defaultColorStr); + + assertEquals(color, defaultColorStr); + } + + @Test + public void whenInvertMap_thenMustReturnInvertedMap() { + Map invColorMap = MapUtils.invertMap(this.colorMap); + + int size = invColorMap.size(); + Assertions.assertThat(invColorMap).hasSameSizeAs(colorMap).containsKeys(this.colorMap.values().toArray(new String[size])).containsValues(this.colorMap.keySet().toArray(new String[size])); + } + + @Test(expected = IllegalArgumentException.class) + public void whenCreateFixedSizedMapAndAdd_thenMustThrowException() { + Map rgbMap = MapUtils.fixedSizeMap(MapUtils.putAll(new HashMap(), this.color1DArray)); + + rgbMap.put("ORANGE", "#FFA500"); + } + + @Test(expected = IllegalArgumentException.class) + public void whenAddDuplicateToUniqueValuesPredicateMap_thenMustThrowException() { + Map uniqValuesMap = MapUtils.predicatedMap(this.colorMap, null, PredicateUtils.uniquePredicate()); + + uniqValuesMap.put("NEW_RED", "#FF0000"); + } + + @Test + public void whenCreateLazyMap_theMapIsCreated() { + Map intStrMap = MapUtils.lazyMap(new HashMap(), TransformerUtils.stringValueTransformer()); + + assertThat(intStrMap, is(anEmptyMap())); + + intStrMap.get(1); + intStrMap.get(2); + intStrMap.get(3); + + assertThat(intStrMap, is(aMapWithSize(3))); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java b/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java deleted file mode 100644 index 4408dcc195..0000000000 --- a/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.baeldung.commons.collections4; - -import org.apache.commons.collections4.Bag; -import org.apache.commons.collections4.SortedBag; -import org.apache.commons.collections4.bag.*; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsEqual.equalTo; - -public class BagTests { - - @Test - public void givenMultipleCopies_whenAdded_theCountIsKept() { - Bag bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 })); - - assertThat(bag.getCount(1), equalTo(2)); - } - - @Test - public void givenBag_whenBagAddAPILikeCollectionAPI_thenFalse() { - Collection collection = new ArrayList<>(); - - // Collection contract defines that add() should return true - assertThat(collection.add(9), is(true)); - - // Even when element is already in the collection - collection.add(1); - assertThat(collection.add(1), is(true)); - - Bag bag = new HashBag<>(); - - // Bag returns true on adding a new element - assertThat(bag.add(9), is(true)); - - bag.add(1); - // But breaks the contract with false when it has to increment the count - assertThat(bag.add(1), is(not(true))); - } - - @Test - public void givenDecoratedBag_whenBagAddAPILikeCollectionAPI_thenTrue() { - Bag bag = CollectionBag.collectionBag(new HashBag<>()); - - bag.add(1); - // This time the behavior is compliant to the Java Collection - assertThat(bag.add(1), is((true))); - } - - @Test - public void givenAdd_whenCountOfElementsDefined_thenCountAreAdded() { - Bag bag = new HashBag<>(); - - // Adding 1 for 5 times - bag.add(1, 5); - assertThat(bag.getCount(1), equalTo(5)); - } - - @Test - public void givenMultipleCopies_whenRemove_allAreRemoved() { - Bag bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 })); - - // From 3 we delete 1, 2 remain - bag.remove(3, 1); - assertThat(bag.getCount(3), equalTo(2)); - - // From 2 we delete all - bag.remove(1); - assertThat(bag.getCount(1), equalTo(0)); - } - - @Test - public void givenTree_whenDuplicateElementsAdded_thenSort() { - TreeBag bag = new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 })); - - assertThat(bag.first(), equalTo(1)); - assertThat(bag.getCount(bag.first()), equalTo(2)); - assertThat(bag.last(), equalTo(7)); - assertThat(bag.getCount(bag.last()), equalTo(3)); - } - - @Test - public void givenDecoratedTree_whenTreeAddAPILikeCollectionAPI_thenTrue() { - SortedBag bag = CollectionSortedBag.collectionSortedBag(new TreeBag<>()); - - bag.add(1); - assertThat(bag.add(1), is((true))); - } - - @Test - public void givenSortedBag_whenDuplicateElementsAdded_thenSort() { - SynchronizedSortedBag bag = SynchronizedSortedBag.synchronizedSortedBag(new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 }))); - - assertThat(bag.first(), equalTo(1)); - assertThat(bag.getCount(bag.first()), equalTo(2)); - assertThat(bag.last(), equalTo(7)); - assertThat(bag.getCount(bag.last()), equalTo(3)); - } -} diff --git a/libraries/src/test/java/com/baeldung/commons/collections4/BagUnitTest.java b/libraries/src/test/java/com/baeldung/commons/collections4/BagUnitTest.java new file mode 100644 index 0000000000..ebad4093f0 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/collections4/BagUnitTest.java @@ -0,0 +1,105 @@ +package com.baeldung.commons.collections4; + +import org.apache.commons.collections4.Bag; +import org.apache.commons.collections4.SortedBag; +import org.apache.commons.collections4.bag.*; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; + +public class BagUnitTest { + + @Test + public void givenMultipleCopies_whenAdded_theCountIsKept() { + Bag bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 })); + + assertThat(bag.getCount(1), equalTo(2)); + } + + @Test + public void givenBag_whenBagAddAPILikeCollectionAPI_thenFalse() { + Collection collection = new ArrayList<>(); + + // Collection contract defines that add() should return true + assertThat(collection.add(9), is(true)); + + // Even when element is already in the collection + collection.add(1); + assertThat(collection.add(1), is(true)); + + Bag bag = new HashBag<>(); + + // Bag returns true on adding a new element + assertThat(bag.add(9), is(true)); + + bag.add(1); + // But breaks the contract with false when it has to increment the count + assertThat(bag.add(1), is(not(true))); + } + + @Test + public void givenDecoratedBag_whenBagAddAPILikeCollectionAPI_thenTrue() { + Bag bag = CollectionBag.collectionBag(new HashBag<>()); + + bag.add(1); + // This time the behavior is compliant to the Java Collection + assertThat(bag.add(1), is((true))); + } + + @Test + public void givenAdd_whenCountOfElementsDefined_thenCountAreAdded() { + Bag bag = new HashBag<>(); + + // Adding 1 for 5 times + bag.add(1, 5); + assertThat(bag.getCount(1), equalTo(5)); + } + + @Test + public void givenMultipleCopies_whenRemove_allAreRemoved() { + Bag bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 })); + + // From 3 we delete 1, 2 remain + bag.remove(3, 1); + assertThat(bag.getCount(3), equalTo(2)); + + // From 2 we delete all + bag.remove(1); + assertThat(bag.getCount(1), equalTo(0)); + } + + @Test + public void givenTree_whenDuplicateElementsAdded_thenSort() { + TreeBag bag = new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 })); + + assertThat(bag.first(), equalTo(1)); + assertThat(bag.getCount(bag.first()), equalTo(2)); + assertThat(bag.last(), equalTo(7)); + assertThat(bag.getCount(bag.last()), equalTo(3)); + } + + @Test + public void givenDecoratedTree_whenTreeAddAPILikeCollectionAPI_thenTrue() { + SortedBag bag = CollectionSortedBag.collectionSortedBag(new TreeBag<>()); + + bag.add(1); + assertThat(bag.add(1), is((true))); + } + + @Test + public void givenSortedBag_whenDuplicateElementsAdded_thenSort() { + SynchronizedSortedBag bag = SynchronizedSortedBag.synchronizedSortedBag(new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 }))); + + assertThat(bag.first(), equalTo(1)); + assertThat(bag.getCount(bag.first()), equalTo(2)); + assertThat(bag.last(), equalTo(7)); + assertThat(bag.getCount(bag.last()), equalTo(3)); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java b/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java deleted file mode 100644 index 6210bb51a9..0000000000 --- a/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.baeldung.commons.csv; - -import org.apache.commons.csv.CSVFormat; -import org.apache.commons.csv.CSVPrinter; -import org.apache.commons.csv.CSVRecord; -import org.junit.Test; - -import java.io.FileReader; -import java.io.IOException; -import java.io.Reader; -import java.io.StringWriter; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -public class CSVReaderWriterTest { - - public static final Map AUTHOR_BOOK_MAP = Collections.unmodifiableMap(new LinkedHashMap() { - { - put("Dan Simmons", "Hyperion"); - put("Douglas Adams", "The Hitchhiker's Guide to the Galaxy"); - } - }); - public static final String[] HEADERS = { "author", "title" }; - public static final String EXPECTED_FILESTREAM = "author,title\r\n" + "Dan Simmons,Hyperion\r\n" + "Douglas Adams,The Hitchhiker's Guide to the Galaxy"; - - @Test - public void givenCSVFile_whenRead_thenContentsAsExpected() throws IOException { - Reader in = new FileReader("src/test/resources/book.csv"); - Iterable records = CSVFormat.DEFAULT.withHeader(HEADERS).withFirstRecordAsHeader().parse(in); - for (CSVRecord record : records) { - String author = record.get("author"); - String title = record.get("title"); - assertEquals(AUTHOR_BOOK_MAP.get(author), title); - } - } - - @Test - public void givenAuthorBookMap_whenWrittenToStream_thenOutputStreamAsExpected() throws IOException { - StringWriter sw = new StringWriter(); - try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withHeader(HEADERS))) { - AUTHOR_BOOK_MAP.forEach((author, title) -> { - try { - printer.printRecord(author, title); - } catch (IOException e) { - e.printStackTrace(); - } - }); - } - assertEquals(EXPECTED_FILESTREAM, sw.toString().trim()); - } - -} diff --git a/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterUnitTest.java b/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterUnitTest.java new file mode 100644 index 0000000000..f93e59ed75 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterUnitTest.java @@ -0,0 +1,55 @@ +package com.baeldung.commons.csv; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVPrinter; +import org.apache.commons.csv.CSVRecord; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; +import java.io.StringWriter; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +public class CSVReaderWriterUnitTest { + + public static final Map AUTHOR_BOOK_MAP = Collections.unmodifiableMap(new LinkedHashMap() { + { + put("Dan Simmons", "Hyperion"); + put("Douglas Adams", "The Hitchhiker's Guide to the Galaxy"); + } + }); + public static final String[] HEADERS = { "author", "title" }; + public static final String EXPECTED_FILESTREAM = "author,title\r\n" + "Dan Simmons,Hyperion\r\n" + "Douglas Adams,The Hitchhiker's Guide to the Galaxy"; + + @Test + public void givenCSVFile_whenRead_thenContentsAsExpected() throws IOException { + Reader in = new FileReader("src/test/resources/book.csv"); + Iterable records = CSVFormat.DEFAULT.withHeader(HEADERS).withFirstRecordAsHeader().parse(in); + for (CSVRecord record : records) { + String author = record.get("author"); + String title = record.get("title"); + assertEquals(AUTHOR_BOOK_MAP.get(author), title); + } + } + + @Test + public void givenAuthorBookMap_whenWrittenToStream_thenOutputStreamAsExpected() throws IOException { + StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withHeader(HEADERS))) { + AUTHOR_BOOK_MAP.forEach((author, title) -> { + try { + printer.printRecord(author, title); + } catch (IOException e) { + e.printStackTrace(); + } + }); + } + assertEquals(EXPECTED_FILESTREAM, sw.toString().trim()); + } + +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsTest.java deleted file mode 100644 index 29bcebeb2b..0000000000 --- a/libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsTest.java +++ /dev/null @@ -1,149 +0,0 @@ -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.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -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.BasicThreadFactory; -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); - } - - @Test - public void testBuildDefaults() { - BasicThreadFactory.Builder builder = new BasicThreadFactory.Builder(); - BasicThreadFactory factory = builder.build(); - assertNull("No naming pattern set Yet", factory.getNamingPattern()); - BasicThreadFactory factory2 = builder.namingPattern("sampleNamingPattern").daemon(true).priority(Thread.MIN_PRIORITY).build(); - assertNotNull("Got a naming pattern", factory2.getNamingPattern()); - assertEquals("sampleNamingPattern", factory2.getNamingPattern()); - - } -} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsUnitTest.java new file mode 100644 index 0000000000..a10f92639c --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsUnitTest.java @@ -0,0 +1,149 @@ +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.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; +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.BasicThreadFactory; +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 Lang3UtilsUnitTest { + + @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); + } + + @Test + public void testBuildDefaults() { + BasicThreadFactory.Builder builder = new BasicThreadFactory.Builder(); + BasicThreadFactory factory = builder.build(); + assertNull("No naming pattern set Yet", factory.getNamingPattern()); + BasicThreadFactory factory2 = builder.namingPattern("sampleNamingPattern").daemon(true).priority(Thread.MIN_PRIORITY).build(); + assertNotNull("Got a naming pattern", factory2.getNamingPattern()); + assertEquals("sampleNamingPattern", factory2.getNamingPattern()); + + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/math/IntegrationTest.java b/libraries/src/test/java/com/baeldung/commons/math/IntegrationTest.java deleted file mode 100644 index 7e047577e5..0000000000 --- a/libraries/src/test/java/com/baeldung/commons/math/IntegrationTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.commons.math; - -import org.apache.commons.math3.analysis.UnivariateFunction; -import org.apache.commons.math3.analysis.integration.SimpsonIntegrator; -import org.apache.commons.math3.analysis.integration.UnivariateIntegrator; -import org.junit.Assert; -import org.junit.Test; - -public class IntegrationTest { - - @Test - public void whenUnivariateIntegratorIntegrate_thenCorrect() { - final UnivariateFunction function = v -> v; - final UnivariateIntegrator integrator = new SimpsonIntegrator(1.0e-12, 1.0e-8, 1, 32); - - final double i = integrator.integrate(100, function, 0, 10); - - Assert.assertEquals(16 + 2d / 3d, i, 1e-7); - } - -} diff --git a/libraries/src/test/java/com/baeldung/commons/math/SimpsonIntegratorUnitTest.java b/libraries/src/test/java/com/baeldung/commons/math/SimpsonIntegratorUnitTest.java new file mode 100644 index 0000000000..bb4dc53eec --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/math/SimpsonIntegratorUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.commons.math; + +import org.apache.commons.math3.analysis.UnivariateFunction; +import org.apache.commons.math3.analysis.integration.SimpsonIntegrator; +import org.apache.commons.math3.analysis.integration.UnivariateIntegrator; +import org.junit.Assert; +import org.junit.Test; + +public class SimpsonIntegratorUnitTest { + + @Test + public void whenUnivariateIntegratorIntegrate_thenCorrect() { + final UnivariateFunction function = v -> v; + final UnivariateIntegrator integrator = new SimpsonIntegrator(1.0e-12, 1.0e-8, 1, 32); + + final double i = integrator.integrate(100, function, 0, 10); + + Assert.assertEquals(16 + 2d / 3d, i, 1e-7); + } + +} diff --git a/libraries/src/test/java/com/baeldung/crdt/CRDTTest.java b/libraries/src/test/java/com/baeldung/crdt/CRDTTest.java deleted file mode 100644 index 3d3c952863..0000000000 --- a/libraries/src/test/java/com/baeldung/crdt/CRDTTest.java +++ /dev/null @@ -1,149 +0,0 @@ -package com.baeldung.crdt; - -import com.netopyr.wurmloch.crdt.GCounter; -import com.netopyr.wurmloch.crdt.GSet; -import com.netopyr.wurmloch.crdt.LWWRegister; -import com.netopyr.wurmloch.crdt.PNCounter; -import com.netopyr.wurmloch.store.LocalCrdtStore; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class CRDTTest { - - @Test - public void givenGrowOnlySet_whenTwoReplicasDiverge_thenShouldMergeItWithoutAConflict() { - // given - final LocalCrdtStore crdtStore1 = new LocalCrdtStore(); - final LocalCrdtStore crdtStore2 = new LocalCrdtStore(); - crdtStore1.connect(crdtStore2); - - final GSet replica1 = crdtStore1.createGSet("ID_1"); - final GSet replica2 = crdtStore2. findGSet("ID_1").get(); - - // when - replica1.add("apple"); - replica2.add("banana"); - - // then - assertThat(replica1).contains("apple", "banana"); - assertThat(replica2).contains("apple", "banana"); - - // when - crdtStore1.disconnect(crdtStore2); - - replica1.add("strawberry"); - replica2.add("pear"); - - assertThat(replica1).contains("apple", "banana", "strawberry"); - assertThat(replica2).contains("apple", "banana", "pear"); - - crdtStore1.connect(crdtStore2); - - // then - assertThat(replica1).contains("apple", "banana", "strawberry", "pear"); - assertThat(replica2).contains("apple", "banana", "strawberry", "pear"); - } - - @Test - public void givenIncrementOnlyCounter_whenTwoReplicasDiverge_thenShouldMergeIt() { - // given - final LocalCrdtStore crdtStore1 = new LocalCrdtStore(); - final LocalCrdtStore crdtStore2 = new LocalCrdtStore(); - crdtStore1.connect(crdtStore2); - - final GCounter replica1 = crdtStore1.createGCounter("ID_1"); - final GCounter replica2 = crdtStore2.findGCounter("ID_1").get(); - - // when - replica1.increment(); - replica2.increment(2L); - - // then - assertThat(replica1.get()).isEqualTo(3L); - assertThat(replica2.get()).isEqualTo(3L); - - // when - crdtStore1.disconnect(crdtStore2); - - replica1.increment(3L); - replica2.increment(5L); - - assertThat(replica1.get()).isEqualTo(6L); - assertThat(replica2.get()).isEqualTo(8L); - - crdtStore1.connect(crdtStore2); - - // then - assertThat(replica1.get()).isEqualTo(11L); - assertThat(replica2.get()).isEqualTo(11L); - } - - @Test - public void givenPNCounter_whenReplicasDiverge_thenShouldMergeWithoutAConflict() { - // given - final LocalCrdtStore crdtStore1 = new LocalCrdtStore(); - final LocalCrdtStore crdtStore2 = new LocalCrdtStore(); - crdtStore1.connect(crdtStore2); - - final PNCounter replica1 = crdtStore1.createPNCounter("ID_1"); - final PNCounter replica2 = crdtStore2.findPNCounter("ID_1").get(); - - // when - replica1.increment(); - replica2.decrement(2L); - - // then - assertThat(replica1.get()).isEqualTo(-1L); - assertThat(replica2.get()).isEqualTo(-1L); - - // when - crdtStore1.disconnect(crdtStore2); - - replica1.decrement(3L); - replica2.increment(5L); - - assertThat(replica1.get()).isEqualTo(-4L); - assertThat(replica2.get()).isEqualTo(4L); - - crdtStore1.connect(crdtStore2); - - // then - assertThat(replica1.get()).isEqualTo(1L); - assertThat(replica2.get()).isEqualTo(1L); - } - - @Test - public void givenLastWriteWinsStrategy_whenReplicasDiverge_thenAfterMergeShouldKeepOnlyLastValue() { - // given - final LocalCrdtStore crdtStore1 = new LocalCrdtStore("N_1"); - final LocalCrdtStore crdtStore2 = new LocalCrdtStore("N_2"); - crdtStore1.connect(crdtStore2); - - final LWWRegister replica1 = crdtStore1.createLWWRegister("ID_1"); - final LWWRegister replica2 = crdtStore2. findLWWRegister("ID_1").get(); - - // when - replica1.set("apple"); - replica2.set("banana"); - - // then - assertThat(replica1.get()).isEqualTo("banana"); - assertThat(replica2.get()).isEqualTo("banana"); - - // when - crdtStore1.disconnect(crdtStore2); - - replica1.set("strawberry"); - replica2.set("pear"); - - assertThat(replica1.get()).isEqualTo("strawberry"); - assertThat(replica2.get()).isEqualTo("pear"); - - crdtStore1.connect(crdtStore2); - - // then - assertThat(replica1.get()).isEqualTo("pear"); - assertThat(replica2.get()).isEqualTo("pear"); - } -} diff --git a/libraries/src/test/java/com/baeldung/crdt/CRDTUnitTest.java b/libraries/src/test/java/com/baeldung/crdt/CRDTUnitTest.java new file mode 100644 index 0000000000..840263e430 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/crdt/CRDTUnitTest.java @@ -0,0 +1,149 @@ +package com.baeldung.crdt; + +import com.netopyr.wurmloch.crdt.GCounter; +import com.netopyr.wurmloch.crdt.GSet; +import com.netopyr.wurmloch.crdt.LWWRegister; +import com.netopyr.wurmloch.crdt.PNCounter; +import com.netopyr.wurmloch.store.LocalCrdtStore; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CRDTUnitTest { + + @Test + public void givenGrowOnlySet_whenTwoReplicasDiverge_thenShouldMergeItWithoutAConflict() { + // given + final LocalCrdtStore crdtStore1 = new LocalCrdtStore(); + final LocalCrdtStore crdtStore2 = new LocalCrdtStore(); + crdtStore1.connect(crdtStore2); + + final GSet replica1 = crdtStore1.createGSet("ID_1"); + final GSet replica2 = crdtStore2. findGSet("ID_1").get(); + + // when + replica1.add("apple"); + replica2.add("banana"); + + // then + assertThat(replica1).contains("apple", "banana"); + assertThat(replica2).contains("apple", "banana"); + + // when + crdtStore1.disconnect(crdtStore2); + + replica1.add("strawberry"); + replica2.add("pear"); + + assertThat(replica1).contains("apple", "banana", "strawberry"); + assertThat(replica2).contains("apple", "banana", "pear"); + + crdtStore1.connect(crdtStore2); + + // then + assertThat(replica1).contains("apple", "banana", "strawberry", "pear"); + assertThat(replica2).contains("apple", "banana", "strawberry", "pear"); + } + + @Test + public void givenIncrementOnlyCounter_whenTwoReplicasDiverge_thenShouldMergeIt() { + // given + final LocalCrdtStore crdtStore1 = new LocalCrdtStore(); + final LocalCrdtStore crdtStore2 = new LocalCrdtStore(); + crdtStore1.connect(crdtStore2); + + final GCounter replica1 = crdtStore1.createGCounter("ID_1"); + final GCounter replica2 = crdtStore2.findGCounter("ID_1").get(); + + // when + replica1.increment(); + replica2.increment(2L); + + // then + assertThat(replica1.get()).isEqualTo(3L); + assertThat(replica2.get()).isEqualTo(3L); + + // when + crdtStore1.disconnect(crdtStore2); + + replica1.increment(3L); + replica2.increment(5L); + + assertThat(replica1.get()).isEqualTo(6L); + assertThat(replica2.get()).isEqualTo(8L); + + crdtStore1.connect(crdtStore2); + + // then + assertThat(replica1.get()).isEqualTo(11L); + assertThat(replica2.get()).isEqualTo(11L); + } + + @Test + public void givenPNCounter_whenReplicasDiverge_thenShouldMergeWithoutAConflict() { + // given + final LocalCrdtStore crdtStore1 = new LocalCrdtStore(); + final LocalCrdtStore crdtStore2 = new LocalCrdtStore(); + crdtStore1.connect(crdtStore2); + + final PNCounter replica1 = crdtStore1.createPNCounter("ID_1"); + final PNCounter replica2 = crdtStore2.findPNCounter("ID_1").get(); + + // when + replica1.increment(); + replica2.decrement(2L); + + // then + assertThat(replica1.get()).isEqualTo(-1L); + assertThat(replica2.get()).isEqualTo(-1L); + + // when + crdtStore1.disconnect(crdtStore2); + + replica1.decrement(3L); + replica2.increment(5L); + + assertThat(replica1.get()).isEqualTo(-4L); + assertThat(replica2.get()).isEqualTo(4L); + + crdtStore1.connect(crdtStore2); + + // then + assertThat(replica1.get()).isEqualTo(1L); + assertThat(replica2.get()).isEqualTo(1L); + } + + @Test + public void givenLastWriteWinsStrategy_whenReplicasDiverge_thenAfterMergeShouldKeepOnlyLastValue() { + // given + final LocalCrdtStore crdtStore1 = new LocalCrdtStore("N_1"); + final LocalCrdtStore crdtStore2 = new LocalCrdtStore("N_2"); + crdtStore1.connect(crdtStore2); + + final LWWRegister replica1 = crdtStore1.createLWWRegister("ID_1"); + final LWWRegister replica2 = crdtStore2. findLWWRegister("ID_1").get(); + + // when + replica1.set("apple"); + replica2.set("banana"); + + // then + assertThat(replica1.get()).isEqualTo("banana"); + assertThat(replica2.get()).isEqualTo("banana"); + + // when + crdtStore1.disconnect(crdtStore2); + + replica1.set("strawberry"); + replica2.set("pear"); + + assertThat(replica1.get()).isEqualTo("strawberry"); + assertThat(replica2.get()).isEqualTo("pear"); + + crdtStore1.connect(crdtStore2); + + // then + assertThat(replica1.get()).isEqualTo("pear"); + assertThat(replica2.get()).isEqualTo("pear"); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java deleted file mode 100644 index ee369fc75b..0000000000 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.eclipsecollections; - -import static org.junit.Assert.assertTrue; - -import org.eclipse.collections.api.list.MutableList; -import org.eclipse.collections.impl.block.factory.Predicates; -import org.eclipse.collections.impl.list.mutable.FastList; -import org.junit.Before; -import org.junit.Test; - -public class AllSatisfyPatternTest { - - MutableList list; - - @Before - public void getList() { - this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); - } - - @Test - public void whenAnySatisfiesCondition_thenCorrect() { - boolean result = list.allSatisfy(Predicates.greaterThan(0)); - - assertTrue(result); - } -} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternUnitTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternUnitTest.java new file mode 100644 index 0000000000..b9790e37ea --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertTrue; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Before; +import org.junit.Test; + +public class AllSatisfyPatternUnitTest { + + MutableList list; + + @Before + public void getList() { + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); + } + + @Test + public void whenAnySatisfiesCondition_thenCorrect() { + boolean result = list.allSatisfy(Predicates.greaterThan(0)); + + assertTrue(result); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java deleted file mode 100644 index a3314ebee6..0000000000 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.eclipsecollections; - -import static org.junit.Assert.assertTrue; - -import org.eclipse.collections.api.list.MutableList; -import org.eclipse.collections.impl.block.factory.Predicates; -import org.eclipse.collections.impl.list.mutable.FastList; -import org.junit.Before; -import org.junit.Test; - -public class AnySatisfyPatternTest { - - MutableList list; - - @Before - public void getList() { - this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); - } - - @Test - public void whenAnySatisfiesCondition_thenCorrect() { - boolean result = list.anySatisfy(Predicates.greaterThan(30)); - - assertTrue(result); - } -} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternUnitTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternUnitTest.java new file mode 100644 index 0000000000..d5a736503e --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertTrue; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Before; +import org.junit.Test; + +public class AnySatisfyPatternUnitTest { + + MutableList list; + + @Before + public void getList() { + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); + } + + @Test + public void whenAnySatisfiesCondition_thenCorrect() { + boolean result = list.anySatisfy(Predicates.greaterThan(30)); + + assertTrue(result); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java deleted file mode 100644 index b1aaceb09b..0000000000 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.eclipsecollections; - -import org.eclipse.collections.api.list.MutableList; -import org.eclipse.collections.impl.list.mutable.FastList; - -import org.assertj.core.api.Assertions; -import org.junit.Test; - -public class CollectPatternTest { - - @Test - public void whenCollect_thenCorrect() { - Student student1 = new Student("John", "Hopkins"); - Student student2 = new Student("George", "Adams"); - - MutableList students = FastList.newListWith(student1, student2); - - MutableList lastNames = students.collect(Student::getLastName); - - Assertions.assertThat(lastNames).containsExactly("Hopkins", "Adams"); - } -} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternUnitTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternUnitTest.java new file mode 100644 index 0000000000..ff111a6d72 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.list.mutable.FastList; + +import org.assertj.core.api.Assertions; +import org.junit.Test; + +public class CollectPatternUnitTest { + + @Test + public void whenCollect_thenCorrect() { + Student student1 = new Student("John", "Hopkins"); + Student student2 = new Student("George", "Adams"); + + MutableList students = FastList.newListWith(student1, student2); + + MutableList lastNames = students.collect(Student::getLastName); + + Assertions.assertThat(lastNames).containsExactly("Hopkins", "Adams"); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java deleted file mode 100644 index e279314034..0000000000 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.eclipsecollections; - -import org.assertj.core.api.Assertions; -import org.eclipse.collections.api.list.MutableList; -import org.eclipse.collections.impl.list.mutable.FastList; -import org.junit.Test; - -public class ConvertContainerToAnotherTest { - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void whenConvertContainerToAnother_thenCorrect() { - MutableList cars = (MutableList) ConvertContainerToAnother.convertToList(); - - Assertions.assertThat(cars).containsExactlyElementsOf(FastList.newListWith("Volkswagen", "Toyota", "Mercedes")); - } -} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherUnitTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherUnitTest.java new file mode 100644 index 0000000000..cb2bc11dc0 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.eclipsecollections; + +import org.assertj.core.api.Assertions; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Test; + +public class ConvertContainerToAnotherUnitTest { + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void whenConvertContainerToAnother_thenCorrect() { + MutableList cars = (MutableList) ConvertContainerToAnother.convertToList(); + + Assertions.assertThat(cars).containsExactlyElementsOf(FastList.newListWith("Volkswagen", "Toyota", "Mercedes")); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java deleted file mode 100644 index 4ef7348a0d..0000000000 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.eclipsecollections; - -import org.assertj.core.api.Assertions; -import org.eclipse.collections.api.list.MutableList; -import org.eclipse.collections.impl.block.factory.Predicates; -import org.eclipse.collections.impl.list.mutable.FastList; -import org.junit.Before; -import org.junit.Test; - -public class DetectPatternTest { - - MutableList list; - - @Before - public void getList() { - this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); - } - - @Test - public void whenDetect_thenCorrect() { - Integer result = list.detect(Predicates.greaterThan(30)); - - Assertions.assertThat(result).isEqualTo(41); - } -} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternUnitTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternUnitTest.java new file mode 100644 index 0000000000..1479b06593 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.eclipsecollections; + +import org.assertj.core.api.Assertions; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Before; +import org.junit.Test; + +public class DetectPatternUnitTest { + + MutableList list; + + @Before + public void getList() { + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); + } + + @Test + public void whenDetect_thenCorrect() { + Integer result = list.detect(Predicates.greaterThan(30)); + + Assertions.assertThat(result).isEqualTo(41); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java deleted file mode 100644 index 3091f90908..0000000000 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.eclipsecollections; - -import org.assertj.core.api.Assertions; -import org.eclipse.collections.api.list.MutableList; -import org.eclipse.collections.impl.list.mutable.FastList; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; - -public class FlatCollectTest { - - MutableList addresses1; - MutableList addresses2; - MutableList addresses3; - MutableList addresses4; - - List expectedAddresses; - MutableList students; - - @Before - public void setup() { - String address1 = "73 Pacific St., Forest Hills, NY 11375"; - String address2 = "93 Bayport Ave., South Richmond Hill, NY 11419"; - String address3 = "548 Market St, San Francisco, CA 94104"; - String address4 = "8605 Santa Monica Blvd, West Hollywood, CA 90069"; - - this.addresses1 = FastList.newListWith(address1, address2); - this.addresses2 = FastList.newListWith(address3, address4); - Student student1 = new Student("John", "Hopkins", addresses1); - Student student2 = new Student("George", "Adams", addresses2); - this.addresses2 = FastList.newListWith(address3, address4); - this.students = FastList.newListWith(student1, student2); - this.expectedAddresses = new ArrayList<>(); - this.expectedAddresses.add("73 Pacific St., Forest Hills, NY 11375"); - this.expectedAddresses.add("93 Bayport Ave., South Richmond Hill, NY 11419"); - this.expectedAddresses.add("548 Market St, San Francisco, CA 94104"); - this.expectedAddresses.add("8605 Santa Monica Blvd, West Hollywood, CA 90069"); - } - - @Test - public void whenFlatCollect_thenCorrect() { - MutableList addresses = students.flatCollect(Student::getAddresses); - - Assertions.assertThat(addresses).containsExactlyElementsOf(this.expectedAddresses); - } -} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectUnitTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectUnitTest.java new file mode 100644 index 0000000000..b0735267ae --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.eclipsecollections; + +import org.assertj.core.api.Assertions; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.list.mutable.FastList; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class FlatCollectUnitTest { + + MutableList addresses1; + MutableList addresses2; + MutableList addresses3; + MutableList addresses4; + + List expectedAddresses; + MutableList students; + + @Before + public void setup() { + String address1 = "73 Pacific St., Forest Hills, NY 11375"; + String address2 = "93 Bayport Ave., South Richmond Hill, NY 11419"; + String address3 = "548 Market St, San Francisco, CA 94104"; + String address4 = "8605 Santa Monica Blvd, West Hollywood, CA 90069"; + + this.addresses1 = FastList.newListWith(address1, address2); + this.addresses2 = FastList.newListWith(address3, address4); + Student student1 = new Student("John", "Hopkins", addresses1); + Student student2 = new Student("George", "Adams", addresses2); + this.addresses2 = FastList.newListWith(address3, address4); + this.students = FastList.newListWith(student1, student2); + this.expectedAddresses = new ArrayList<>(); + this.expectedAddresses.add("73 Pacific St., Forest Hills, NY 11375"); + this.expectedAddresses.add("93 Bayport Ave., South Richmond Hill, NY 11419"); + this.expectedAddresses.add("548 Market St, San Francisco, CA 94104"); + this.expectedAddresses.add("8605 Santa Monica Blvd, West Hollywood, CA 90069"); + } + + @Test + public void whenFlatCollect_thenCorrect() { + MutableList addresses = students.flatCollect(Student::getAddresses); + + Assertions.assertThat(addresses).containsExactlyElementsOf(this.expectedAddresses); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java deleted file mode 100644 index 8cea575222..0000000000 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.eclipsecollections; - -import static org.junit.Assert.assertEquals; - -import org.eclipse.collections.api.tuple.Pair; -import org.eclipse.collections.impl.map.mutable.UnifiedMap; -import org.eclipse.collections.impl.tuple.Tuples; -import org.junit.Test; - -public class ForEachPatternTest { - - @SuppressWarnings("unchecked") - @Test - public void whenInstantiateAndChangeValues_thenCorrect() { - Pair pair1 = Tuples.pair(1, "One"); - Pair pair2 = Tuples.pair(2, "Two"); - Pair pair3 = Tuples.pair(3, "Three"); - - UnifiedMap map = UnifiedMap.newMapWith(pair1, pair2, pair3); - - for (int i = 0; i < map.size(); i++) { - map.put(i + 1, "New Value"); - } - - for (int i = 0; i < map.size(); i++) { - assertEquals("New Value", map.get(i + 1)); - } - } -} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternUnitTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternUnitTest.java new file mode 100644 index 0000000000..38d95047ed --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertEquals; + +import org.eclipse.collections.api.tuple.Pair; +import org.eclipse.collections.impl.map.mutable.UnifiedMap; +import org.eclipse.collections.impl.tuple.Tuples; +import org.junit.Test; + +public class ForEachPatternUnitTest { + + @SuppressWarnings("unchecked") + @Test + public void whenInstantiateAndChangeValues_thenCorrect() { + Pair pair1 = Tuples.pair(1, "One"); + Pair pair2 = Tuples.pair(2, "Two"); + Pair pair3 = Tuples.pair(3, "Three"); + + UnifiedMap map = UnifiedMap.newMapWith(pair1, pair2, pair3); + + for (int i = 0; i < map.size(); i++) { + map.put(i + 1, "New Value"); + } + + for (int i = 0; i < map.size(); i++) { + assertEquals("New Value", map.get(i + 1)); + } + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java deleted file mode 100644 index 01a8fcaef4..0000000000 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.eclipsecollections; - -import static org.junit.Assert.assertEquals; - -import java.util.List; - -import org.eclipse.collections.impl.factory.Lists; -import org.junit.Test; - -public class InjectIntoPatternTest { - - @Test - public void whenInjectInto_thenCorrect() { - List list = Lists.mutable.of(1, 2, 3, 4); - int result = 5; - for (int i = 0; i < list.size(); i++) { - Integer v = list.get(i); - result = result + v.intValue(); - } - - assertEquals(15, result); - } -} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternUnitTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternUnitTest.java new file mode 100644 index 0000000000..10448c4474 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertEquals; + +import java.util.List; + +import org.eclipse.collections.impl.factory.Lists; +import org.junit.Test; + +public class InjectIntoPatternUnitTest { + + @Test + public void whenInjectInto_thenCorrect() { + List list = Lists.mutable.of(1, 2, 3, 4); + int result = 5; + for (int i = 0; i < list.size(); i++) { + Integer v = list.get(i); + result = result + v.intValue(); + } + + assertEquals(15, result); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java deleted file mode 100644 index bcb816c34a..0000000000 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.eclipsecollections; - -import org.assertj.core.api.Assertions; -import org.eclipse.collections.api.LazyIterable; -import org.eclipse.collections.api.list.MutableList; -import org.eclipse.collections.impl.factory.Lists; -import org.junit.Test; - -public class LazyIterationTest { - - @Test - public void whenLazyIteration_thenCorrect() { - Student student1 = new Student("John", "Hopkins"); - Student student2 = new Student("George", "Adams"); - Student student3 = new Student("Jennifer", "Rodriguez"); - - MutableList students = Lists.mutable.with(student1, student2, student3); - LazyIterable lazyStudents = students.asLazy(); - LazyIterable lastNames = lazyStudents.collect(Student::getLastName); - - Assertions.assertThat(lastNames).containsAll(Lists.mutable.with("Hopkins", "Adams", "Rodriguez")); - } -} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationUnitTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationUnitTest.java new file mode 100644 index 0000000000..0c3418b7b2 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.eclipsecollections; + +import org.assertj.core.api.Assertions; +import org.eclipse.collections.api.LazyIterable; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.factory.Lists; +import org.junit.Test; + +public class LazyIterationUnitTest { + + @Test + public void whenLazyIteration_thenCorrect() { + Student student1 = new Student("John", "Hopkins"); + Student student2 = new Student("George", "Adams"); + Student student3 = new Student("Jennifer", "Rodriguez"); + + MutableList students = Lists.mutable.with(student1, student2, student3); + LazyIterable lazyStudents = students.asLazy(); + LazyIterable lastNames = lazyStudents.collect(Student::getLastName); + + Assertions.assertThat(lastNames).containsAll(Lists.mutable.with("Hopkins", "Adams", "Rodriguez")); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java deleted file mode 100644 index 8ef18004aa..0000000000 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.eclipsecollections; - -import org.assertj.core.api.Assertions; -import org.eclipse.collections.api.block.predicate.Predicate; -import org.eclipse.collections.api.list.MutableList; -import org.eclipse.collections.api.partition.list.PartitionMutableList; -import org.eclipse.collections.impl.list.mutable.FastList; -import org.junit.Before; -import org.junit.Test; - -public class PartitionPatternTest { - - MutableList list; - - @Before - public void getList() { - this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); - } - - @Test - public void whenAnySatisfiesCondition_thenCorrect() { - MutableList numbers = list; - PartitionMutableList partitionedFolks = numbers.partition(new Predicate() { - - /** - * - */ - private static final long serialVersionUID = -1551138743683678406L; - - public boolean accept(Integer each) { - return each > 30; - } - }); - MutableList greaterThanThirty = partitionedFolks.getSelected().sortThis(); - MutableList smallerThanThirty = partitionedFolks.getRejected().sortThis(); - - Assertions.assertThat(smallerThanThirty).containsExactly(1, 5, 8, 17, 23); - Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41); - } -} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternUnitTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternUnitTest.java new file mode 100644 index 0000000000..e5c27179a9 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.eclipsecollections; + +import org.assertj.core.api.Assertions; +import org.eclipse.collections.api.block.predicate.Predicate; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.partition.list.PartitionMutableList; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Before; +import org.junit.Test; + +public class PartitionPatternUnitTest { + + MutableList list; + + @Before + public void getList() { + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); + } + + @Test + public void whenAnySatisfiesCondition_thenCorrect() { + MutableList numbers = list; + PartitionMutableList partitionedFolks = numbers.partition(new Predicate() { + + /** + * + */ + private static final long serialVersionUID = -1551138743683678406L; + + public boolean accept(Integer each) { + return each > 30; + } + }); + MutableList greaterThanThirty = partitionedFolks.getSelected().sortThis(); + MutableList smallerThanThirty = partitionedFolks.getRejected().sortThis(); + + Assertions.assertThat(smallerThanThirty).containsExactly(1, 5, 8, 17, 23); + Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java deleted file mode 100644 index bd743d56e8..0000000000 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.eclipsecollections; - -import org.assertj.core.api.Assertions; -import org.eclipse.collections.api.list.MutableList; -import org.eclipse.collections.impl.block.factory.Predicates; -import org.eclipse.collections.impl.list.mutable.FastList; -import org.junit.Before; -import org.junit.Test; - -public class RejectPatternTest { - - MutableList list; - MutableList expectedList; - - @Before - public void setup() { - this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); - this.expectedList = FastList.newListWith(1, 5, 8, 17, 23); - } - - @Test - public void whenReject_thenCorrect() { - MutableList notGreaterThanThirty = list.reject(Predicates.greaterThan(30)).sortThis(); - - Assertions.assertThat(notGreaterThanThirty).containsExactlyElementsOf(this.expectedList); - } -} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternUnitTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternUnitTest.java new file mode 100644 index 0000000000..b455938b0b --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.eclipsecollections; + +import org.assertj.core.api.Assertions; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Before; +import org.junit.Test; + +public class RejectPatternUnitTest { + + MutableList list; + MutableList expectedList; + + @Before + public void setup() { + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); + this.expectedList = FastList.newListWith(1, 5, 8, 17, 23); + } + + @Test + public void whenReject_thenCorrect() { + MutableList notGreaterThanThirty = list.reject(Predicates.greaterThan(30)).sortThis(); + + Assertions.assertThat(notGreaterThanThirty).containsExactlyElementsOf(this.expectedList); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java deleted file mode 100644 index 154be08f08..0000000000 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.eclipsecollections; - -import org.assertj.core.api.Assertions; -import org.eclipse.collections.api.list.MutableList; -import org.eclipse.collections.impl.block.factory.Predicates; -import org.eclipse.collections.impl.list.mutable.FastList; -import org.junit.Before; -import org.junit.Test; - -public class SelectPatternTest { - - MutableList list; - - @Before - public void getList() { - this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); - } - - @Test - public void givenListwhenSelect_thenCorrect() { - MutableList greaterThanThirty = list.select(Predicates.greaterThan(30)).sortThis(); - - Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41); - } - - @SuppressWarnings("rawtypes") - public MutableList selectUsingLambda() { - return list.select(each -> each > 30).sortThis(); - } - - @SuppressWarnings("unchecked") - @Test - public void givenListwhenSelectUsingLambda_thenCorrect() { - MutableList greaterThanThirty = selectUsingLambda(); - - Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41); - } -} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternUnitTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternUnitTest.java new file mode 100644 index 0000000000..7735daff65 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.eclipsecollections; + +import org.assertj.core.api.Assertions; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Before; +import org.junit.Test; + +public class SelectPatternUnitTest { + + MutableList list; + + @Before + public void getList() { + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); + } + + @Test + public void givenListwhenSelect_thenCorrect() { + MutableList greaterThanThirty = list.select(Predicates.greaterThan(30)).sortThis(); + + Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41); + } + + @SuppressWarnings("rawtypes") + public MutableList selectUsingLambda() { + return list.select(each -> each > 30).sortThis(); + } + + @SuppressWarnings("unchecked") + @Test + public void givenListwhenSelectUsingLambda_thenCorrect() { + MutableList greaterThanThirty = selectUsingLambda(); + + Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java deleted file mode 100644 index 2b5aa06289..0000000000 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.eclipsecollections; - -import org.eclipse.collections.api.list.MutableList; -import org.eclipse.collections.api.tuple.Pair; -import org.eclipse.collections.impl.factory.Lists; -import org.eclipse.collections.impl.tuple.Tuples; - -import org.assertj.core.api.Assertions; -import org.junit.Before; -import org.junit.Test; - -public class ZipTest { - - MutableList> expectedPairs; - - @SuppressWarnings("unchecked") - @Before - public void setup() { - Pair pair1 = Tuples.pair("1", "Porsche"); - Pair pair2 = Tuples.pair("2", "Volvo"); - Pair pair3 = Tuples.pair("3", "Toyota"); - expectedPairs = Lists.mutable.of(pair1, pair2, pair3); - } - - @Test - public void whenZip_thenCorrect() { - MutableList numbers = Lists.mutable.with("1", "2", "3", "Ignored"); - MutableList cars = Lists.mutable.with("Porsche", "Volvo", "Toyota"); - MutableList> pairs = numbers.zip(cars); - - Assertions.assertThat(pairs).containsExactlyElementsOf(this.expectedPairs); - } -} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipUnitTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipUnitTest.java new file mode 100644 index 0000000000..942cdf4595 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.tuple.Pair; +import org.eclipse.collections.impl.factory.Lists; +import org.eclipse.collections.impl.tuple.Tuples; + +import org.assertj.core.api.Assertions; +import org.junit.Before; +import org.junit.Test; + +public class ZipUnitTest { + + MutableList> expectedPairs; + + @SuppressWarnings("unchecked") + @Before + public void setup() { + Pair pair1 = Tuples.pair("1", "Porsche"); + Pair pair2 = Tuples.pair("2", "Volvo"); + Pair pair3 = Tuples.pair("3", "Toyota"); + expectedPairs = Lists.mutable.of(pair1, pair2, pair3); + } + + @Test + public void whenZip_thenCorrect() { + MutableList numbers = Lists.mutable.with("1", "2", "3", "Ignored"); + MutableList cars = Lists.mutable.with("Porsche", "Volvo", "Toyota"); + MutableList> pairs = numbers.zip(cars); + + Assertions.assertThat(pairs).containsExactlyElementsOf(this.expectedPairs); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java deleted file mode 100644 index 724f693011..0000000000 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.eclipsecollections; - -import org.assertj.core.api.Assertions; -import org.eclipse.collections.api.list.MutableList; -import org.eclipse.collections.api.tuple.Pair; -import org.eclipse.collections.impl.factory.Lists; -import org.eclipse.collections.impl.list.mutable.FastList; -import org.eclipse.collections.impl.tuple.Tuples; -import org.junit.Before; -import org.junit.Test; - -public class ZipWithIndexTest { - - MutableList> expectedPairs; - - @SuppressWarnings("unchecked") - @Before - public void setup() { - Pair pair1 = Tuples.pair("Porsche", 0); - Pair pair2 = Tuples.pair("Volvo", 1); - Pair pair3 = Tuples.pair("Toyota", 2); - expectedPairs = Lists.mutable.of(pair1, pair2, pair3); - } - - @Test - public void whenZip_thenCorrect() { - MutableList cars = FastList.newListWith("Porsche", "Volvo", "Toyota"); - MutableList> pairs = cars.zipWithIndex(); - - Assertions.assertThat(pairs).containsExactlyElementsOf(this.expectedPairs); - } -} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexUnitTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexUnitTest.java new file mode 100644 index 0000000000..b297d1d1eb --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.eclipsecollections; + +import org.assertj.core.api.Assertions; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.tuple.Pair; +import org.eclipse.collections.impl.factory.Lists; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.eclipse.collections.impl.tuple.Tuples; +import org.junit.Before; +import org.junit.Test; + +public class ZipWithIndexUnitTest { + + MutableList> expectedPairs; + + @SuppressWarnings("unchecked") + @Before + public void setup() { + Pair pair1 = Tuples.pair("Porsche", 0); + Pair pair2 = Tuples.pair("Volvo", 1); + Pair pair3 = Tuples.pair("Toyota", 2); + expectedPairs = Lists.mutable.of(pair1, pair2, pair3); + } + + @Test + public void whenZip_thenCorrect() { + MutableList cars = FastList.newListWith("Porsche", "Volvo", "Toyota"); + MutableList> pairs = cars.zipWithIndex(); + + Assertions.assertThat(pairs).containsExactlyElementsOf(this.expectedPairs); + } +} diff --git a/libraries/src/test/java/com/baeldung/fj/FunctionalJavaTest.java b/libraries/src/test/java/com/baeldung/fj/FunctionalJavaTest.java deleted file mode 100644 index 33952c8669..0000000000 --- a/libraries/src/test/java/com/baeldung/fj/FunctionalJavaTest.java +++ /dev/null @@ -1,79 +0,0 @@ -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/fj/FunctionalJavaUnitTest.java b/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java new file mode 100644 index 0000000000..d62a115abd --- /dev/null +++ b/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.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 FunctionalJavaUnitTest { + + 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/flink/BackupCreatorIntegrationTest.java b/libraries/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java new file mode 100644 index 0000000000..ab7d119c16 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java @@ -0,0 +1,103 @@ +package com.baeldung.flink; + +import com.baeldung.flink.model.Backup; +import com.baeldung.flink.model.InputMessage; +import com.baeldung.flink.operator.BackupAggregator; +import com.baeldung.flink.operator.InputMessageTimestampAssigner; +import com.baeldung.flink.schema.BackupSerializationSchema; +import com.baeldung.flink.schema.InputMessageDeserializationSchema; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.apache.commons.collections.ListUtils; +import org.apache.flink.api.common.serialization.DeserializationSchema; +import org.apache.flink.api.common.serialization.SerializationSchema; +import org.apache.flink.streaming.api.TimeCharacteristic; +import org.apache.flink.streaming.api.datastream.DataStreamSource; +import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; +import org.apache.flink.streaming.api.functions.sink.SinkFunction; +import org.apache.flink.streaming.api.windowing.time.Time; +import org.awaitility.Awaitility; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class BackupCreatorIntegrationTest { + public static ObjectMapper mapper; + + @Before + public void setup() { + mapper = new ObjectMapper().registerModule(new JavaTimeModule()); + } + + @Test + public void givenProperJson_whenDeserializeIsInvoked_thenProperObjectIsReturned() throws IOException { + InputMessage message = new InputMessage("Me", "User", LocalDateTime.now(), "Test Message"); + byte[] messageSerialized = mapper.writeValueAsBytes(message); + DeserializationSchema deserializationSchema = new InputMessageDeserializationSchema(); + InputMessage messageDeserialized = deserializationSchema.deserialize(messageSerialized); + + assertEquals(message, messageDeserialized); + } + + @Test + public void givenMultipleInputMessagesFromDifferentDays_whenBackupCreatorIsUser_thenMessagesAreGroupedProperly() throws Exception { + LocalDateTime currentTime = LocalDateTime.now(); + InputMessage message = new InputMessage("Me", "User", currentTime, "First TestMessage"); + InputMessage secondMessage = new InputMessage("Me", "User", currentTime.plusHours(1), "First TestMessage"); + InputMessage thirdMessage = new InputMessage("Me", "User", currentTime.plusHours(2), "First TestMessage"); + InputMessage fourthMessage = new InputMessage("Me", "User", currentTime.plusHours(3), "First TestMessage"); + InputMessage fifthMessage = new InputMessage("Me", "User", currentTime.plusHours(25), "First TestMessage"); + InputMessage sixthMessage = new InputMessage("Me", "User", currentTime.plusHours(26), "First TestMessage"); + + List firstBackupMessages = Arrays.asList(message, secondMessage, thirdMessage, fourthMessage); + List secondBackupMessages = Arrays.asList(fifthMessage, sixthMessage); + List inputMessages = ListUtils.union(firstBackupMessages, secondBackupMessages); + + StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); + env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); + env.setParallelism(1); + DataStreamSource testDataSet = env.fromCollection(inputMessages); + CollectingSink sink = new CollectingSink(); + testDataSet.assignTimestampsAndWatermarks(new InputMessageTimestampAssigner()) + .timeWindowAll(Time.hours(24)) + .aggregate(new BackupAggregator()) + .addSink(sink); + + env.execute(); + + Awaitility.await().until(() -> sink.backups.size() == 2); + assertEquals(2, sink.backups.size()); + assertEquals(firstBackupMessages, sink.backups.get(0).getInputMessages()); + assertEquals(secondBackupMessages, sink.backups.get(1).getInputMessages()); + + } + + @Test + public void givenProperBackupObject_whenSerializeIsInvoked_thenObjectIsProperlySerialized() throws IOException { + InputMessage message = new InputMessage("Me", "User", LocalDateTime.now(), "Test Message"); + List messages = Arrays.asList(message); + Backup backup = new Backup(messages, LocalDateTime.now()); + byte[] backupSerialized = mapper.writeValueAsBytes(backup); + SerializationSchema serializationSchema = new BackupSerializationSchema(); + byte[] backupProcessed = serializationSchema.serialize(backup); + + assertEquals(backupSerialized, backupProcessed); + } + + private static class CollectingSink implements SinkFunction { + + public static List backups = new ArrayList<>(); + + @Override + public synchronized void invoke(Backup value, Context context) throws Exception { + backups.add(value); + } + } +} diff --git a/libraries/src/test/java/com/baeldung/flink/WordCapitalizerIntegrationTest.java b/libraries/src/test/java/com/baeldung/flink/WordCapitalizerIntegrationTest.java new file mode 100644 index 0000000000..8a98dae4b5 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/flink/WordCapitalizerIntegrationTest.java @@ -0,0 +1,34 @@ +package com.baeldung.flink; + +import com.baeldung.flink.operator.WordsCapitalizer; +import org.apache.flink.api.java.DataSet; +import org.apache.flink.api.java.ExecutionEnvironment; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class WordCapitalizerIntegrationTest { + + @Test + public void givenDataSet_whenExecuteWordCapitalizer_thenReturnCapitalizedWords() throws Exception { + ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); + List data = Arrays.asList("dog", "cat", "wolf", "pig"); + + DataSet testDataSet = env.fromCollection(data); + + + List dataProcessed = testDataSet + .map(new WordsCapitalizer()) + .collect(); + + List testDataCapitalized = data.stream() + .map(String::toUpperCase) + .collect(Collectors.toList()); + + Assert.assertEquals(testDataCapitalized, dataProcessed); + } + +} diff --git a/libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java b/libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java new file mode 100644 index 0000000000..43da69f96d --- /dev/null +++ b/libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java @@ -0,0 +1,73 @@ +package com.baeldung.ftp; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockftpserver.fake.FakeFtpServer; +import org.mockftpserver.fake.UserAccount; +import org.mockftpserver.fake.filesystem.DirectoryEntry; +import org.mockftpserver.fake.filesystem.FileEntry; +import org.mockftpserver.fake.filesystem.FileSystem; +import org.mockftpserver.fake.filesystem.UnixFakeFileSystem; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.Collection; + +import static org.assertj.core.api.Assertions.assertThat; + +public class FtpClientIntegrationTest { + + private FakeFtpServer fakeFtpServer; + + private FtpClient ftpClient; + + @Before + public void setup() throws IOException { + fakeFtpServer = new FakeFtpServer(); + fakeFtpServer.addUserAccount(new UserAccount("user", "password", "/data")); + + FileSystem fileSystem = new UnixFakeFileSystem(); + fileSystem.add(new DirectoryEntry("/data")); + fileSystem.add(new FileEntry("/data/foobar.txt", "abcdef 1234567890")); + fakeFtpServer.setFileSystem(fileSystem); + fakeFtpServer.setServerControlPort(0); + + fakeFtpServer.start(); + + ftpClient = new FtpClient("localhost", fakeFtpServer.getServerControlPort(), "user", "password"); + ftpClient.open(); + } + + @After + public void teardown() throws IOException { + ftpClient.close(); + fakeFtpServer.stop(); + } + + @Test + public void givenRemoteFile_whenListingRemoteFiles_thenItIsContainedInList() throws IOException { + Collection files = ftpClient.listFiles(""); + + assertThat(files).contains("foobar.txt"); + } + + @Test + public void givenRemoteFile_whenDownloading_thenItIsOnTheLocalFilesystem() throws IOException { + ftpClient.downloadFile("/foobar.txt", "downloaded_buz.txt"); + + assertThat(new File("downloaded_buz.txt")).exists(); + new File("downloaded_buz.txt").delete(); // cleanup + } + + @Test + public void givenLocalFile_whenUploadingIt_thenItExistsOnRemoteLocation() throws URISyntaxException, IOException { + File file = new File(getClass().getClassLoader().getResource("ftp/baz.txt").toURI()); + + ftpClient.putFileToPath(file, "/buz.txt"); + + assertThat(fakeFtpServer.getFileSystem().exists("/buz.txt")).isTrue(); + } + +} diff --git a/libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java b/libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java new file mode 100644 index 0000000000..ef6809b02d --- /dev/null +++ b/libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java @@ -0,0 +1,63 @@ +package com.baeldung.ftp; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockftpserver.fake.FakeFtpServer; +import org.mockftpserver.fake.UserAccount; +import org.mockftpserver.fake.filesystem.DirectoryEntry; +import org.mockftpserver.fake.filesystem.FileEntry; +import org.mockftpserver.fake.filesystem.FileSystem; +import org.mockftpserver.fake.filesystem.UnixFakeFileSystem; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; +import java.nio.file.Files; +import java.util.Collection; + +import static org.assertj.core.api.Assertions.assertThat; + +public class JdkFtpClientIntegrationTest { + + private FakeFtpServer fakeFtpServer; + + + @Before + public void setup() throws IOException { + fakeFtpServer = new FakeFtpServer(); + fakeFtpServer.addUserAccount(new UserAccount("user", "password", "/data")); + + FileSystem fileSystem = new UnixFakeFileSystem(); + fileSystem.add(new DirectoryEntry("/data")); + fileSystem.add(new FileEntry("/data/foobar.txt", "abcdef 1234567890")); + fakeFtpServer.setFileSystem(fileSystem); + fakeFtpServer.setServerControlPort(0); + + fakeFtpServer.start(); + } + + @After + public void teardown() throws IOException { + fakeFtpServer.stop(); + } + + @Test + public void givenRemoteFile_whenDownloading_thenItIsOnTheLocalFilesystem() throws IOException { + String ftpUrl = String.format("ftp://user:password@localhost:%d/foobar.txt", fakeFtpServer.getServerControlPort()); + + URLConnection urlConnection = new URL(ftpUrl).openConnection(); + InputStream inputStream = urlConnection.getInputStream(); + Files.copy(inputStream, new File("downloaded_buz.txt").toPath()); + inputStream.close(); + + assertThat(new File("downloaded_buz.txt")).exists(); + + new File("downloaded_buz.txt").delete(); // cleanup + } + +} diff --git a/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java deleted file mode 100644 index 09d31eac21..0000000000 --- a/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.baeldung.hoverfly; - -import static io.specto.hoverfly.junit.core.SimulationSource.dsl; -import static io.specto.hoverfly.junit.dsl.HoverflyDsl.service; -import static io.specto.hoverfly.junit.dsl.HttpBodyConverter.jsonWithSingleQuotes; -import static io.specto.hoverfly.junit.dsl.ResponseCreators.success; -import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.any; -import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsTo; -import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToJson; -import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToXml; -import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matches; -import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.startsWith; -import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesJsonPath; -import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesXPath; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.concurrent.TimeUnit; - -import org.apache.commons.lang3.time.StopWatch; -import org.junit.ClassRule; -import org.junit.Test; -import org.springframework.http.HttpStatus; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.web.client.RestTemplate; - -import io.specto.hoverfly.junit.core.SimulationSource; -import io.specto.hoverfly.junit.rule.HoverflyRule; - -public class HoverflyApiIntegrationTest { - - private static final SimulationSource source = dsl(service("http://www.baeldung.com").get("/api/courses/1").willReturn(success().body(jsonWithSingleQuotes("{'id':'1','name':'HCI'}"))) - - .post("/api/courses").willReturn(success()) - - .andDelay(3, TimeUnit.SECONDS).forMethod("POST"), - - service(matches("www.*dung.com")).get(startsWith("/api/student")).queryParam("page", any()).willReturn(success()) - - .post(equalsTo("/api/student")).body(equalsToJson(jsonWithSingleQuotes("{'id':'1','name':'Joe'}"))).willReturn(success()) - - .put("/api/student/1").body(matchesJsonPath("$.name")).willReturn(success()) - - .post("/api/student").body(equalsToXml("2John")).willReturn(success()) - - .put("/api/student/2").body(matchesXPath("/student/name")).willReturn(success())); - - @ClassRule - public static final HoverflyRule rule = HoverflyRule.inSimulationMode(source); - private final RestTemplate restTemplate = new RestTemplate(); - - @Test - public void givenGetCourseById_whenRequestSimulated_thenAPICalledSuccessfully() throws URISyntaxException { - final ResponseEntity courseResponse = restTemplate.getForEntity("http://www.baeldung.com/api/courses/1", String.class); - - assertEquals(HttpStatus.OK, courseResponse.getStatusCode()); - assertEquals("{\"id\":\"1\",\"name\":\"HCI\"}", courseResponse.getBody()); - } - - @Test - public void givenPostCourse_whenDelayInRequest_thenResponseIsDelayed() throws URISyntaxException { - StopWatch stopWatch = new StopWatch(); - stopWatch.start(); - final ResponseEntity postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/courses", null, Void.class); - stopWatch.stop(); - long postTime = stopWatch.getTime(); - - assertEquals(HttpStatus.OK, postResponse.getStatusCode()); - assertTrue(3L <= TimeUnit.MILLISECONDS.toSeconds(postTime)); - } - - @Test - public void givenGetStudent_whenRequestMatcher_thenAPICalledSuccessfully() throws URISyntaxException { - final ResponseEntity courseResponse = restTemplate.getForEntity("http://www.baeldung.com/api/student?page=3", Void.class); - - assertEquals(HttpStatus.OK, courseResponse.getStatusCode()); - } - - @Test - public void givenPostStudent_whenBodyRequestMatcherJson_thenResponseContainsEqualJson() throws URISyntaxException { - final ResponseEntity postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/student", "{\"id\":\"1\",\"name\":\"Joe\"}", Void.class); - - assertEquals(HttpStatus.OK, postResponse.getStatusCode()); - } - - @Test - public void givenPutStudent_whenJsonPathMatcher_thenRequestJsonContainsElementInPath() throws URISyntaxException { - RequestEntity putRequest = RequestEntity.put(new URI("http://www.baeldung.com/api/student/1")).body("{\"id\":\"1\",\"name\":\"Trevor\"}"); - - ResponseEntity putResponse = restTemplate.exchange(putRequest, String.class); - assertEquals(HttpStatus.OK, putResponse.getStatusCode()); - } - - @Test - public void givenPostStudent_whenBodyRequestMatcherXml_thenResponseContainsEqualXml() throws URISyntaxException { - final ResponseEntity postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/student", "2John", Void.class); - - assertEquals(HttpStatus.OK, postResponse.getStatusCode()); - } - - @Test - public void givenPutStudent_whenXPathMatcher_thenRequestXmlContainsElementInXPath() throws URISyntaxException { - RequestEntity putRequest = RequestEntity.put(new URI("http://www.baeldung.com/api/student/2")).body("" + "2Monica"); - - ResponseEntity putResponse = restTemplate.exchange(putRequest, String.class); - assertEquals(HttpStatus.OK, putResponse.getStatusCode()); - } -} diff --git a/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiLiveTest.java b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiLiveTest.java new file mode 100644 index 0000000000..8d60b40bb0 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiLiveTest.java @@ -0,0 +1,112 @@ +package com.baeldung.hoverfly; + +import static io.specto.hoverfly.junit.core.SimulationSource.dsl; +import static io.specto.hoverfly.junit.dsl.HoverflyDsl.service; +import static io.specto.hoverfly.junit.dsl.HttpBodyConverter.jsonWithSingleQuotes; +import static io.specto.hoverfly.junit.dsl.ResponseCreators.success; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.any; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsTo; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToJson; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToXml; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matches; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.startsWith; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesJsonPath; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesXPath; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.lang3.time.StopWatch; +import org.junit.ClassRule; +import org.junit.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import io.specto.hoverfly.junit.core.SimulationSource; +import io.specto.hoverfly.junit.rule.HoverflyRule; + +public class HoverflyApiLiveTest { + + private static final SimulationSource source = dsl(service("http://www.baeldung.com").get("/api/courses/1").willReturn(success().body(jsonWithSingleQuotes("{'id':'1','name':'HCI'}"))) + + .post("/api/courses").willReturn(success()) + + .andDelay(3, TimeUnit.SECONDS).forMethod("POST"), + + service(matches("www.*dung.com")).get(startsWith("/api/student")).queryParam("page", any()).willReturn(success()) + + .post(equalsTo("/api/student")).body(equalsToJson(jsonWithSingleQuotes("{'id':'1','name':'Joe'}"))).willReturn(success()) + + .put("/api/student/1").body(matchesJsonPath("$.name")).willReturn(success()) + + .post("/api/student").body(equalsToXml("2John")).willReturn(success()) + + .put("/api/student/2").body(matchesXPath("/student/name")).willReturn(success())); + + @ClassRule + public static final HoverflyRule rule = HoverflyRule.inSimulationMode(source); + private final RestTemplate restTemplate = new RestTemplate(); + + @Test + public void givenGetCourseById_whenRequestSimulated_thenAPICalledSuccessfully() throws URISyntaxException { + final ResponseEntity courseResponse = restTemplate.getForEntity("http://www.baeldung.com/api/courses/1", String.class); + + assertEquals(HttpStatus.OK, courseResponse.getStatusCode()); + assertEquals("{\"id\":\"1\",\"name\":\"HCI\"}", courseResponse.getBody()); + } + + @Test + public void givenPostCourse_whenDelayInRequest_thenResponseIsDelayed() throws URISyntaxException { + StopWatch stopWatch = new StopWatch(); + stopWatch.start(); + final ResponseEntity postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/courses", null, Void.class); + stopWatch.stop(); + long postTime = stopWatch.getTime(); + + assertEquals(HttpStatus.OK, postResponse.getStatusCode()); + assertTrue(3L <= TimeUnit.MILLISECONDS.toSeconds(postTime)); + } + + @Test + public void givenGetStudent_whenRequestMatcher_thenAPICalledSuccessfully() throws URISyntaxException { + final ResponseEntity courseResponse = restTemplate.getForEntity("http://www.baeldung.com/api/student?page=3", Void.class); + + assertEquals(HttpStatus.OK, courseResponse.getStatusCode()); + } + + @Test + public void givenPostStudent_whenBodyRequestMatcherJson_thenResponseContainsEqualJson() throws URISyntaxException { + final ResponseEntity postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/student", "{\"id\":\"1\",\"name\":\"Joe\"}", Void.class); + + assertEquals(HttpStatus.OK, postResponse.getStatusCode()); + } + + @Test + public void givenPutStudent_whenJsonPathMatcher_thenRequestJsonContainsElementInPath() throws URISyntaxException { + RequestEntity putRequest = RequestEntity.put(new URI("http://www.baeldung.com/api/student/1")).body("{\"id\":\"1\",\"name\":\"Trevor\"}"); + + ResponseEntity putResponse = restTemplate.exchange(putRequest, String.class); + assertEquals(HttpStatus.OK, putResponse.getStatusCode()); + } + + @Test + public void givenPostStudent_whenBodyRequestMatcherXml_thenResponseContainsEqualXml() throws URISyntaxException { + final ResponseEntity postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/student", "2John", Void.class); + + assertEquals(HttpStatus.OK, postResponse.getStatusCode()); + } + + @Test + public void givenPutStudent_whenXPathMatcher_thenRequestXmlContainsElementInXPath() throws URISyntaxException { + RequestEntity putRequest = RequestEntity.put(new URI("http://www.baeldung.com/api/student/2")).body("" + "2Monica"); + + ResponseEntity putResponse = restTemplate.exchange(putRequest, String.class); + assertEquals(HttpStatus.OK, putResponse.getStatusCode()); + } +} diff --git a/libraries/src/test/java/com/baeldung/infinispan/AbstractIntegrationTest.java b/libraries/src/test/java/com/baeldung/infinispan/AbstractIntegrationTest.java new file mode 100644 index 0000000000..2a9d430430 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/infinispan/AbstractIntegrationTest.java @@ -0,0 +1,57 @@ +package com.baeldung.infinispan; + +import com.baeldung.infinispan.listener.CacheListener; +import com.baeldung.infinispan.repository.HelloWorldRepository; +import com.baeldung.infinispan.service.HelloWorldService; +import com.baeldung.infinispan.service.TransactionalService; +import org.infinispan.Cache; +import org.infinispan.manager.DefaultCacheManager; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; + +import java.util.function.Supplier; + +@Ignore +public abstract class AbstractIntegrationTest { + + private DefaultCacheManager cacheManager; + + private HelloWorldRepository repository = new HelloWorldRepository(); + + protected HelloWorldService helloWorldService; + protected TransactionalService transactionalService; + + @Before + public void setup() { + CacheConfiguration configuration = new CacheConfiguration(); + CacheListener listener = new CacheListener(); + + cacheManager = configuration.cacheManager(); + + Cache transactionalCache = configuration.transactionalCache(cacheManager, listener); + + Cache simpleHelloWorldCache = configuration.simpleHelloWorldCache(cacheManager, listener); + + Cache expiringHelloWorldCache = configuration.expiringHelloWorldCache(cacheManager, listener); + + Cache evictingHelloWorldCache = configuration.evictingHelloWorldCache(cacheManager, listener); + + Cache passivatingHelloWorldCache = configuration.passivatingHelloWorldCache(cacheManager, listener); + + this.helloWorldService = new HelloWorldService(repository, listener, simpleHelloWorldCache, expiringHelloWorldCache, evictingHelloWorldCache, passivatingHelloWorldCache); + + this.transactionalService = new TransactionalService(transactionalCache); + } + + @After + public void tearDown() { + cacheManager.stop(); + } + + protected long timeThis(Supplier supplier) { + long millis = System.currentTimeMillis(); + supplier.get(); + return System.currentTimeMillis() - millis; + } +} diff --git a/libraries/src/test/java/com/baeldung/infinispan/ConfigurationTest.java b/libraries/src/test/java/com/baeldung/infinispan/ConfigurationTest.java deleted file mode 100644 index 9210b18f0c..0000000000 --- a/libraries/src/test/java/com/baeldung/infinispan/ConfigurationTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.baeldung.infinispan; - -import com.baeldung.infinispan.listener.CacheListener; -import com.baeldung.infinispan.repository.HelloWorldRepository; -import com.baeldung.infinispan.service.HelloWorldService; -import com.baeldung.infinispan.service.TransactionalService; -import org.infinispan.Cache; -import org.infinispan.manager.DefaultCacheManager; -import org.junit.After; -import org.junit.Before; - -import java.util.function.Supplier; - -public class ConfigurationTest { - - private DefaultCacheManager cacheManager; - - private HelloWorldRepository repository = new HelloWorldRepository(); - - protected HelloWorldService helloWorldService; - protected TransactionalService transactionalService; - - @Before - public void setup() { - CacheConfiguration configuration = new CacheConfiguration(); - CacheListener listener = new CacheListener(); - - cacheManager = configuration.cacheManager(); - - Cache transactionalCache = configuration.transactionalCache(cacheManager, listener); - - Cache simpleHelloWorldCache = configuration.simpleHelloWorldCache(cacheManager, listener); - - Cache expiringHelloWorldCache = configuration.expiringHelloWorldCache(cacheManager, listener); - - Cache evictingHelloWorldCache = configuration.evictingHelloWorldCache(cacheManager, listener); - - Cache passivatingHelloWorldCache = configuration.passivatingHelloWorldCache(cacheManager, listener); - - this.helloWorldService = new HelloWorldService(repository, listener, simpleHelloWorldCache, expiringHelloWorldCache, evictingHelloWorldCache, passivatingHelloWorldCache); - - this.transactionalService = new TransactionalService(transactionalCache); - } - - @After - public void tearDown() { - cacheManager.stop(); - } - - protected long timeThis(Supplier supplier) { - long millis = System.currentTimeMillis(); - supplier.get(); - return System.currentTimeMillis() - millis; - } -} diff --git a/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceIntegrationTest.java b/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceIntegrationTest.java deleted file mode 100644 index 0a2ace9ca0..0000000000 --- a/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceIntegrationTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.infinispan.service; - -import com.baeldung.infinispan.ConfigurationTest; -import org.junit.Test; - -import static org.assertj.core.api.Java6Assertions.assertThat; - -public class HelloWorldServiceIntegrationTest extends ConfigurationTest { - - @Test - public void whenGetIsCalledTwoTimes_thenTheSecondShouldHitTheCache() { - assertThat(timeThis(() -> helloWorldService.findSimpleHelloWorld())).isGreaterThanOrEqualTo(1000); - - assertThat(timeThis(() -> helloWorldService.findSimpleHelloWorld())).isLessThan(100); - } - - @Test - public void whenGetIsCalledTwoTimesQuickly_thenTheSecondShouldHitTheCache() { - assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isGreaterThanOrEqualTo(1000); - - assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isLessThan(100); - } - - @Test - public void whenGetIsCalledTwoTimesSparsely_thenNeitherShouldHitTheCache() throws InterruptedException { - assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isGreaterThanOrEqualTo(1000); - - Thread.sleep(1100); - - assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isGreaterThanOrEqualTo(1000); - } - - @Test - public void givenOneEntryIsConfigured_whenTwoAreAdded_thenFirstShouldntBeAvailable() { - assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 1"))).isGreaterThanOrEqualTo(1000); - - assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 2"))).isGreaterThanOrEqualTo(1000); - - assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 1"))).isGreaterThanOrEqualTo(1000); - } - - @Test - public void givenOneEntryIsConfigured_whenTwoAreAdded_thenTheFirstShouldBeAvailable() { - assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 1"))).isGreaterThanOrEqualTo(1000); - - assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 2"))).isGreaterThanOrEqualTo(1000); - - assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 1"))).isLessThan(100); - } - -} diff --git a/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceTemporaryLiveTest.java b/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceTemporaryLiveTest.java new file mode 100644 index 0000000000..46cc77cbba --- /dev/null +++ b/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceTemporaryLiveTest.java @@ -0,0 +1,51 @@ +package com.baeldung.infinispan.service; + +import com.baeldung.infinispan.AbstractIntegrationTest; +import org.junit.Test; + +import static org.assertj.core.api.Java6Assertions.assertThat; + +public class HelloWorldServiceTemporaryLiveTest extends AbstractIntegrationTest { + + @Test + public void whenGetIsCalledTwoTimes_thenTheSecondShouldHitTheCache() { + assertThat(timeThis(() -> helloWorldService.findSimpleHelloWorld())).isGreaterThanOrEqualTo(1000); + + assertThat(timeThis(() -> helloWorldService.findSimpleHelloWorld())).isLessThan(100); + } + + @Test + public void whenGetIsCalledTwoTimesQuickly_thenTheSecondShouldHitTheCache() { + assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isGreaterThanOrEqualTo(1000); + + assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isLessThan(100); + } + + @Test + public void whenGetIsCalledTwoTimesSparsely_thenNeitherShouldHitTheCache() throws InterruptedException { + assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isGreaterThanOrEqualTo(1000); + + Thread.sleep(1100); + + assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isGreaterThanOrEqualTo(1000); + } + + @Test + public void givenOneEntryIsConfigured_whenTwoAreAdded_thenFirstShouldntBeAvailable() { + assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 1"))).isGreaterThanOrEqualTo(1000); + + assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 2"))).isGreaterThanOrEqualTo(1000); + + assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 1"))).isGreaterThanOrEqualTo(1000); + } + + @Test + public void givenOneEntryIsConfigured_whenTwoAreAdded_thenTheFirstShouldBeAvailable() { + assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 1"))).isGreaterThanOrEqualTo(1000); + + assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 2"))).isGreaterThanOrEqualTo(1000); + + assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 1"))).isLessThan(100); + } + +} diff --git a/libraries/src/test/java/com/baeldung/infinispan/service/TransactionalServiceIntegrationTest.java b/libraries/src/test/java/com/baeldung/infinispan/service/TransactionalServiceIntegrationTest.java index ace99eef36..800c6c2775 100644 --- a/libraries/src/test/java/com/baeldung/infinispan/service/TransactionalServiceIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/infinispan/service/TransactionalServiceIntegrationTest.java @@ -1,11 +1,11 @@ package com.baeldung.infinispan.service; -import com.baeldung.infinispan.ConfigurationTest; +import com.baeldung.infinispan.AbstractIntegrationTest; import org.junit.Test; import static org.assertj.core.api.Java6Assertions.assertThat; -public class TransactionalServiceIntegrationTest extends ConfigurationTest { +public class TransactionalServiceIntegrationTest extends AbstractIntegrationTest { @Test public void whenLockingAnEntry_thenItShouldBeInaccessible() throws InterruptedException { diff --git a/libraries/src/test/java/com/baeldung/javapoet/test/PersonGeneratorUnitTest.java b/libraries/src/test/java/com/baeldung/javapoet/test/PersonGeneratorUnitTest.java new file mode 100644 index 0000000000..61bf3ebc33 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/javapoet/test/PersonGeneratorUnitTest.java @@ -0,0 +1,99 @@ +package com.baeldung.javapoet.test; + +import com.baeldung.javapoet.PersonGenerator; +import org.apache.commons.io.FileUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +@RunWith(JUnit4.class) +public class PersonGeneratorUnitTest { + + private PersonGenerator generator; + private Path generatedFolderPath; + private Path expectedFolderPath; + + @Before + public void setUp() { + String packagePath = this + .getClass() + .getPackage() + .getName() + .replace(".", "/") + "/person"; + generator = new PersonGenerator(); + generatedFolderPath = generator + .getOutputPath() + .resolve(packagePath); + expectedFolderPath = Paths.get(new File(".").getAbsolutePath() + "/src/test/java/" + packagePath); + } + + @After + public void tearDown() throws Exception { + FileUtils.deleteDirectory(new File(generator + .getOutputPath() + .toUri())); + } + + @Test + public void whenGenerateGenderEnum_thenGenerateGenderEnumAndWriteToFile() throws IOException { + generator.generateGenderEnum(); + String fileName = "Gender.java"; + assertThatFileIsGeneratedAsExpected(fileName); + deleteGeneratedFile(fileName); + } + + @Test + public void whenGeneratePersonInterface_thenGeneratePersonInterfaceAndWriteToFile() throws IOException { + generator.generatePersonInterface(); + String fileName = "Person.java"; + assertThatFileIsGeneratedAsExpected(fileName); + deleteGeneratedFile(fileName); + } + + @Test + public void whenGenerateStudentClass_thenGenerateStudentClassAndWriteToFile() throws IOException { + generator.generateStudentClass(); + String fileName = "Student.java"; + assertThatFileIsGeneratedAsExpected(fileName); + deleteGeneratedFile(fileName); + } + + private void assertThatFileIsGeneratedAsExpected(String fileName) throws IOException { + String generatedFileContent = extractFileContent(generatedFolderPath.resolve(fileName)); + String expectedFileContent = extractFileContent(expectedFolderPath.resolve(fileName)); + + assertThat("Generated file is identical to the file with the expected content", generatedFileContent, is(equalTo(expectedFileContent))); + + } + + private void deleteGeneratedFile(String fileName) throws IOException { + Path generatedFilePath = generatedFolderPath.resolve(fileName); + Files.delete(generatedFilePath); + } + + private String extractFileContent(Path filePath) throws IOException { + byte[] fileContentAsBytes = Files.readAllBytes(filePath); + String fileContentAsString = new String(fileContentAsBytes, StandardCharsets.UTF_8); + + if (!fileContentAsString.contains("\r\n")) { + // file is not in DOS format + // convert it first, so that the content comparison will be relevant + return fileContentAsString.replaceAll("\n", "\r\n"); + } + return fileContentAsString; + } + +} diff --git a/libraries/src/test/java/com/baeldung/javapoet/test/person/Gender.java b/libraries/src/test/java/com/baeldung/javapoet/test/person/Gender.java new file mode 100644 index 0000000000..3c5657fb9d --- /dev/null +++ b/libraries/src/test/java/com/baeldung/javapoet/test/person/Gender.java @@ -0,0 +1,9 @@ +package com.baeldung.javapoet.test.person; + +public enum Gender { + MALE, + + FEMALE, + + UNSPECIFIED +} diff --git a/libraries/src/test/java/com/baeldung/javapoet/test/person/Person.java b/libraries/src/test/java/com/baeldung/javapoet/test/person/Person.java new file mode 100644 index 0000000000..fae8b23075 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/javapoet/test/person/Person.java @@ -0,0 +1,13 @@ +package com.baeldung.javapoet.test.person; + +import java.lang.String; + +public interface Person { + String DEFAULT_NAME = "Alice"; + + String getName(); + + default String getDefaultName() { + return DEFAULT_NAME; + } +} diff --git a/libraries/src/test/java/com/baeldung/javapoet/test/person/Student.java b/libraries/src/test/java/com/baeldung/javapoet/test/person/Student.java new file mode 100644 index 0000000000..1c7d5cc096 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/javapoet/test/person/Student.java @@ -0,0 +1,37 @@ +package com.baeldung.javapoet.test.person; + +import java.lang.Override; +import java.lang.String; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.stream.IntStream; + +public class Student implements Person { + private String name; + + @Override + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public void printNameMultipleTimes() { + List names = new ArrayList<>(); + IntStream.range(0, 10).forEach(i -> names.add(name)); + names.forEach(System.out::println); + } + + public static void sortByLength(List strings) { + Collections.sort(strings, new Comparator() { + @Override + public int compare(String a, String b) { + return a.length() - b.length(); + } + }); + } +} diff --git a/libraries/src/test/java/com/baeldung/jdeffered/AppTest.java b/libraries/src/test/java/com/baeldung/jdeffered/AppTest.java deleted file mode 100644 index 97b20cda57..0000000000 --- a/libraries/src/test/java/com/baeldung/jdeffered/AppTest.java +++ /dev/null @@ -1,26 +0,0 @@ -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/jdeffered/JDeferredUnitTest.java b/libraries/src/test/java/com/baeldung/jdeffered/JDeferredUnitTest.java new file mode 100644 index 0000000000..80cd16bd53 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/jdeffered/JDeferredUnitTest.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 JDeferredUnitTest { + + @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/jool/JOOLTest.java b/libraries/src/test/java/com/baeldung/jool/JOOLTest.java deleted file mode 100644 index 2cb393abd3..0000000000 --- a/libraries/src/test/java/com/baeldung/jool/JOOLTest.java +++ /dev/null @@ -1,167 +0,0 @@ -package com.baeldung.jool; - -import org.jooq.lambda.Seq; -import org.jooq.lambda.Unchecked; -import org.jooq.lambda.function.Function1; -import org.jooq.lambda.function.Function2; -import org.jooq.lambda.tuple.Tuple2; -import org.jooq.lambda.tuple.Tuple3; -import org.jooq.lambda.tuple.Tuple4; -import org.junit.Test; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static junit.framework.Assert.assertTrue; -import static junit.framework.TestCase.assertEquals; -import static org.jooq.lambda.tuple.Tuple.tuple; - -public class JOOLTest { - @Test - public void givenSeq_whenCheckContains_shouldReturnTrue() { - List concat = Seq.of(1, 2, 3).concat(Seq.of(4, 5, 6)).toList(); - - assertEquals(concat, Arrays.asList(1, 2, 3, 4, 5, 6)); - - assertTrue(Seq.of(1, 2, 3, 4).contains(2)); - - assertTrue(Seq.of(1, 2, 3, 4).containsAll(2, 3)); - - assertTrue(Seq.of(1, 2, 3, 4).containsAny(2, 5)); - } - - @Test - public void givenStreams_whenJoin_shouldHaveElementsFromTwoStreams() { - // given - Stream left = Stream.of(1, 2, 4); - Stream right = Stream.of(1, 2, 3); - - // when - List rightCollected = right.collect(Collectors.toList()); - List collect = left.filter(rightCollected::contains).collect(Collectors.toList()); - - // then - assertEquals(collect, Arrays.asList(1, 2)); - } - - @Test - public void givenSeq_whenJoin_shouldHaveElementsFromBothSeq() { - assertEquals(Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2))); - - assertEquals(Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null))); - - assertEquals(Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3))); - - assertEquals(Seq.of(1, 2).crossJoin(Seq.of("A", "B")).toList(), Arrays.asList(tuple(1, "A"), tuple(1, "B"), tuple(2, "A"), tuple(2, "B"))); - } - - @Test - public void givenSeq_whenManipulateSeq_seqShouldHaveNewElementsInIt() { - assertEquals(Seq.of(1, 2, 3).cycle().limit(9).toList(), Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3)); - - assertEquals(Seq.of(1, 2, 3).duplicate().map((first, second) -> tuple(first.toList(), second.toList())), tuple(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3))); - - assertEquals(Seq.of(1, 2, 3, 4).intersperse(0).toList(), Arrays.asList(1, 0, 2, 0, 3, 0, 4)); - - assertEquals(Seq.of(1, 2, 3, 4, 5).shuffle().toList().size(), 5); - - assertEquals(Seq.of(1, 2, 3, 4).partition(i -> i > 2).map((first, second) -> tuple(first.toList(), second.toList())), tuple(Arrays.asList(3, 4), Arrays.asList(1, 2)) - - ); - - assertEquals(Seq.of(1, 2, 3, 4).reverse().toList(), Arrays.asList(4, 3, 2, 1)); - } - - @Test - public void givenSeq_whenGroupByAndFold_shouldReturnProperSeq() { - - Map> expectedAfterGroupBy = new HashMap<>(); - expectedAfterGroupBy.put(1, Arrays.asList(1, 3)); - expectedAfterGroupBy.put(0, Arrays.asList(2, 4)); - - assertEquals(Seq.of(1, 2, 3, 4).groupBy(i -> i % 2), expectedAfterGroupBy); - - assertEquals(Seq.of("a", "b", "c").foldLeft("!", (u, t) -> u + t), "!abc"); - - assertEquals(Seq.of("a", "b", "c").foldRight("!", (t, u) -> t + u), "abc!"); - } - - @Test - public void givenSeq_whenUsingSeqWhile_shouldBehaveAsWhileLoop() { - - assertEquals(Seq.of(1, 2, 3, 4, 5).skipWhile(i -> i < 3).toList(), Arrays.asList(3, 4, 5)); - - assertEquals(Seq.of(1, 2, 3, 4, 5).skipUntil(i -> i == 3).toList(), Arrays.asList(3, 4, 5)); - } - - @Test - public void givenSeq_whenZip_shouldHaveZippedSeq() { - - assertEquals(Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")).toList(), Arrays.asList(tuple(1, "a"), tuple(2, "b"), tuple(3, "c"))); - - assertEquals(Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y).toList(), Arrays.asList("1:a", "2:b", "3:c")); - - assertEquals(Seq.of("a", "b", "c").zipWithIndex().toList(), Arrays.asList(tuple("a", 0L), tuple("b", 1L), tuple("c", 2L))); - } - - public Integer methodThatThrowsChecked(String arg) throws Exception { - return arg.length(); - } - - @Test - public void givenOperationThatThrowsCheckedException_whenExecuteAndNeedToWrapCheckedIntoUnchecked_shouldPass() { - // when - List collect = Stream.of("a", "b", "c").map(elem -> { - try { - return methodThatThrowsChecked(elem); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - }).collect(Collectors.toList()); - - // then - assertEquals(collect, Arrays.asList(1, 1, 1)); - } - - @Test - public void givenOperationThatThrowsCheckedException_whenExecuteUsingUncheckedFuction_shouldPass() { - // when - List collect = Stream.of("a", "b", "c").map(Unchecked.function(this::methodThatThrowsChecked)).collect(Collectors.toList()); - - // then - assertEquals(collect, Arrays.asList(1, 1, 1)); - } - - @Test - public void givenFunction_whenAppliedPartially_shouldAddNumberToPartialArgument() { - // given - Function2 addTwoNumbers = (v1, v2) -> v1 + v2; - addTwoNumbers.toBiFunction(); - Function1 addToTwo = addTwoNumbers.applyPartially(2); - - // when - Integer result = addToTwo.apply(5); - - // then - assertEquals(result, (Integer) 7); - } - - @Test - public void givenSeqOfTuples_whenTransformToLowerNumberOfTuples_shouldHaveProperResult() { - // given - Seq> personDetails = Seq.of(tuple("michael", "similar", 49), tuple("jodie", "variable", 43)); - Tuple2 tuple = tuple("winter", "summer"); - - // when - List> result = personDetails.map(t -> t.limit2().concat(tuple)).toList(); - - // then - assertEquals(result, Arrays.asList(tuple("michael", "similar", "winter", "summer"), tuple("jodie", "variable", "winter", "summer"))); - } -} diff --git a/libraries/src/test/java/com/baeldung/jool/JOOLUnitTest.java b/libraries/src/test/java/com/baeldung/jool/JOOLUnitTest.java new file mode 100644 index 0000000000..153014e324 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/jool/JOOLUnitTest.java @@ -0,0 +1,167 @@ +package com.baeldung.jool; + +import org.jooq.lambda.Seq; +import org.jooq.lambda.Unchecked; +import org.jooq.lambda.function.Function1; +import org.jooq.lambda.function.Function2; +import org.jooq.lambda.tuple.Tuple2; +import org.jooq.lambda.tuple.Tuple3; +import org.jooq.lambda.tuple.Tuple4; +import org.junit.Test; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static junit.framework.Assert.assertTrue; +import static junit.framework.TestCase.assertEquals; +import static org.jooq.lambda.tuple.Tuple.tuple; + +public class JOOLUnitTest { + @Test + public void givenSeq_whenCheckContains_shouldReturnTrue() { + List concat = Seq.of(1, 2, 3).concat(Seq.of(4, 5, 6)).toList(); + + assertEquals(concat, Arrays.asList(1, 2, 3, 4, 5, 6)); + + assertTrue(Seq.of(1, 2, 3, 4).contains(2)); + + assertTrue(Seq.of(1, 2, 3, 4).containsAll(2, 3)); + + assertTrue(Seq.of(1, 2, 3, 4).containsAny(2, 5)); + } + + @Test + public void givenStreams_whenJoin_shouldHaveElementsFromTwoStreams() { + // given + Stream left = Stream.of(1, 2, 4); + Stream right = Stream.of(1, 2, 3); + + // when + List rightCollected = right.collect(Collectors.toList()); + List collect = left.filter(rightCollected::contains).collect(Collectors.toList()); + + // then + assertEquals(collect, Arrays.asList(1, 2)); + } + + @Test + public void givenSeq_whenJoin_shouldHaveElementsFromBothSeq() { + assertEquals(Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2))); + + assertEquals(Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null))); + + assertEquals(Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3))); + + assertEquals(Seq.of(1, 2).crossJoin(Seq.of("A", "B")).toList(), Arrays.asList(tuple(1, "A"), tuple(1, "B"), tuple(2, "A"), tuple(2, "B"))); + } + + @Test + public void givenSeq_whenManipulateSeq_seqShouldHaveNewElementsInIt() { + assertEquals(Seq.of(1, 2, 3).cycle().limit(9).toList(), Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3)); + + assertEquals(Seq.of(1, 2, 3).duplicate().map((first, second) -> tuple(first.toList(), second.toList())), tuple(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3))); + + assertEquals(Seq.of(1, 2, 3, 4).intersperse(0).toList(), Arrays.asList(1, 0, 2, 0, 3, 0, 4)); + + assertEquals(Seq.of(1, 2, 3, 4, 5).shuffle().toList().size(), 5); + + assertEquals(Seq.of(1, 2, 3, 4).partition(i -> i > 2).map((first, second) -> tuple(first.toList(), second.toList())), tuple(Arrays.asList(3, 4), Arrays.asList(1, 2)) + + ); + + assertEquals(Seq.of(1, 2, 3, 4).reverse().toList(), Arrays.asList(4, 3, 2, 1)); + } + + @Test + public void givenSeq_whenGroupByAndFold_shouldReturnProperSeq() { + + Map> expectedAfterGroupBy = new HashMap<>(); + expectedAfterGroupBy.put(1, Arrays.asList(1, 3)); + expectedAfterGroupBy.put(0, Arrays.asList(2, 4)); + + assertEquals(Seq.of(1, 2, 3, 4).groupBy(i -> i % 2), expectedAfterGroupBy); + + assertEquals(Seq.of("a", "b", "c").foldLeft("!", (u, t) -> u + t), "!abc"); + + assertEquals(Seq.of("a", "b", "c").foldRight("!", (t, u) -> t + u), "abc!"); + } + + @Test + public void givenSeq_whenUsingSeqWhile_shouldBehaveAsWhileLoop() { + + assertEquals(Seq.of(1, 2, 3, 4, 5).skipWhile(i -> i < 3).toList(), Arrays.asList(3, 4, 5)); + + assertEquals(Seq.of(1, 2, 3, 4, 5).skipUntil(i -> i == 3).toList(), Arrays.asList(3, 4, 5)); + } + + @Test + public void givenSeq_whenZip_shouldHaveZippedSeq() { + + assertEquals(Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")).toList(), Arrays.asList(tuple(1, "a"), tuple(2, "b"), tuple(3, "c"))); + + assertEquals(Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y).toList(), Arrays.asList("1:a", "2:b", "3:c")); + + assertEquals(Seq.of("a", "b", "c").zipWithIndex().toList(), Arrays.asList(tuple("a", 0L), tuple("b", 1L), tuple("c", 2L))); + } + + public Integer methodThatThrowsChecked(String arg) throws Exception { + return arg.length(); + } + + @Test + public void givenOperationThatThrowsCheckedException_whenExecuteAndNeedToWrapCheckedIntoUnchecked_shouldPass() { + // when + List collect = Stream.of("a", "b", "c").map(elem -> { + try { + return methodThatThrowsChecked(elem); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + }).collect(Collectors.toList()); + + // then + assertEquals(collect, Arrays.asList(1, 1, 1)); + } + + @Test + public void givenOperationThatThrowsCheckedException_whenExecuteUsingUncheckedFuction_shouldPass() { + // when + List collect = Stream.of("a", "b", "c").map(Unchecked.function(this::methodThatThrowsChecked)).collect(Collectors.toList()); + + // then + assertEquals(collect, Arrays.asList(1, 1, 1)); + } + + @Test + public void givenFunction_whenAppliedPartially_shouldAddNumberToPartialArgument() { + // given + Function2 addTwoNumbers = (v1, v2) -> v1 + v2; + addTwoNumbers.toBiFunction(); + Function1 addToTwo = addTwoNumbers.applyPartially(2); + + // when + Integer result = addToTwo.apply(5); + + // then + assertEquals(result, (Integer) 7); + } + + @Test + public void givenSeqOfTuples_whenTransformToLowerNumberOfTuples_shouldHaveProperResult() { + // given + Seq> personDetails = Seq.of(tuple("michael", "similar", 49), tuple("jodie", "variable", 43)); + Tuple2 tuple = tuple("winter", "summer"); + + // when + List> result = personDetails.map(t -> t.limit2().concat(tuple)).toList(); + + // then + assertEquals(result, Arrays.asList(tuple("michael", "similar", "winter", "summer"), tuple("jodie", "variable", "winter", "summer"))); + } +} diff --git a/libraries/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java b/libraries/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java deleted file mode 100644 index c8718aef8d..0000000000 --- a/libraries/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.junitparams; - -import junitparams.FileParameters; -import junitparams.JUnitParamsRunner; -import junitparams.Parameters; -import org.junit.Test; -import org.junit.runner.RunWith; - -import static org.junit.Assert.assertEquals; - -@RunWith(JUnitParamsRunner.class) -public class SafeAdditionUtilTest { - - private SafeAdditionUtil serviceUnderTest = new SafeAdditionUtil(); - - @Test - @Parameters({ "1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15" }) - public void whenCalledWithAnnotationProvidedParams_thenSafeAddAndReturn(int a, int b, int expectedValue) { - assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); - } - - @Test - @Parameters(method = "parametersToTestAdd") - public void whenCalledWithNamedMethod_thendSafeAddAndReturn(int a, int b, int expectedValue) { - assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); - } - - private Object[] parametersToTestAdd() { - return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } }; - } - - @Test - @Parameters - public void whenCalledWithnoParam_thenLoadByNameSafeAddAndReturn(int a, int b, int expectedValue) { - assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); - } - - private Object[] parametersForWhenCalledWithnoParam_thenLoadByNameSafeAddAndReturn() { - return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } }; - } - - @Test - @Parameters(source = TestDataProvider.class) - public void whenCalledWithNamedClass_thenSafeAddAndReturn(int a, int b, int expectedValue) { - assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); - } - - @Test - @FileParameters("src/test/resources/JunitParamsTestParameters.csv") - public void whenCalledWithCsvFile_thenSafeAddAndReturn(int a, int b, int expectedValue) { - assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); - } - -} diff --git a/libraries/src/test/java/com/baeldung/junitparams/SafeAdditionUtilUnitTest.java b/libraries/src/test/java/com/baeldung/junitparams/SafeAdditionUtilUnitTest.java new file mode 100644 index 0000000000..f9213d9ab5 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/junitparams/SafeAdditionUtilUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.junitparams; + +import junitparams.FileParameters; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.assertEquals; + +@RunWith(JUnitParamsRunner.class) +public class SafeAdditionUtilUnitTest { + + private SafeAdditionUtil serviceUnderTest = new SafeAdditionUtil(); + + @Test + @Parameters({ "1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15" }) + public void whenCalledWithAnnotationProvidedParams_thenSafeAddAndReturn(int a, int b, int expectedValue) { + assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); + } + + @Test + @Parameters(method = "parametersToTestAdd") + public void whenCalledWithNamedMethod_thendSafeAddAndReturn(int a, int b, int expectedValue) { + assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); + } + + private Object[] parametersToTestAdd() { + return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } }; + } + + @Test + @Parameters + public void whenCalledWithnoParam_thenLoadByNameSafeAddAndReturn(int a, int b, int expectedValue) { + assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); + } + + private Object[] parametersForWhenCalledWithnoParam_thenLoadByNameSafeAddAndReturn() { + return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } }; + } + + @Test + @Parameters(source = TestDataProvider.class) + public void whenCalledWithNamedClass_thenSafeAddAndReturn(int a, int b, int expectedValue) { + assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); + } + + @Test + @FileParameters("src/test/resources/JunitParamsTestParameters.csv") + public void whenCalledWithCsvFile_thenSafeAddAndReturn(int a, int b, int expectedValue) { + assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); + } + +} diff --git a/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncDispatchTest.java b/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncDispatchTest.java deleted file mode 100644 index 0cab612a7b..0000000000 --- a/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncDispatchTest.java +++ /dev/null @@ -1,37 +0,0 @@ -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/MBassadorAsyncDispatchUnitTest.java b/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncDispatchUnitTest.java new file mode 100644 index 0000000000..903da00995 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncDispatchUnitTest.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 MBassadorAsyncDispatchUnitTest { + + 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 deleted file mode 100644 index 99ea1aab71..0000000000 --- a/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncInvocationTest.java +++ /dev/null @@ -1,45 +0,0 @@ -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 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/MBassadorAsyncInvocationUnitTest.java b/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncInvocationUnitTest.java new file mode 100644 index 0000000000..bf20645e2d --- /dev/null +++ b/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncInvocationUnitTest.java @@ -0,0 +1,45 @@ +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 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 MBassadorAsyncInvocationUnitTest { + + 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 deleted file mode 100644 index 04f6272412..0000000000 --- a/libraries/src/test/java/com/baeldung/mbassador/MBassadorBasicTest.java +++ /dev/null @@ -1,69 +0,0 @@ -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/MBassadorBasicUnitTest.java b/libraries/src/test/java/com/baeldung/mbassador/MBassadorBasicUnitTest.java new file mode 100644 index 0000000000..bd05d2888e --- /dev/null +++ b/libraries/src/test/java/com/baeldung/mbassador/MBassadorBasicUnitTest.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 MBassadorBasicUnitTest { + + 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 deleted file mode 100644 index 9d9a58aee9..0000000000 --- a/libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationTest.java +++ /dev/null @@ -1,89 +0,0 @@ -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 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/MBassadorConfigurationUnitTest.java b/libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationUnitTest.java new file mode 100644 index 0000000000..68cfff0014 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationUnitTest.java @@ -0,0 +1,89 @@ +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 java.util.*; + +import static junit.framework.TestCase.assertTrue; +import static org.junit.Assert.*; + +public class MBassadorConfigurationUnitTest 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 deleted file mode 100644 index e90ae15d3d..0000000000 --- a/libraries/src/test/java/com/baeldung/mbassador/MBassadorFilterTest.java +++ /dev/null @@ -1,103 +0,0 @@ -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/MBassadorFilterUnitTest.java b/libraries/src/test/java/com/baeldung/mbassador/MBassadorFilterUnitTest.java new file mode 100644 index 0000000000..0094140fee --- /dev/null +++ b/libraries/src/test/java/com/baeldung/mbassador/MBassadorFilterUnitTest.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 MBassadorFilterUnitTest { + + 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 deleted file mode 100644 index be5c9d4897..0000000000 --- a/libraries/src/test/java/com/baeldung/mbassador/MBassadorHierarchyTest.java +++ /dev/null @@ -1,61 +0,0 @@ -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/mbassador/MBassadorHierarchyUnitTest.java b/libraries/src/test/java/com/baeldung/mbassador/MBassadorHierarchyUnitTest.java new file mode 100644 index 0000000000..6f1ca83f0a --- /dev/null +++ b/libraries/src/test/java/com/baeldung/mbassador/MBassadorHierarchyUnitTest.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 MBassadorHierarchyUnitTest { + + 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 deleted file mode 100644 index b023ffe8d9..0000000000 --- a/libraries/src/test/java/com/baeldung/measurement/WaterTankTests.java +++ /dev/null @@ -1,86 +0,0 @@ -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/measurement/WaterTankUnitTest.java b/libraries/src/test/java/com/baeldung/measurement/WaterTankUnitTest.java new file mode 100644 index 0000000000..e23eea1714 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/measurement/WaterTankUnitTest.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 WaterTankUnitTest { + + @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/opencsv/OpenCsvIntegrationTest.java b/libraries/src/test/java/com/baeldung/opencsv/OpenCsvIntegrationTest.java new file mode 100644 index 0000000000..fca96684ad --- /dev/null +++ b/libraries/src/test/java/com/baeldung/opencsv/OpenCsvIntegrationTest.java @@ -0,0 +1,66 @@ +package com.baeldung.opencsv; + +import com.baeldung.opencsv.helpers.Helpers; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class OpenCsvIntegrationTest { + + private Object testReadCsv(Object result) { + assert (result != null); + assert (result instanceof String); + assert (!((String) result).isEmpty()); + System.out.println(result); + return result; + } + + private Object testWriteCsv(Object result) { + assert (result instanceof String); + assert (!((String) result).isEmpty()); + return result; + } + + @Before + public void setup() { + } + + @Test + public void positionExampleTest() { + testReadCsv(Application.simpleSyncPositionBeanExample()); + } + + @Test + public void namedColumnExampleTest() { + testReadCsv(Application.namedSyncColumnBeanExample()); + } + + @Test + public void writeCsvUsingBeanBuilderTest() { + testWriteCsv(Application.writeSyncCsvFromBeanExample()); + } + + @Test + public void oneByOneExampleTest() { + testReadCsv(Application.oneByOneSyncExample()); + } + + @Test + public void readAllExampleTest() { + testReadCsv(Application.readAllSyncExample()); + } + + @Test + public void csvWriterOneByOneTest() { + testWriteCsv(Application.csvWriterSyncOneByOne()); + } + + @Test + public void csvWriterAllTest() { + testWriteCsv(Application.csvWriterSyncAll()); + } + + @After + public void close() { + } +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/opencsv/OpenCsvTest.java b/libraries/src/test/java/com/baeldung/opencsv/OpenCsvTest.java deleted file mode 100644 index 394b3fba4f..0000000000 --- a/libraries/src/test/java/com/baeldung/opencsv/OpenCsvTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.baeldung.opencsv; - -import com.baeldung.opencsv.helpers.Helpers; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class OpenCsvTest { - - private Object testReadCsv(Object result) { - assert (result != null); - assert (result instanceof String); - assert (!((String) result).isEmpty()); - System.out.println(result); - return result; - } - - private Object testWriteCsv(Object result) { - assert (result instanceof String); - assert (!((String) result).isEmpty()); - return result; - } - - @Before - public void setup() { - } - - @Test - public void positionExampleTest() { - testReadCsv(Application.simpleSyncPositionBeanExample()); - } - - @Test - public void namedColumnExampleTest() { - testReadCsv(Application.namedSyncColumnBeanExample()); - } - - @Test - public void writeCsvUsingBeanBuilderTest() { - testWriteCsv(Application.writeSyncCsvFromBeanExample()); - } - - @Test - public void oneByOneExampleTest() { - testReadCsv(Application.oneByOneSyncExample()); - } - - @Test - public void readAllExampleTest() { - testReadCsv(Application.readAllSyncExample()); - } - - @Test - public void csvWriterOneByOneTest() { - testWriteCsv(Application.csvWriterSyncOneByOne()); - } - - @Test - public void csvWriterAllTest() { - testWriteCsv(Application.csvWriterSyncAll()); - } - - @After - public void close() { - } -} \ 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 deleted file mode 100644 index e9d5b8ede5..0000000000 --- a/libraries/src/test/java/com/baeldung/protonpack/CollectorUtilsTests.java +++ /dev/null @@ -1,55 +0,0 @@ -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/CollectorUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/protonpack/CollectorUtilsUnitTest.java new file mode 100644 index 0000000000..871a8a1935 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/protonpack/CollectorUtilsUnitTest.java @@ -0,0 +1,55 @@ +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 CollectorUtilsUnitTest { + + @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 deleted file mode 100644 index ccd43b7777..0000000000 --- a/libraries/src/test/java/com/baeldung/protonpack/StreamUtilsTests.java +++ /dev/null @@ -1,180 +0,0 @@ -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/protonpack/StreamUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/protonpack/StreamUtilsUnitTest.java new file mode 100644 index 0000000000..889641502e --- /dev/null +++ b/libraries/src/test/java/com/baeldung/protonpack/StreamUtilsUnitTest.java @@ -0,0 +1,180 @@ +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 StreamUtilsUnitTest { + + @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(500L)); + } + +} diff --git a/libraries/src/test/java/com/baeldung/resilience4j/Resilience4jUnitTest.java b/libraries/src/test/java/com/baeldung/resilience4j/Resilience4jUnitTest.java new file mode 100644 index 0000000000..ced95c99cb --- /dev/null +++ b/libraries/src/test/java/com/baeldung/resilience4j/Resilience4jUnitTest.java @@ -0,0 +1,126 @@ +package com.baeldung.resilience4j; + +import io.github.resilience4j.bulkhead.Bulkhead; +import io.github.resilience4j.bulkhead.BulkheadConfig; +import io.github.resilience4j.bulkhead.BulkheadRegistry; +import io.github.resilience4j.circuitbreaker.CircuitBreaker; +import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig; +import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry; +import io.github.resilience4j.retry.Retry; +import io.github.resilience4j.retry.RetryConfig; +import io.github.resilience4j.retry.RetryRegistry; +import io.github.resilience4j.timelimiter.TimeLimiter; +import io.github.resilience4j.timelimiter.TimeLimiterConfig; +import org.junit.Before; +import org.junit.Test; + +import java.time.Duration; +import java.util.concurrent.*; +import java.util.function.Function; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +public class Resilience4jUnitTest { + + interface RemoteService { + + int process(int i); + } + + private RemoteService service; + + @Before + public void setUp() { + service = mock(RemoteService.class); + } + + @Test + public void whenCircuitBreakerIsUsed_thenItWorksAsExpected() { + CircuitBreakerConfig config = CircuitBreakerConfig.custom() + // Percentage of failures to start short-circuit + .failureRateThreshold(20) + // Min number of call attempts + .ringBufferSizeInClosedState(5) + .build(); + CircuitBreakerRegistry registry = CircuitBreakerRegistry.of(config); + CircuitBreaker circuitBreaker = registry.circuitBreaker("my"); + Function decorated = CircuitBreaker.decorateFunction(circuitBreaker, service::process); + + when(service.process(anyInt())).thenThrow(new RuntimeException()); + + for (int i = 0; i < 10; i++) { + try { + decorated.apply(i); + } catch (Exception ignore) { + } + } + + verify(service, times(5)).process(any(Integer.class)); + } + + @Test + public void whenBulkheadIsUsed_thenItWorksAsExpected() throws InterruptedException { + BulkheadConfig config = BulkheadConfig.custom().maxConcurrentCalls(1).build(); + BulkheadRegistry registry = BulkheadRegistry.of(config); + Bulkhead bulkhead = registry.bulkhead("my"); + Function decorated = Bulkhead.decorateFunction(bulkhead, service::process); + + Future taskInProgress = callAndBlock(decorated); + try { + assertThat(bulkhead.isCallPermitted()).isFalse(); + } finally { + taskInProgress.cancel(true); + } + } + + private Future callAndBlock(Function decoratedService) throws InterruptedException { + CountDownLatch latch = new CountDownLatch(1); + when(service.process(anyInt())).thenAnswer(invocation -> { + latch.countDown(); + Thread.currentThread().join(); + return null; + }); + + ForkJoinTask result = ForkJoinPool.commonPool().submit(() -> { + decoratedService.apply(1); + }); + latch.await(); + return result; + } + + @Test + public void whenRetryIsUsed_thenItWorksAsExpected() { + RetryConfig config = RetryConfig.custom().maxAttempts(2).build(); + RetryRegistry registry = RetryRegistry.of(config); + Retry retry = registry.retry("my"); + Function decorated = Retry.decorateFunction(retry, (Integer s) -> { + service.process(s); + return null; + }); + + when(service.process(anyInt())).thenThrow(new RuntimeException()); + try { + decorated.apply(1); + fail("Expected an exception to be thrown if all retries failed"); + } catch (Exception e) { + verify(service, times(2)).process(any(Integer.class)); + } + } + + @SuppressWarnings("unchecked") + @Test + public void whenTimeLimiterIsUsed_thenItWorksAsExpected() throws Exception { + long ttl = 1; + TimeLimiterConfig config = TimeLimiterConfig.custom().timeoutDuration(Duration.ofMillis(ttl)).build(); + TimeLimiter timeLimiter = TimeLimiter.of(config); + + Future futureMock = mock(Future.class); + Callable restrictedCall = TimeLimiter.decorateFutureSupplier(timeLimiter, () -> futureMock); + restrictedCall.call(); + + verify(futureMock).get(ttl, TimeUnit.MILLISECONDS); + } +} diff --git a/libraries/src/test/java/com/baeldung/snakeyaml/JavaToYAMLSerializationUnitTest.java b/libraries/src/test/java/com/baeldung/snakeyaml/JavaToYAMLSerializationUnitTest.java new file mode 100644 index 0000000000..f6836f6d56 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/snakeyaml/JavaToYAMLSerializationUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.snakeyaml; + +import static org.junit.Assert.assertEquals; + +import java.io.StringWriter; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.junit.Test; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.nodes.Tag; + +import com.baeldung.snakeyaml.Customer; + +public class JavaToYAMLSerializationUnitTest { + + @Test + public void whenDumpMap_thenGenerateCorrectYAML() { + Map data = new LinkedHashMap(); + data.put("name", "Silenthand Olleander"); + data.put("race", "Human"); + data.put("traits", new String[] { "ONE_HAND", "ONE_EYE" }); + Yaml yaml = new Yaml(); + StringWriter writer = new StringWriter(); + yaml.dump(data, writer); + String expectedYaml = "name: Silenthand Olleander\nrace: Human\ntraits: [ONE_HAND, ONE_EYE]\n"; + assertEquals(expectedYaml, writer.toString()); + } + + @Test + public void whenDumpACustomType_thenGenerateCorrectYAML() { + Customer customer = new Customer(); + customer.setAge(45); + customer.setFirstName("Greg"); + customer.setLastName("McDowell"); + Yaml yaml = new Yaml(); + StringWriter writer = new StringWriter(); + yaml.dump(customer, writer); + String expectedYaml = "!!com.baeldung.snakeyaml.Customer {age: 45, contactDetails: null, firstName: Greg,\n homeAddress: null, lastName: McDowell}\n"; + assertEquals(expectedYaml, writer.toString()); + } + + @Test + public void whenDumpAsCustomType_thenGenerateCorrectYAML() { + Customer customer = new Customer(); + customer.setAge(45); + customer.setFirstName("Greg"); + customer.setLastName("McDowell"); + Yaml yaml = new Yaml(); + String expectedYaml = "{age: 45, contactDetails: null, firstName: Greg, homeAddress: null, lastName: McDowell}\n"; + assertEquals(expectedYaml, yaml.dumpAs(customer, Tag.MAP, null)); + } + +} diff --git a/libraries/src/test/java/com/baeldung/snakeyaml/YAMLToJavaDeserialisationUnitTest.java b/libraries/src/test/java/com/baeldung/snakeyaml/YAMLToJavaDeserialisationUnitTest.java new file mode 100644 index 0000000000..56cd3c2b2e --- /dev/null +++ b/libraries/src/test/java/com/baeldung/snakeyaml/YAMLToJavaDeserialisationUnitTest.java @@ -0,0 +1,131 @@ +package com.baeldung.snakeyaml; + +import org.junit.Test; +import org.yaml.snakeyaml.TypeDescription; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +import java.io.InputStream; +import java.util.Date; +import java.util.Map; + +import static org.junit.Assert.*; + +public class YAMLToJavaDeserialisationUnitTest { + + @Test + public void whenLoadYAMLDocument_thenLoadCorrectMap() { + Yaml yaml = new Yaml(); + InputStream inputStream = this.getClass() + .getClassLoader() + .getResourceAsStream("yaml/customer.yaml"); + Map obj = yaml.load(inputStream); + assertEquals("John", obj.get("firstName")); + assertEquals("Doe", obj.get("lastName")); + assertEquals(20, obj.get("age")); + } + + @Test + public void whenLoadYAMLDocumentWithTopLevelClass_thenLoadCorrectJavaObject() { + Yaml yaml = new Yaml(new Constructor(Customer.class)); + InputStream inputStream = this.getClass() + .getClassLoader() + .getResourceAsStream("yaml/customer.yaml"); + Customer customer = yaml.load(inputStream); + assertEquals("John", customer.getFirstName()); + assertEquals("Doe", customer.getLastName()); + assertEquals(20, customer.getAge()); + } + + @Test + public void whenLoadYAMLDocumentWithAssumedClass_thenLoadCorrectJavaObject() { + Yaml yaml = new Yaml(); + InputStream inputStream = this.getClass() + .getClassLoader() + .getResourceAsStream("yaml/customer_with_type.yaml"); + Customer customer = yaml.load(inputStream); + assertEquals("John", customer.getFirstName()); + assertEquals("Doe", customer.getLastName()); + assertEquals(20, customer.getAge()); + } + + @Test + public void whenLoadYAML_thenLoadCorrectImplicitTypes() { + Yaml yaml = new Yaml(); + Map document = yaml.load("3.0: 2018-07-22"); + assertNotNull(document); + assertEquals(1, document.size()); + assertTrue(document.containsKey(3.0d)); + assertTrue(document.get(3.0d) instanceof Date); + } + + @Test + public void whenLoadYAMLDocumentWithTopLevelClass_thenLoadCorrectJavaObjectWithNestedObjects() { + Yaml yaml = new Yaml(new Constructor(Customer.class)); + InputStream inputStream = this.getClass() + .getClassLoader() + .getResourceAsStream("yaml/customer_with_contact_details_and_address.yaml"); + Customer customer = yaml.load(inputStream); + assertNotNull(customer); + assertEquals("John", customer.getFirstName()); + assertEquals("Doe", customer.getLastName()); + assertEquals(31, customer.getAge()); + assertNotNull(customer.getContactDetails()); + assertEquals(2, customer.getContactDetails().size()); + assertEquals("mobile", customer.getContactDetails() + .get(0) + .getType()); + assertEquals(123456789,customer.getContactDetails() + .get(0) + .getNumber()); + assertEquals("landline", customer.getContactDetails() + .get(1) + .getType()); + assertEquals(456786868, customer.getContactDetails() + .get(1) + .getNumber()); + assertNotNull(customer.getHomeAddress()); + assertEquals("Xyz, DEF Street", customer.getHomeAddress() + .getLine()); + } + + @Test + public void whenLoadYAMLDocumentWithTypeDescription_thenLoadCorrectJavaObjectWithCorrectGenericType() { + Constructor constructor = new Constructor(Customer.class); + TypeDescription customTypeDescription = new TypeDescription(Customer.class); + customTypeDescription.addPropertyParameters("contactDetails", Contact.class); + constructor.addTypeDescription(customTypeDescription); + Yaml yaml = new Yaml(constructor); + InputStream inputStream = this.getClass() + .getClassLoader() + .getResourceAsStream("yaml/customer_with_contact_details.yaml"); + Customer customer = yaml.load(inputStream); + assertNotNull(customer); + assertEquals("John", customer.getFirstName()); + assertEquals("Doe", customer.getLastName()); + assertEquals(31, customer.getAge()); + assertNotNull(customer.getContactDetails()); + assertEquals(2, customer.getContactDetails().size()); + assertEquals("mobile", customer.getContactDetails() + .get(0) + .getType()); + assertEquals("landline", customer.getContactDetails() + .get(1) + .getType()); + } + + @Test + public void whenLoadMultipleYAMLDocuments_thenLoadCorrectJavaObjects() { + Yaml yaml = new Yaml(new Constructor(Customer.class)); + InputStream inputStream = this.getClass() + .getClassLoader() + .getResourceAsStream("yaml/customers.yaml"); + int count = 0; + for (Object object : yaml.loadAll(inputStream)) { + count++; + assertTrue(object instanceof Customer); + } + assertEquals(2, count); + } + +} diff --git a/libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsTest.java b/libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsTest.java deleted file mode 100644 index 4cda0b5940..0000000000 --- a/libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.stream; - -import org.jooq.lambda.Seq; -import org.junit.Assert; -import org.junit.Test; - -import java.util.Arrays; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static junit.framework.TestCase.assertEquals; - -public class JoolMergeStreamsTest { - @Test - public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() { - Stream seq1 = Stream.of(1, 3, 5); - Stream seq2 = Stream.of(2, 4, 6); - - Stream resultingSeq = Seq.ofType(seq1, Integer.class).append(seq2); - - assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingSeq.collect(Collectors.toList())); - } - - @Test - public void givenThreeStreams_whenAppendingAndPrependingStreams_thenResultingStreamContainsElementsFromAllStreams() { - Stream seq = Stream.of("foo", "bar"); - Stream openingBracketSeq = Stream.of("["); - Stream closingBracketSeq = Stream.of("]"); - - Stream resultingStream = Seq.ofType(seq, String.class).append(closingBracketSeq).prepend(openingBracketSeq); - - Assert.assertEquals(Arrays.asList("[", "foo", "bar", "]"), resultingStream.collect(Collectors.toList())); - } -} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsUnitTest.java b/libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsUnitTest.java new file mode 100644 index 0000000000..31f3a04362 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.stream; + +import org.jooq.lambda.Seq; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static junit.framework.TestCase.assertEquals; + +public class JoolMergeStreamsUnitTest { + @Test + public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() { + Stream seq1 = Stream.of(1, 3, 5); + Stream seq2 = Stream.of(2, 4, 6); + + Stream resultingSeq = Seq.ofType(seq1, Integer.class).append(seq2); + + assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingSeq.collect(Collectors.toList())); + } + + @Test + public void givenThreeStreams_whenAppendingAndPrependingStreams_thenResultingStreamContainsElementsFromAllStreams() { + Stream seq = Stream.of("foo", "bar"); + Stream openingBracketSeq = Stream.of("["); + Stream closingBracketSeq = Stream.of("]"); + + Stream resultingStream = Seq.ofType(seq, String.class).append(closingBracketSeq).prepend(openingBracketSeq); + + Assert.assertEquals(Arrays.asList("[", "foo", "bar", "]"), resultingStream.collect(Collectors.toList())); + } +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/stream/MergeStreamsTest.java b/libraries/src/test/java/com/baeldung/stream/MergeStreamsTest.java deleted file mode 100644 index b8748abe03..0000000000 --- a/libraries/src/test/java/com/baeldung/stream/MergeStreamsTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.stream; - -import org.junit.Test; - -import java.util.Arrays; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static org.junit.Assert.assertEquals; - -public class MergeStreamsTest { - - @Test - public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() { - Stream stream1 = Stream.of(1, 3, 5); - Stream stream2 = Stream.of(2, 4, 6); - - Stream resultingStream = Stream.concat(stream1, stream2); - - assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingStream.collect(Collectors.toList())); - } - - @Test - public void givenThreeStreams_whenMergingStreams_thenResultingStreamContainsElementsFromAllStreams() { - Stream stream1 = Stream.of(1, 3, 5); - Stream stream2 = Stream.of(2, 4, 6); - Stream stream3 = Stream.of(18, 15, 36); - - Stream resultingStream = Stream.concat(Stream.concat(stream1, stream2), stream3); - - assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36), resultingStream.collect(Collectors.toList())); - } - - @Test - public void givenFourStreams_whenMergingStreams_thenResultingStreamContainsElementsFromAllStreams() { - Stream stream1 = Stream.of(1, 3, 5); - Stream stream2 = Stream.of(2, 4, 6); - Stream stream3 = Stream.of(18, 15, 36); - Stream stream4 = Stream.of(99); - - Stream resultingStream = Stream.of(stream1, stream2, stream3, stream4).flatMap(Function.identity()); - - assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), resultingStream.collect(Collectors.toList())); - - } -} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/stream/MergeStreamsUnitTest.java b/libraries/src/test/java/com/baeldung/stream/MergeStreamsUnitTest.java new file mode 100644 index 0000000000..38ddb47d87 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/stream/MergeStreamsUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.stream; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; + +public class MergeStreamsUnitTest { + + @Test + public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() { + Stream stream1 = Stream.of(1, 3, 5); + Stream stream2 = Stream.of(2, 4, 6); + + Stream resultingStream = Stream.concat(stream1, stream2); + + assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingStream.collect(Collectors.toList())); + } + + @Test + public void givenThreeStreams_whenMergingStreams_thenResultingStreamContainsElementsFromAllStreams() { + Stream stream1 = Stream.of(1, 3, 5); + Stream stream2 = Stream.of(2, 4, 6); + Stream stream3 = Stream.of(18, 15, 36); + + Stream resultingStream = Stream.concat(Stream.concat(stream1, stream2), stream3); + + assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36), resultingStream.collect(Collectors.toList())); + } + + @Test + public void givenFourStreams_whenMergingStreams_thenResultingStreamContainsElementsFromAllStreams() { + Stream stream1 = Stream.of(1, 3, 5); + Stream stream2 = Stream.of(2, 4, 6); + Stream stream3 = Stream.of(18, 15, 36); + Stream stream4 = Stream.of(99); + + Stream resultingStream = Stream.of(stream1, stream2, stream3, stream4).flatMap(Function.identity()); + + assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), resultingStream.collect(Collectors.toList())); + + } +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsTest.java b/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsTest.java deleted file mode 100644 index e5392dff2a..0000000000 --- a/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.stream; - -import one.util.streamex.StreamEx; -import org.junit.Test; - -import java.util.Arrays; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static org.junit.Assert.assertEquals; - -public class StreamExMergeStreamsTest { - - @Test - public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() { - Stream stream1 = Stream.of(1, 3, 5); - Stream stream2 = Stream.of(2, 4, 6); - - Stream resultingStream = StreamEx.of(stream1).append(stream2); - - assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingStream.collect(Collectors.toList())); - } - - @Test - public void givenFourStreams_whenMergingStreams_thenResultingStreamContainsElementsFromAllStreams() { - Stream stream1 = Stream.of(1, 3, 5); - Stream stream2 = Stream.of(2, 4, 6); - Stream stream3 = Stream.of(18, 15, 36); - Stream stream4 = Stream.of(99); - - Stream resultingStream = StreamEx.of(stream1).append(stream2).append(stream3).append(stream4); - - assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), resultingStream.collect(Collectors.toList())); - - } - - @Test - public void givenThreeStreams_whenAppendingAndPrependingStreams_thenResultingStreamContainsElementsFromAllStreams() { - Stream stream1 = Stream.of("foo", "bar"); - Stream openingBracketStream = Stream.of("["); - Stream closingBracketStream = Stream.of("]"); - - Stream resultingStream = StreamEx.of(stream1).append(closingBracketStream).prepend(openingBracketStream); - - assertEquals(Arrays.asList("[", "foo", "bar", "]"), resultingStream.collect(Collectors.toList())); - } -} diff --git a/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsUnitTest.java b/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsUnitTest.java new file mode 100644 index 0000000000..220348bf36 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.stream; + +import one.util.streamex.StreamEx; +import org.junit.Test; + +import java.util.Arrays; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; + +public class StreamExMergeStreamsUnitTest { + + @Test + public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() { + Stream stream1 = Stream.of(1, 3, 5); + Stream stream2 = Stream.of(2, 4, 6); + + Stream resultingStream = StreamEx.of(stream1).append(stream2); + + assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingStream.collect(Collectors.toList())); + } + + @Test + public void givenFourStreams_whenMergingStreams_thenResultingStreamContainsElementsFromAllStreams() { + Stream stream1 = Stream.of(1, 3, 5); + Stream stream2 = Stream.of(2, 4, 6); + Stream stream3 = Stream.of(18, 15, 36); + Stream stream4 = Stream.of(99); + + Stream resultingStream = StreamEx.of(stream1).append(stream2).append(stream3).append(stream4); + + assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), resultingStream.collect(Collectors.toList())); + + } + + @Test + public void givenThreeStreams_whenAppendingAndPrependingStreams_thenResultingStreamContainsElementsFromAllStreams() { + Stream stream1 = Stream.of("foo", "bar"); + Stream openingBracketStream = Stream.of("["); + Stream closingBracketStream = Stream.of("]"); + + Stream resultingStream = StreamEx.of(stream1).append(closingBracketStream).prepend(openingBracketStream); + + assertEquals(Arrays.asList("[", "foo", "bar", "]"), resultingStream.collect(Collectors.toList())); + } +} diff --git a/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java b/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java deleted file mode 100644 index 3ed797ccaa..0000000000 --- a/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.baeldung.streamutils; - -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.charset.StandardCharsets; - -import org.junit.Assert; -import org.junit.Test; -import org.springframework.util.StreamUtils; - -import static com.baeldung.streamutils.CopyStream.getStringFromInputStream; - -public class CopyStreamTest { - - @Test - public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException { - String inputFileName = "src/test/resources/input.txt"; - String outputFileName = "src/test/resources/output.txt"; - File outputFile = new File(outputFileName); - InputStream in = new FileInputStream(inputFileName); - OutputStream out = new FileOutputStream(outputFileName); - - StreamUtils.copy(in, out); - - assertTrue(outputFile.exists()); - String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); - String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); - Assert.assertEquals(inputFileContent, outputFileContent); - } - - @Test - public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException { - String inputFileName = "src/test/resources/input.txt"; - String outputFileName = "src/test/resources/output.txt"; - File outputFile = new File(outputFileName); - InputStream in = new FileInputStream(inputFileName); - OutputStream out = new FileOutputStream(outputFileName); - - StreamUtils.copyRange(in, out, 1, 10); - - assertTrue(outputFile.exists()); - String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); - String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); - Assert.assertEquals(inputFileContent.substring(1, 11), outputFileContent); - } - - @Test - public void whenCopyStringToOutputStream_thenCorrect() throws IOException { - String string = "Should be copied to OutputStream."; - String outputFileName = "src/test/resources/output.txt"; - File outputFile = new File(outputFileName); - OutputStream out = new FileOutputStream("src/test/resources/output.txt"); - - StreamUtils.copy(string, StandardCharsets.UTF_8, out); - - assertTrue(outputFile.exists()); - String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); - Assert.assertEquals(outputFileContent, string); - } - - @Test - public void whenCopyInputStreamToString_thenCorrect() throws IOException { - String inputFileName = "src/test/resources/input.txt"; - InputStream is = new FileInputStream(inputFileName); - String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8); - - String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); - Assert.assertEquals(inputFileContent, content); - } - - @Test - public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException { - String outputFileName = "src/test/resources/output.txt"; - String string = "Should be copied to OutputStream."; - byte[] byteArray = string.getBytes(); - OutputStream out = new FileOutputStream("src/test/resources/output.txt"); - - StreamUtils.copy(byteArray, out); - String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); - Assert.assertEquals(outputFileContent, string); - } - - @Test - public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException { - String inputFileName = "src/test/resources/input.txt"; - InputStream in = new FileInputStream(inputFileName); - byte[] out = StreamUtils.copyToByteArray(in); - - String content = new String(out); - String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); - Assert.assertEquals(inputFileContent, content); - } - -} diff --git a/libraries/src/test/java/com/baeldung/streamutils/CopyStreamUnitTest.java b/libraries/src/test/java/com/baeldung/streamutils/CopyStreamUnitTest.java new file mode 100644 index 0000000000..5af914afea --- /dev/null +++ b/libraries/src/test/java/com/baeldung/streamutils/CopyStreamUnitTest.java @@ -0,0 +1,100 @@ +package com.baeldung.streamutils; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.util.StreamUtils; + +import static com.baeldung.streamutils.CopyStream.getStringFromInputStream; + +public class CopyStreamUnitTest { + + @Test + public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + InputStream in = new FileInputStream(inputFileName); + OutputStream out = new FileOutputStream(outputFileName); + + StreamUtils.copy(in, out); + + assertTrue(outputFile.exists()); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(inputFileContent, outputFileContent); + } + + @Test + public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + InputStream in = new FileInputStream(inputFileName); + OutputStream out = new FileOutputStream(outputFileName); + + StreamUtils.copyRange(in, out, 1, 10); + + assertTrue(outputFile.exists()); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(inputFileContent.substring(1, 11), outputFileContent); + } + + @Test + public void whenCopyStringToOutputStream_thenCorrect() throws IOException { + String string = "Should be copied to OutputStream."; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + OutputStream out = new FileOutputStream("src/test/resources/output.txt"); + + StreamUtils.copy(string, StandardCharsets.UTF_8, out); + + assertTrue(outputFile.exists()); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(outputFileContent, string); + } + + @Test + public void whenCopyInputStreamToString_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + InputStream is = new FileInputStream(inputFileName); + String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8); + + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + Assert.assertEquals(inputFileContent, content); + } + + @Test + public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException { + String outputFileName = "src/test/resources/output.txt"; + String string = "Should be copied to OutputStream."; + byte[] byteArray = string.getBytes(); + OutputStream out = new FileOutputStream("src/test/resources/output.txt"); + + StreamUtils.copy(byteArray, out); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(outputFileContent, string); + } + + @Test + public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + InputStream in = new FileInputStream(inputFileName); + byte[] out = StreamUtils.copyToByteArray(in); + + String content = new String(out); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + Assert.assertEquals(inputFileContent, content); + } + +} diff --git a/libraries/src/test/java/com/baeldung/text/DiffTest.java b/libraries/src/test/java/com/baeldung/text/DiffTest.java deleted file mode 100644 index 932fc96f21..0000000000 --- a/libraries/src/test/java/com/baeldung/text/DiffTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.text; - -import org.apache.commons.text.diff.EditScript; -import org.apache.commons.text.diff.StringsComparator; -import org.junit.Assert; -import org.junit.Test; - -public class DiffTest { - - @Test - public void whenEditScript_thenCorrect() { - StringsComparator cmp = new StringsComparator("ABCFGH", "BCDEFG"); - EditScript script = cmp.getScript(); - int mod = script.getModifications(); - - Assert.assertEquals(4, mod); - } -} diff --git a/libraries/src/test/java/com/baeldung/text/DiffUnitTest.java b/libraries/src/test/java/com/baeldung/text/DiffUnitTest.java new file mode 100644 index 0000000000..f8a5d6fc0c --- /dev/null +++ b/libraries/src/test/java/com/baeldung/text/DiffUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.text; + +import org.apache.commons.text.diff.EditScript; +import org.apache.commons.text.diff.StringsComparator; +import org.junit.Assert; +import org.junit.Test; + +public class DiffUnitTest { + + @Test + public void whenEditScript_thenCorrect() { + StringsComparator cmp = new StringsComparator("ABCFGH", "BCDEFG"); + EditScript script = cmp.getScript(); + int mod = script.getModifications(); + + Assert.assertEquals(4, mod); + } +} diff --git a/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceTest.java b/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceTest.java deleted file mode 100644 index e0a00afd84..0000000000 --- a/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.text; - -import org.apache.commons.text.similarity.LongestCommonSubsequence; -import org.apache.commons.text.similarity.LongestCommonSubsequenceDistance; -import org.junit.Assert; -import org.junit.Test; - -public class LongestCommonSubsequenceTest { - - @Test - public void whenCompare_thenCorrect() { - LongestCommonSubsequence lcs = new LongestCommonSubsequence(); - int countLcs = lcs.apply("New York", "New Hampshire"); - - Assert.assertEquals(5, countLcs); - } - - @Test - public void whenCalculateDistance_thenCorrect() { - LongestCommonSubsequenceDistance lcsd = new LongestCommonSubsequenceDistance(); - int countLcsd = lcsd.apply("New York", "New Hampshire"); - - Assert.assertEquals(11, countLcsd); - } -} diff --git a/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceUnitTest.java b/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceUnitTest.java new file mode 100644 index 0000000000..47cfda1863 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.text; + +import org.apache.commons.text.similarity.LongestCommonSubsequence; +import org.apache.commons.text.similarity.LongestCommonSubsequenceDistance; +import org.junit.Assert; +import org.junit.Test; + +public class LongestCommonSubsequenceUnitTest { + + @Test + public void whenCompare_thenCorrect() { + LongestCommonSubsequence lcs = new LongestCommonSubsequence(); + int countLcs = lcs.apply("New York", "New Hampshire"); + + Assert.assertEquals(5, countLcs); + } + + @Test + public void whenCalculateDistance_thenCorrect() { + LongestCommonSubsequenceDistance lcsd = new LongestCommonSubsequenceDistance(); + int countLcsd = lcsd.apply("New York", "New Hampshire"); + + Assert.assertEquals(11, countLcsd); + } +} diff --git a/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java b/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java deleted file mode 100644 index 4ebf00e1ed..0000000000 --- a/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.text; - -import org.apache.commons.text.StrBuilder; -import org.junit.Assert; -import org.junit.Test; - -public class StrBuilderTest { - - @Test - public void whenReplaced_thenCorrect() { - StrBuilder strBuilder = new StrBuilder("example StrBuilder!"); - strBuilder.replaceAll("example", "new"); - - Assert.assertEquals(new StrBuilder("new StrBuilder!"), strBuilder); - } - - @Test - public void whenCleared_thenEmpty() { - StrBuilder strBuilder = new StrBuilder("example StrBuilder!"); - strBuilder.clear(); - - Assert.assertEquals(new StrBuilder(""), strBuilder); - } -} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/text/StrBuilderUnitTest.java b/libraries/src/test/java/com/baeldung/text/StrBuilderUnitTest.java new file mode 100644 index 0000000000..09bb7f9a3f --- /dev/null +++ b/libraries/src/test/java/com/baeldung/text/StrBuilderUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.text; + +import org.apache.commons.text.StrBuilder; +import org.junit.Assert; +import org.junit.Test; + +public class StrBuilderUnitTest { + + @Test + public void whenReplaced_thenCorrect() { + StrBuilder strBuilder = new StrBuilder("example StrBuilder!"); + strBuilder.replaceAll("example", "new"); + + Assert.assertEquals(new StrBuilder("new StrBuilder!"), strBuilder); + } + + @Test + public void whenCleared_thenEmpty() { + StrBuilder strBuilder = new StrBuilder("example StrBuilder!"); + strBuilder.clear(); + + Assert.assertEquals(new StrBuilder(""), strBuilder); + } +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/text/StrSubstitutorTest.java b/libraries/src/test/java/com/baeldung/text/StrSubstitutorTest.java deleted file mode 100644 index 24e6ff59c8..0000000000 --- a/libraries/src/test/java/com/baeldung/text/StrSubstitutorTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.text; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.text.StrSubstitutor; -import org.junit.Assert; -import org.junit.Test; - -public class StrSubstitutorTest { - - @Test - public void whenSubstituted_thenCorrect() { - Map substitutes = new HashMap<>(); - substitutes.put("name", "John"); - substitutes.put("college", "University of Stanford"); - String templateString = "My name is ${name} and I am a student at the ${college}."; - StrSubstitutor sub = new StrSubstitutor(substitutes); - String result = sub.replace(templateString); - - Assert.assertEquals("My name is John and I am a student at the University of Stanford.", result); - } -} diff --git a/libraries/src/test/java/com/baeldung/text/StrSubstitutorUnitTest.java b/libraries/src/test/java/com/baeldung/text/StrSubstitutorUnitTest.java new file mode 100644 index 0000000000..85f5084485 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/text/StrSubstitutorUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.text; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.text.StrSubstitutor; +import org.junit.Assert; +import org.junit.Test; + +public class StrSubstitutorUnitTest { + + @Test + public void whenSubstituted_thenCorrect() { + Map substitutes = new HashMap<>(); + substitutes.put("name", "John"); + substitutes.put("college", "University of Stanford"); + String templateString = "My name is ${name} and I am a student at the ${college}."; + StrSubstitutor sub = new StrSubstitutor(substitutes); + String result = sub.replace(templateString); + + Assert.assertEquals("My name is John and I am a student at the University of Stanford.", result); + } +} diff --git a/libraries/src/test/java/com/baeldung/text/UnicodeEscaperTest.java b/libraries/src/test/java/com/baeldung/text/UnicodeEscaperTest.java deleted file mode 100644 index 5a52bfd0db..0000000000 --- a/libraries/src/test/java/com/baeldung/text/UnicodeEscaperTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.text; - -import org.apache.commons.text.translate.UnicodeEscaper; -import org.junit.Assert; -import org.junit.Test; - -public class UnicodeEscaperTest { - - @Test - public void whenTranslate_thenCorrect() { - UnicodeEscaper ue = UnicodeEscaper.above(0); - String result = ue.translate("ABCD"); - - Assert.assertEquals("\\u0041\\u0042\\u0043\\u0044", result); - } -} diff --git a/libraries/src/test/java/com/baeldung/text/UnicodeEscaperUnitTest.java b/libraries/src/test/java/com/baeldung/text/UnicodeEscaperUnitTest.java new file mode 100644 index 0000000000..5614566949 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/text/UnicodeEscaperUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.text; + +import org.apache.commons.text.translate.UnicodeEscaper; +import org.junit.Assert; +import org.junit.Test; + +public class UnicodeEscaperUnitTest { + + @Test + public void whenTranslate_thenCorrect() { + UnicodeEscaper ue = UnicodeEscaper.above(0); + String result = ue.translate("ABCD"); + + Assert.assertEquals("\\u0041\\u0042\\u0043\\u0044", result); + } +} diff --git a/libraries/src/test/java/com/baeldung/unirest/HttpClientLiveTest.java b/libraries/src/test/java/com/baeldung/unirest/HttpClientLiveTest.java new file mode 100644 index 0000000000..7d3bce5cfe --- /dev/null +++ b/libraries/src/test/java/com/baeldung/unirest/HttpClientLiveTest.java @@ -0,0 +1,174 @@ +package com.baeldung.unirest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +import org.apache.http.entity.ContentType; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import com.baeldung.unirest.Article; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.mashape.unirest.http.HttpResponse; +import com.mashape.unirest.http.JsonNode; +import com.mashape.unirest.http.ObjectMapper; +import com.mashape.unirest.http.Unirest; +import com.mashape.unirest.http.async.Callback; +import com.mashape.unirest.http.exceptions.UnirestException; + +public class HttpClientLiveTest { + + @BeforeClass + public static void setup() { + // Unirest.setProxy(new HttpHost("localhost", 8080)); + Unirest.setTimeouts(20000, 15000); + Unirest.setDefaultHeader("X-app-name", "baeldung-unirest"); + Unirest.setDefaultHeader("X-request-id", "100004f00ab5"); + Unirest.setConcurrency(20, 5); + Unirest.setObjectMapper(new ObjectMapper() { + com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper(); + + public String writeValue(Object value) { + try { + return mapper.writeValueAsString(value); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + + } + + public T readValue(String value, Class valueType) { + + try { + return mapper.readValue(value, valueType); + } catch (Exception e) { + throw new RuntimeException(e); + } + + } + }); + } + + @AfterClass + public static void tearDown() throws IOException { + Unirest.clearDefaultHeaders(); + Unirest.shutdown(); + } + + @Test + public void shouldReturnStatusOkay() throws UnirestException { + HttpResponse jsonResponse = Unirest.get("http://www.mocky.io/v2/5a9ce37b3100004f00ab5154") + .header("accept", "application/json") + .queryString("apiKey", "123") + .asJson(); + assertNotNull(jsonResponse.getBody()); + assertEquals(200, jsonResponse.getStatus()); + } + + @Test + public void shouldReturnStatusAccepted() throws UnirestException { + + Map headers = new HashMap(); + headers.put("accept", "application/json"); + headers.put("Authorization", "Bearer 5a9ce37b3100004f00ab5154"); + + Map fields = new HashMap(); + fields.put("name", "Sam Baeldung"); + fields.put("id", "PSP123"); + + HttpResponse jsonResponse = Unirest.put("http://www.mocky.io/v2/5a9ce7853100002a00ab515e") + .headers(headers) + .fields(fields) + .asJson(); + assertNotNull(jsonResponse.getBody()); + assertEquals(202, jsonResponse.getStatus()); + } + + @Test + public void givenRequestBodyWhenCreatedThenCorrect() throws UnirestException { + + HttpResponse jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d") + .body("{\"name\":\"Sam Baeldung\", \"city\":\"viena\"}") + .asJson(); + assertEquals(201, jsonResponse.getStatus()); + } + + @Test + @Ignore + public void whenAysncRequestShouldReturnOk() throws InterruptedException, ExecutionException { + Future> future = Unirest.post("http://www.mocky.io/v2/5a9ce37b3100004f00ab5154?mocky-delay=10000ms") + .header("accept", "application/json") + .asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + // Do something if the request failed + } + + public void completed(HttpResponse response) { + // Do something if the request is successful + } + + public void cancelled() { + // Do something if the request is cancelled + } + + }); + assertEquals(200, future.get() + .getStatus()); + + } + + @Test + public void givenArticleWhenCreatedThenCorrect() throws UnirestException { + Article article = new Article("ID1213", "Guide to Rest", "baeldung"); + HttpResponse jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d") + .body(article) + .asJson(); + assertEquals(201, jsonResponse.getStatus()); + } + + // @Test + public void givenFileWhenUploadedThenCorrect() throws UnirestException { + + HttpResponse jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d") + .field("file", new File("/path/to/file")) + .asJson(); + assertEquals(201, jsonResponse.getStatus()); + } + + // @Test + public void givenByteStreamWhenUploadedThenCorrect() throws IOException, UnirestException { + try (InputStream inputStream = new FileInputStream(new File("/path/to/file/artcile.txt"))) { + byte[] bytes = new byte[inputStream.available()]; + inputStream.read(bytes); + HttpResponse jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d") + .field("file", bytes, "article.txt") + .asJson(); + assertEquals(201, jsonResponse.getStatus()); + } + + } + + // @Test + public void givenInputStreamWhenUploadedThenCorrect() throws UnirestException, IOException { + try (InputStream inputStream = new FileInputStream(new File("/path/to/file/artcile.txt"))) { + + HttpResponse jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d") + .field("file", inputStream, ContentType.APPLICATION_OCTET_STREAM, "article.txt") + .asJson(); + assertEquals(201, jsonResponse.getStatus()); + + } + } +} diff --git a/libraries/src/test/java/com/baeldung/unirest/HttpClientTest.java b/libraries/src/test/java/com/baeldung/unirest/HttpClientTest.java deleted file mode 100644 index 82093ad297..0000000000 --- a/libraries/src/test/java/com/baeldung/unirest/HttpClientTest.java +++ /dev/null @@ -1,174 +0,0 @@ -package com.baeldung.unirest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -import org.apache.http.entity.ContentType; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -import com.baeldung.unirest.Article; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.mashape.unirest.http.HttpResponse; -import com.mashape.unirest.http.JsonNode; -import com.mashape.unirest.http.ObjectMapper; -import com.mashape.unirest.http.Unirest; -import com.mashape.unirest.http.async.Callback; -import com.mashape.unirest.http.exceptions.UnirestException; - -public class HttpClientTest { - - @BeforeClass - public static void setup() { - // Unirest.setProxy(new HttpHost("localhost", 8080)); - Unirest.setTimeouts(20000, 15000); - Unirest.setDefaultHeader("X-app-name", "baeldung-unirest"); - Unirest.setDefaultHeader("X-request-id", "100004f00ab5"); - Unirest.setConcurrency(20, 5); - Unirest.setObjectMapper(new ObjectMapper() { - com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper(); - - public String writeValue(Object value) { - try { - return mapper.writeValueAsString(value); - } catch (JsonProcessingException e) { - throw new RuntimeException(e); - } - - } - - public T readValue(String value, Class valueType) { - - try { - return mapper.readValue(value, valueType); - } catch (Exception e) { - throw new RuntimeException(e); - } - - } - }); - } - - @AfterClass - public static void tearDown() throws IOException { - Unirest.clearDefaultHeaders(); - Unirest.shutdown(); - } - - @Test - public void shouldReturnStatusOkay() throws UnirestException { - HttpResponse jsonResponse = Unirest.get("http://www.mocky.io/v2/5a9ce37b3100004f00ab5154") - .header("accept", "application/json") - .queryString("apiKey", "123") - .asJson(); - assertNotNull(jsonResponse.getBody()); - assertEquals(200, jsonResponse.getStatus()); - } - - @Test - public void shouldReturnStatusAccepted() throws UnirestException { - - Map headers = new HashMap(); - headers.put("accept", "application/json"); - headers.put("Authorization", "Bearer 5a9ce37b3100004f00ab5154"); - - Map fields = new HashMap(); - fields.put("name", "Sam Baeldung"); - fields.put("id", "PSP123"); - - HttpResponse jsonResponse = Unirest.put("http://www.mocky.io/v2/5a9ce7853100002a00ab515e") - .headers(headers) - .fields(fields) - .asJson(); - assertNotNull(jsonResponse.getBody()); - assertEquals(202, jsonResponse.getStatus()); - } - - @Test - public void givenRequestBodyWhenCreatedThenCorrect() throws UnirestException { - - HttpResponse jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d") - .body("{\"name\":\"Sam Baeldung\", \"city\":\"viena\"}") - .asJson(); - assertEquals(201, jsonResponse.getStatus()); - } - - @Test - @Ignore - public void whenAysncRequestShouldReturnOk() throws InterruptedException, ExecutionException { - Future> future = Unirest.post("http://www.mocky.io/v2/5a9ce37b3100004f00ab5154?mocky-delay=10000ms") - .header("accept", "application/json") - .asJsonAsync(new Callback() { - - public void failed(UnirestException e) { - // Do something if the request failed - } - - public void completed(HttpResponse response) { - // Do something if the request is successful - } - - public void cancelled() { - // Do something if the request is cancelled - } - - }); - assertEquals(200, future.get() - .getStatus()); - - } - - @Test - public void givenArticleWhenCreatedThenCorrect() throws UnirestException { - Article article = new Article("ID1213", "Guide to Rest", "baeldung"); - HttpResponse jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d") - .body(article) - .asJson(); - assertEquals(201, jsonResponse.getStatus()); - } - - // @Test - public void givenFileWhenUploadedThenCorrect() throws UnirestException { - - HttpResponse jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d") - .field("file", new File("/path/to/file")) - .asJson(); - assertEquals(201, jsonResponse.getStatus()); - } - - // @Test - public void givenByteStreamWhenUploadedThenCorrect() throws IOException, UnirestException { - try (InputStream inputStream = new FileInputStream(new File("/path/to/file/artcile.txt"))) { - byte[] bytes = new byte[inputStream.available()]; - inputStream.read(bytes); - HttpResponse jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d") - .field("file", bytes, "article.txt") - .asJson(); - assertEquals(201, jsonResponse.getStatus()); - } - - } - - // @Test - public void givenInputStreamWhenUploadedThenCorrect() throws UnirestException, IOException { - try (InputStream inputStream = new FileInputStream(new File("/path/to/file/artcile.txt"))) { - - HttpResponse jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d") - .field("file", inputStream, ContentType.APPLICATION_OCTET_STREAM, "article.txt") - .asJson(); - assertEquals(201, jsonResponse.getStatus()); - - } - } -} diff --git a/libraries/src/test/resources/ftp/baz.txt b/libraries/src/test/resources/ftp/baz.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/libraries/src/test/resources/yaml/customer.yaml b/libraries/src/test/resources/yaml/customer.yaml new file mode 100644 index 0000000000..aa76141c7d --- /dev/null +++ b/libraries/src/test/resources/yaml/customer.yaml @@ -0,0 +1,3 @@ +firstName: "John" +lastName: "Doe" +age: 20 \ No newline at end of file diff --git a/libraries/src/test/resources/yaml/customer_with_contact_details.yaml b/libraries/src/test/resources/yaml/customer_with_contact_details.yaml new file mode 100644 index 0000000000..34563cbd21 --- /dev/null +++ b/libraries/src/test/resources/yaml/customer_with_contact_details.yaml @@ -0,0 +1,7 @@ +firstName: "John" +lastName: "Doe" +age: 31 +contactDetails: + - { type: "mobile", number: 123456789} + - { type: "landline", number: 456786868} + \ No newline at end of file diff --git a/libraries/src/test/resources/yaml/customer_with_contact_details_and_address.yaml b/libraries/src/test/resources/yaml/customer_with_contact_details_and_address.yaml new file mode 100644 index 0000000000..664afe8594 --- /dev/null +++ b/libraries/src/test/resources/yaml/customer_with_contact_details_and_address.yaml @@ -0,0 +1,13 @@ +firstName: "John" +lastName: "Doe" +age: 31 +contactDetails: + - type: "mobile" + number: 123456789 + - type: "landline" + number: 456786868 +homeAddress: + line: "Xyz, DEF Street" + city: "City Y" + state: "State Y" + zip: 345657 diff --git a/libraries/src/test/resources/yaml/customer_with_contact_details_and_tags.yaml b/libraries/src/test/resources/yaml/customer_with_contact_details_and_tags.yaml new file mode 100644 index 0000000000..145da256d9 --- /dev/null +++ b/libraries/src/test/resources/yaml/customer_with_contact_details_and_tags.yaml @@ -0,0 +1,6 @@ +firstName: "John" +lastName: "Doe" +age: 31 +contactDetails: + - !contact { type: "mobile", number: 123456789} + - !contact { type: "landline", number: 456786868} diff --git a/libraries/src/test/resources/yaml/customer_with_type.yaml b/libraries/src/test/resources/yaml/customer_with_type.yaml new file mode 100644 index 0000000000..6e13c26cea --- /dev/null +++ b/libraries/src/test/resources/yaml/customer_with_type.yaml @@ -0,0 +1,4 @@ +!!com.baeldung.snakeyaml.Customer +firstName: "John" +lastName: "Doe" +age: 20 \ No newline at end of file diff --git a/libraries/src/test/resources/yaml/customers.yaml b/libraries/src/test/resources/yaml/customers.yaml new file mode 100644 index 0000000000..23b9039c2e --- /dev/null +++ b/libraries/src/test/resources/yaml/customers.yaml @@ -0,0 +1,8 @@ +--- +firstName: "John" +lastName: "Doe" +age: 20 +--- +firstName: "Jack" +lastName: "Jones" +age: 25 \ No newline at end of file diff --git a/linkrest/pom.xml b/linkrest/pom.xml index 5a8b39e7df..a27caea1ff 100644 --- a/linkrest/pom.xml +++ b/linkrest/pom.xml @@ -1,5 +1,5 @@ + 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 linkrest diff --git a/linkrest/src/main/resources/logback.xml b/linkrest/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/linkrest/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/logging-modules/README.md b/logging-modules/README.md index a589b1245c..0f12d7eb22 100644 --- a/logging-modules/README.md +++ b/logging-modules/README.md @@ -5,4 +5,4 @@ - [Creating a Custom Logback Appender](http://www.baeldung.com/custom-logback-appender) - [Get Log Output in JSON Format](http://www.baeldung.com/java-log-json-output) -- [A Guide To Logback](http://www.baeldung.com/a-guide-to-logback) +- [A Guide To Logback](http://www.baeldung.com/logback) diff --git a/logging-modules/log-mdc/pom.xml b/logging-modules/log-mdc/pom.xml index 7628c708e9..8e9968085e 100644 --- a/logging-modules/log-mdc/pom.xml +++ b/logging-modules/log-mdc/pom.xml @@ -1,5 +1,5 @@ + 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 log-mdc @@ -9,11 +9,11 @@ tutorial on logging with MDC and NDC - com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../../parent-spring - + com.baeldung + parent-spring-4 + 0.0.1-SNAPSHOT + ../../parent-spring-4 + @@ -79,23 +79,13 @@ - - 4.3.4.RELEASE - 1.2.17 - 2.7 - 3.3.6 - 3.3.0.Final - 3.1.0 - 2.8.5 - - org.apache.maven.plugins maven-war-plugin - 2.4 + ${maven-war-plugin.version} src/main/webapp logging-service @@ -106,4 +96,15 @@ logging-service + + + 1.2.17 + 2.7 + 3.3.6 + 3.3.0.Final + 3.1.0 + 2.8.5 + 2.4 + + diff --git a/logging-modules/log4j/README.md b/logging-modules/log4j/README.md index 8aae1b5826..9f4184ccba 100644 --- a/logging-modules/log4j/README.md +++ b/logging-modules/log4j/README.md @@ -4,3 +4,4 @@ - [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode) - [Introduction to SLF4J](http://www.baeldung.com/slf4j-with-log4j2-logback) - [A Guide to Rolling File Appenders](http://www.baeldung.com/java-logging-rolling-file-appenders) +- [Logging Exceptions Using SLF4J](https://www.baeldung.com/slf4j-log-exceptions) diff --git a/logging-modules/log4j/pom.xml b/logging-modules/log4j/pom.xml index 5e2f413e09..432295fc62 100644 --- a/logging-modules/log4j/pom.xml +++ b/logging-modules/log4j/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung log4j diff --git a/logging-modules/log4j/src/main/java/com/baeldung/slf4j/SLF4JLogExceptions.java b/logging-modules/log4j/src/main/java/com/baeldung/slf4j/SLF4JLogExceptions.java new file mode 100644 index 0000000000..bd572770ab --- /dev/null +++ b/logging-modules/log4j/src/main/java/com/baeldung/slf4j/SLF4JLogExceptions.java @@ -0,0 +1,16 @@ +package com.baeldung.slf4j; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SLF4JLogExceptions { + + public static void main(String[] args) { + Logger logger = LoggerFactory.getLogger(SLF4JLogExceptions.class); + + logger.error("An exception occurred!"); + logger.error("An exception occurred!", new Exception("Custom exception")); + logger.error("{}, {}! An exception occurred!", "Hello", "World", new Exception("Custom exception")); + } + +} diff --git a/logging-modules/log4j2/README.md b/logging-modules/log4j2/README.md index 57ca4df21b..2cf6f9768f 100644 --- a/logging-modules/log4j2/README.md +++ b/logging-modules/log4j2/README.md @@ -2,3 +2,5 @@ - [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) +- [Programmatic Configuration with Log4j 2](http://www.baeldung.com/log4j2-programmatic-config) +- [Creating a Custom Log4j2 Appender](https://www.baeldung.com/log4j2-custom-appender) diff --git a/logging-modules/log4j2/pom.xml b/logging-modules/log4j2/pom.xml index e2ec67a5b5..65da318636 100644 --- a/logging-modules/log4j2/pom.xml +++ b/logging-modules/log4j2/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 log4j2 @@ -18,6 +18,13 @@ log4j-core ${log4j-core.version} + + + + org.apache.logging.log4j + log4j-api + ${log4j-core.version} + @@ -53,25 +60,65 @@ test-jar test - - - - 2.9.5 - 1.4.193 - 2.1.1 - 2.11.0 - + org.apache.maven.plugins maven-compiler-plugin - 3.7.0 + ${maven-compiler-plugin.version} none - + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + + + json + ${java.io.tmpdir}/${maven.build.timestamp}/logfile.json + + + + + + + + + + 2.9.5 + 1.4.193 + 2.1.1 + 2.11.0 + yyyyMMddHHmmss + + + \ No newline at end of file diff --git a/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/appender/MapAppender.java b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/appender/MapAppender.java new file mode 100644 index 0000000000..2015b6d573 --- /dev/null +++ b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/appender/MapAppender.java @@ -0,0 +1,54 @@ +/** + * + */ +package com.baeldung.logging.log4j2.appender; + +import java.time.Instant; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.core.Appender; +import org.apache.logging.log4j.core.Core; +import org.apache.logging.log4j.core.Filter; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.config.plugins.PluginAttribute; +import org.apache.logging.log4j.core.config.plugins.PluginElement; +import org.apache.logging.log4j.core.config.plugins.PluginFactory; + +@Plugin(name = "MapAppender", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE) +public class MapAppender extends AbstractAppender { + + private ConcurrentMap eventMap = new ConcurrentHashMap<>(); + + protected MapAppender(String name, Filter filter) { + super(name, filter, null); + } + + @PluginFactory + public static MapAppender createAppender(@PluginAttribute("name") String name, @PluginElement("Filter") final Filter filter) { + return new MapAppender(name, filter); + } + + @Override + public void append(LogEvent event) { + if (event.getLevel() + .isLessSpecificThan(Level.WARN)) { + error("Unable to log less than WARN level."); + return; + } + eventMap.put(Instant.now() + .toString(), event); + } + + public ConcurrentMap getEventMap() { + return eventMap; + } + + public void setEventMap(ConcurrentMap eventMap) { + this.eventMap = eventMap; + } + +} diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/Log4j2BaseIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/Log4j2BaseIntegrationTest.java new file mode 100644 index 0000000000..6b68977fd6 --- /dev/null +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/Log4j2BaseIntegrationTest.java @@ -0,0 +1,18 @@ +package com.baeldung.logging.log4j2; + +import org.apache.logging.log4j.core.config.ConfigurationFactory; +import org.apache.logging.log4j.spi.LoggerContextFactory; +import org.junit.AfterClass; + +import java.lang.reflect.Field; + +public class Log4j2BaseIntegrationTest { + @AfterClass + public static void tearDown() throws Exception { + Field factories = ConfigurationFactory.class.getDeclaredField("factories"); + factories.setAccessible(true); + factories.set(null, null); + ConfigurationFactory.resetConfigurationFactory(); + + } +} diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/Log4j2Test.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/Log4j2Test.java deleted file mode 100644 index abd92a2202..0000000000 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/Log4j2Test.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.logging.log4j2; - -import org.apache.logging.log4j.core.config.ConfigurationFactory; -import org.apache.logging.log4j.spi.LoggerContextFactory; -import org.junit.AfterClass; - -import java.lang.reflect.Field; - -public class Log4j2Test { - @AfterClass - public static void tearDown() throws Exception { - Field factories = ConfigurationFactory.class.getDeclaredField("factories"); - factories.setAccessible(true); - factories.set(null, null); - ConfigurationFactory.resetConfigurationFactory(); - - } -} diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/appender/MapAppenderIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/appender/MapAppenderIntegrationTest.java new file mode 100644 index 0000000000..020aaafc74 --- /dev/null +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/appender/MapAppenderIntegrationTest.java @@ -0,0 +1,35 @@ +package com.baeldung.logging.log4j2.appender; + +import static org.junit.Assert.assertEquals; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.config.Configuration; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class MapAppenderIntegrationTest { + + private Logger logger; + + @Before + public void setup() { + logger = LogManager.getLogger(MapAppenderIntegrationTest.class); + } + + @Test + public void whenLoggerEmitsLoggingEvent_thenAppenderReceivesEvent() throws Exception { + logger.info("Test from {}", this.getClass() + .getSimpleName()); + LoggerContext context = LoggerContext.getContext(false); + Configuration config = context.getConfiguration(); + MapAppender appender = config.getAppender("MapAppender"); + assertEquals(appender.getEventMap() + .size(), 1); + } + +} diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/setconfigurationfactory/SetConfigurationFactoryIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/setconfigurationfactory/SetConfigurationFactoryIntegrationTest.java new file mode 100644 index 0000000000..db3b0780a2 --- /dev/null +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/setconfigurationfactory/SetConfigurationFactoryIntegrationTest.java @@ -0,0 +1,35 @@ +/** + This class invokes the configuration factory with static initialization, + as defined in section 4.1 of the "Programmatic Configuration with Log4j 2" +**/ +package com.baeldung.logging.log4j2.setconfigurationfactory; + +import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest; +import com.baeldung.logging.log4j2.simpleconfiguration.CustomConfigurationFactory; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; +import org.apache.logging.log4j.core.config.ConfigurationFactory; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class SetConfigurationFactoryIntegrationTest extends Log4j2BaseIntegrationTest { + @BeforeClass + public static void setUp() { + CustomConfigurationFactory customConfigurationFactory = new CustomConfigurationFactory(); + ConfigurationFactory.setConfigurationFactory(customConfigurationFactory); + } + + @Test + public void givenDirectConfiguration_whenUsingFlowMarkers_ThenLogsCorrectly() { + Logger logger = LogManager.getLogger(this.getClass()); + Marker markerContent = MarkerManager.getMarker("FLOW"); + logger.debug(markerContent, "Debug log message"); + logger.info(markerContent, "Info log message"); + logger.error(markerContent, "Error log message"); + } +} \ No newline at end of file diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/setconfigurationfactory/SetConfigurationFactoryTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/setconfigurationfactory/SetConfigurationFactoryTest.java deleted file mode 100644 index 2f9a837424..0000000000 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/setconfigurationfactory/SetConfigurationFactoryTest.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - This class invokes the configuration factory with static initialization, - as defined in section 4.1 of the "Programmatic Configuration with Log4j 2" -**/ -package com.baeldung.logging.log4j2.setconfigurationfactory; - -import com.baeldung.logging.log4j2.Log4j2Test; -import com.baeldung.logging.log4j2.simpleconfiguration.CustomConfigurationFactory; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.Marker; -import org.apache.logging.log4j.MarkerManager; -import org.apache.logging.log4j.core.config.ConfigurationFactory; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -@RunWith(JUnit4.class) -public class SetConfigurationFactoryTest extends Log4j2Test { - @BeforeClass - public static void setUp() { - CustomConfigurationFactory customConfigurationFactory = new CustomConfigurationFactory(); - ConfigurationFactory.setConfigurationFactory(customConfigurationFactory); - } - - @Test - public void givenDirectConfiguration_whenUsingFlowMarkers_ThenLogsCorrectly() { - Logger logger = LogManager.getLogger(this.getClass()); - Marker markerContent = MarkerManager.getMarker("FLOW"); - logger.debug(markerContent, "Debug log message"); - logger.info(markerContent, "Info log message"); - logger.error(markerContent, "Error log message"); - } -} \ No newline at end of file diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfiguration/SimpleConfigurationIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfiguration/SimpleConfigurationIntegrationTest.java new file mode 100644 index 0000000000..25f0736df5 --- /dev/null +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfiguration/SimpleConfigurationIntegrationTest.java @@ -0,0 +1,30 @@ +/** + This class invokes the configuration factory through the run time property, + as defined in section 4.2 of the "Programmatic Configuration with Log4j 2" +**/ +package com.baeldung.logging.log4j2.simpleconfiguration; + +import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; +import org.apache.logging.log4j.core.config.plugins.util.PluginManager; +import org.junit.BeforeClass; +import org.junit.Test; + +public class SimpleConfigurationIntegrationTest extends Log4j2BaseIntegrationTest { + @BeforeClass + public static void setUp() { + PluginManager.addPackage("com.baeldung.logging.log4j2.simpleconfiguration"); + } + + @Test + public void givenSimpleConfigurationPlugin_whenUsingFlowMarkers_thenLogsCorrectly() throws Exception { + Logger logger = LogManager.getLogger(this.getClass()); + Marker markerContent = MarkerManager.getMarker("FLOW"); + logger.debug(markerContent, "Debug log message"); + logger.info(markerContent, "Info log message"); + logger.error(markerContent, "Error log message"); + } +} \ No newline at end of file diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfiguration/SimpleConfigurationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfiguration/SimpleConfigurationTest.java deleted file mode 100644 index 02330a808b..0000000000 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfiguration/SimpleConfigurationTest.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - This class invokes the configuration factory through the run time property, - as defined in section 4.2 of the "Programmatic Configuration with Log4j 2" -**/ -package com.baeldung.logging.log4j2.simpleconfiguration; - -import com.baeldung.logging.log4j2.Log4j2Test; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.Marker; -import org.apache.logging.log4j.MarkerManager; -import org.apache.logging.log4j.core.config.plugins.util.PluginManager; -import org.junit.BeforeClass; -import org.junit.Test; - -public class SimpleConfigurationTest extends Log4j2Test { - @BeforeClass - public static void setUp() { - PluginManager.addPackage("com.baeldung.logging.log4j2.simpleconfiguration"); - } - - @Test - public void givenSimpleConfigurationPlugin_whenUsingFlowMarkers_thenLogsCorrectly() throws Exception { - Logger logger = LogManager.getLogger(this.getClass()); - Marker markerContent = MarkerManager.getMarker("FLOW"); - logger.debug(markerContent, "Debug log message"); - logger.info(markerContent, "Info log message"); - logger.error(markerContent, "Error log message"); - } -} \ No newline at end of file diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfigurator/SimpleConfiguratorIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfigurator/SimpleConfiguratorIntegrationTest.java new file mode 100644 index 0000000000..49cde67303 --- /dev/null +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfigurator/SimpleConfiguratorIntegrationTest.java @@ -0,0 +1,40 @@ +/** + * This class demonstrates how to use ConfigurationBuilderFactory directly, + * as described in Section 3 of "Programmatic Configuration with Log4j 2" + **/ + +package com.baeldung.logging.log4j2.simpleconfigurator; + +import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.core.appender.ConsoleAppender; +import org.apache.logging.log4j.core.config.Configurator; +import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder; +import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder; +import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory; +import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class SimpleConfiguratorIntegrationTest extends Log4j2BaseIntegrationTest { + + @Test + public void givenDefaultLog4j2Environment_whenProgrammaticallyConfigured_thenLogsCorrectly() { + ConfigurationBuilder builder = ConfigurationBuilderFactory.newConfigurationBuilder(); + AppenderComponentBuilder console = builder.newAppender("Stdout", "CONSOLE") + .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT); + console.add(builder.newLayout("PatternLayout") + .addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable")); + builder.add(console); + builder.add(builder.newLogger("com", Level.DEBUG) + .add(builder.newAppenderRef("Stdout")) + .addAttribute("additivity", false)); + builder.add(builder.newRootLogger(Level.ERROR) + .add(builder.newAppenderRef("Stdout"))); + Configurator.initialize(builder.build()); + LogPrinter logPrinter = new LogPrinter(); + logPrinter.printlog(); + } +} diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfigurator/SimpleConfiguratorTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfigurator/SimpleConfiguratorTest.java deleted file mode 100644 index 03bf996120..0000000000 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfigurator/SimpleConfiguratorTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * This class demonstrates how to use ConfigurationBuilderFactory directly, - * as described in Section 3 of "Programmatic Configuration with Log4j 2" - **/ - -package com.baeldung.logging.log4j2.simpleconfigurator; - -import com.baeldung.logging.log4j2.Log4j2Test; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.core.appender.ConsoleAppender; -import org.apache.logging.log4j.core.config.Configurator; -import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder; -import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder; -import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory; -import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -@RunWith(JUnit4.class) -public class SimpleConfiguratorTest extends Log4j2Test { - - @Test - public void givenDefaultLog4j2Environment_whenProgrammaticallyConfigured_thenLogsCorrectly() { - ConfigurationBuilder builder = ConfigurationBuilderFactory.newConfigurationBuilder(); - AppenderComponentBuilder console = builder.newAppender("Stdout", "CONSOLE") - .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT); - console.add(builder.newLayout("PatternLayout") - .addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable")); - builder.add(console); - builder.add(builder.newLogger("com", Level.DEBUG) - .add(builder.newAppenderRef("Stdout")) - .addAttribute("additivity", false)); - builder.add(builder.newRootLogger(Level.ERROR) - .add(builder.newAppenderRef("Stdout"))); - Configurator.initialize(builder.build()); - LogPrinter logPrinter = new LogPrinter(); - logPrinter.printlog(); - } -} diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingIntegrationTest.java index c15bd8a514..3e94e4e430 100644 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingIntegrationTest.java +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingIntegrationTest.java @@ -21,9 +21,12 @@ import com.baeldung.logging.log4j2.tests.jdbc.ConnectionFactory; @RunWith(JUnit4.class) public class CustomLoggingIntegrationTest { - + + private static String logFilePath = System.getProperty("logging.folder.path"); + @BeforeClass public static void setup() throws Exception { + Connection connection = ConnectionFactory.getConnection(); connection.createStatement() .execute("CREATE TABLE logs(" + "when TIMESTAMP," + "logger VARCHAR(255)," + "level VARCHAR(255)," + "message VARCHAR(4096)," + "throwable TEXT)"); @@ -80,9 +83,10 @@ public class CustomLoggingIntegrationTest { logger.info("This is async JSON message #{} at INFO level.", count); } - long logEventsCount = Files.lines(Paths.get("target/logfile.json")) + long logEventsCount = Files.lines(Paths.get(logFilePath)) .count(); - assertTrue(logEventsCount > 0 && logEventsCount <= count); + + assertTrue(logEventsCount >= 0 && logEventsCount <= count); } @Test @@ -114,7 +118,7 @@ public class CustomLoggingIntegrationTest { if (resultSet.next()) { logCount = resultSet.getInt("ROW_COUNT"); } - assertTrue(logCount == count); + assertTrue(logCount <= count); } @Test diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java new file mode 100644 index 0000000000..e842cda3d6 --- /dev/null +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java @@ -0,0 +1,47 @@ +package com.baeldung.logging.log4j2.tests; + +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JSONLayoutIntegrationTest extends Log4j2BaseIntegrationTest { + + private static Logger logger; + private ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream(); + private PrintStream ps = new PrintStream(consoleOutput); + + @Before + public void setUp() { + // Redirect console output to our stream + System.setOut(ps); + logger = LogManager.getLogger("CONSOLE_JSON_APPENDER"); + } + + @Test + public void whenLogLayoutInJSON_thenOutputIsCorrectJSON() { + logger.debug("Debug message"); + String currentLog = consoleOutput.toString(); + assertTrue(currentLog.isEmpty()); + assertTrue(isValidJSON(currentLog)); + } + + public static boolean isValidJSON(String jsonInString) { + try { + final ObjectMapper mapper = new ObjectMapper(); + mapper.readTree(jsonInString); + return true; + } catch (IOException e) { + return false; + } + } +} \ No newline at end of file diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutTest.java deleted file mode 100644 index 7a6fbf999c..0000000000 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.logging.log4j2.tests; - -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.PrintStream; - -import com.baeldung.logging.log4j2.Log4j2Test; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.junit.Before; -import org.junit.Test; - -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JSONLayoutTest extends Log4j2Test { - - private static Logger logger; - private ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream(); - private PrintStream ps = new PrintStream(consoleOutput); - - @Before - public void setUp() { - // Redirect console output to our stream - System.setOut(ps); - logger = LogManager.getLogger("CONSOLE_JSON_APPENDER"); - } - - @Test - public void whenLogLayoutInJSON_thenOutputIsCorrectJSON() { - logger.debug("Debug message"); - String currentLog = consoleOutput.toString(); - assertTrue(!currentLog.isEmpty() && isValidJSON(currentLog)); - } - - public static boolean isValidJSON(String jsonInString) { - try { - final ObjectMapper mapper = new ObjectMapper(); - mapper.readTree(jsonInString); - return true; - } catch (IOException e) { - return false; - } - } -} \ No newline at end of file diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/XMLConfigLogIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/XMLConfigLogIntegrationTest.java new file mode 100644 index 0000000000..d705b50b1a --- /dev/null +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/XMLConfigLogIntegrationTest.java @@ -0,0 +1,44 @@ + +/** + This class loads the logging configuration from the xml defined in + src/main/resources and uses the same configuration generated through + programmatic configuration as defined in simple-configuration example. +**/ + +package com.baeldung.logging.log4j2.xmlconfiguration; + +import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.config.plugins.util.PluginManager; +import org.junit.BeforeClass; +import org.junit.Test; + +public class XMLConfigLogIntegrationTest extends Log4j2BaseIntegrationTest { + + @BeforeClass + public static void setUp() { + PluginManager.addPackage("com.baeldung.logging.log4j2.xmlconfiguration"); + } + + @Test + public void givenXMLConfigurationPlugin_whenUsingFlowMarkers_ThenLogsCorrectly() throws Exception { + Logger logger = LogManager.getLogger(this.getClass()); + Marker markerContent = MarkerManager.getMarker("FLOW"); + logger.debug(markerContent, "Debug log message"); + logger.info(markerContent, "Info log message"); + logger.error(markerContent, "Error log message"); + } + + @Test + public void givenXMLConfigurationPlugin_whenSimpleLog_ThenLogsCorrectly() throws Exception { + Logger logger = LogManager.getLogger(this.getClass()); + LoggerContext ctx = (LoggerContext) LogManager.getContext(); + logger.debug("Debug log message"); + logger.info("Info log message"); + logger.error("Error log message"); + } +} diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/XMLConfigLogTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/XMLConfigLogTest.java deleted file mode 100644 index 41f733804a..0000000000 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/XMLConfigLogTest.java +++ /dev/null @@ -1,44 +0,0 @@ - -/** - This class loads the logging configuration from the xml defined in - src/main/resources and uses the same configuration generated through - programmatic configuration as defined in simple-configuration example. -**/ - -package com.baeldung.logging.log4j2.xmlconfiguration; - -import com.baeldung.logging.log4j2.Log4j2Test; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.Marker; -import org.apache.logging.log4j.MarkerManager; -import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.config.plugins.util.PluginManager; -import org.junit.BeforeClass; -import org.junit.Test; - -public class XMLConfigLogTest extends Log4j2Test { - - @BeforeClass - public static void setUp() { - PluginManager.addPackage("com.baeldung.logging.log4j2.xmlconfiguration"); - } - - @Test - public void givenXMLConfigurationPlugin_whenUsingFlowMarkers_ThenLogsCorrectly() throws Exception { - Logger logger = LogManager.getLogger(this.getClass()); - Marker markerContent = MarkerManager.getMarker("FLOW"); - logger.debug(markerContent, "Debug log message"); - logger.info(markerContent, "Info log message"); - logger.error(markerContent, "Error log message"); - } - - @Test - public void givenXMLConfigurationPlugin_whenSimpleLog_ThenLogsCorrectly() throws Exception { - Logger logger = LogManager.getLogger(this.getClass()); - LoggerContext ctx = (LoggerContext) LogManager.getContext(); - logger.debug("Debug log message"); - logger.info("Info log message"); - logger.error("Error log message"); - } -} diff --git a/logging-modules/log4j2/src/test/resources/log4j2.xml b/logging-modules/log4j2/src/test/resources/log4j2.xml index 4dcb7cce5a..246ffb0707 100644 --- a/logging-modules/log4j2/src/test/resources/log4j2.xml +++ b/logging-modules/log4j2/src/test/resources/log4j2.xml @@ -1,6 +1,6 @@ - + @@ -21,7 +21,7 @@ - + @@ -50,6 +50,7 @@ size="17 kB" /> + + \ No newline at end of file diff --git a/logging-modules/logback/pom.xml b/logging-modules/logback/pom.xml index 2ffcd0dbf8..e917754b3c 100644 --- a/logging-modules/logback/pom.xml +++ b/logging-modules/logback/pom.xml @@ -1,6 +1,6 @@ 4.0.0 @@ -40,7 +40,6 @@ - UTF-8 1.2.3 0.1.5 2.9.3 diff --git a/logging-modules/logback/src/test/java/com/baeldung/logback/JSONLayoutIntegrationTest.java b/logging-modules/logback/src/test/java/com/baeldung/logback/JSONLayoutIntegrationTest.java new file mode 100644 index 0000000000..06962c1ea1 --- /dev/null +++ b/logging-modules/logback/src/test/java/com/baeldung/logback/JSONLayoutIntegrationTest.java @@ -0,0 +1,45 @@ +package com.baeldung.logback; + +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; + +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JSONLayoutIntegrationTest { + + private static Logger logger; + private ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream(); + private PrintStream ps = new PrintStream(consoleOutput); + + @Before + public void setUp() { + // Redirect console output to our stream + System.setOut(ps); + logger = LoggerFactory.getLogger("jsonLogger"); + } + + @Test + public void whenLogLayoutInJSON_thenOutputIsCorrectJSON() { + logger.debug("Debug message"); + String currentLog = consoleOutput.toString(); + assertTrue(!currentLog.isEmpty() && isValidJSON(currentLog)); + } + + public static boolean isValidJSON(String jsonInString) { + try { + final ObjectMapper mapper = new ObjectMapper(); + mapper.readTree(jsonInString); + return true; + } catch (IOException e) { + return false; + } + } +} diff --git a/logging-modules/logback/src/test/java/com/baeldung/logback/JSONLayoutTest.java b/logging-modules/logback/src/test/java/com/baeldung/logback/JSONLayoutTest.java deleted file mode 100644 index ca3c4b3457..0000000000 --- a/logging-modules/logback/src/test/java/com/baeldung/logback/JSONLayoutTest.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.logback; - -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.PrintStream; - -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JSONLayoutTest { - - private static Logger logger; - private ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream(); - private PrintStream ps = new PrintStream(consoleOutput); - - @Before - public void setUp() { - // Redirect console output to our stream - System.setOut(ps); - logger = LoggerFactory.getLogger("jsonLogger"); - } - - @Test - public void whenLogLayoutInJSON_thenOutputIsCorrectJSON() { - logger.debug("Debug message"); - String currentLog = consoleOutput.toString(); - assertTrue(!currentLog.isEmpty() && isValidJSON(currentLog)); - } - - public static boolean isValidJSON(String jsonInString) { - try { - final ObjectMapper mapper = new ObjectMapper(); - mapper.readTree(jsonInString); - return true; - } catch (IOException e) { - return false; - } - } -} diff --git a/logging-modules/logback/src/test/java/com/baeldung/logback/LogbackIntegrationTest.java b/logging-modules/logback/src/test/java/com/baeldung/logback/LogbackIntegrationTest.java new file mode 100644 index 0000000000..2f4553df41 --- /dev/null +++ b/logging-modules/logback/src/test/java/com/baeldung/logback/LogbackIntegrationTest.java @@ -0,0 +1,89 @@ +package com.baeldung.logback; + +import ch.qos.logback.classic.Level; +import org.junit.Test; + +import ch.qos.logback.classic.Logger; +import org.slf4j.LoggerFactory; + +public class LogbackIntegrationTest { + + @Test + public void givenLogHierarchy_MessagesFiltered() { + + ch.qos.logback.classic.Logger parentLogger = + (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.baeldung.logback"); + + parentLogger.setLevel(Level.INFO); + + Logger childlogger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger("com.baeldung.logback.tests"); + + parentLogger.warn("This message is logged because WARN > INFO."); + + // This request is disabled, because DEBUG < INFO. + parentLogger.debug("This message is not logged because DEBUG < INFO."); + + childlogger.info("INFO == INFO"); + + childlogger.debug("DEBUG < INFO"); + + } + + @Test + public void givenRootLevel_MessagesFiltered() { + + ch.qos.logback.classic.Logger logger = + (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.baeldung.logback"); + + logger.debug("Hi there!"); + + Logger rootLogger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); + + logger.debug("This message is logged because DEBUG == DEBUG."); + + rootLogger.setLevel(Level.ERROR); + logger.warn("This message is not logged because WARN < ERROR."); + + logger.error("This is logged."); + + } + + @Test + public void givenParameters_ValuesLogged() { + + Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(LogbackIntegrationTest.class); + + String message = "This is a String"; + Integer zero = 0; + + try { + logger.debug("Logging message: {}", message); + logger.debug("Going to divide {} by {}", 42, zero); + int result = 42 / zero; + } catch (Exception e) { + logger.error("Error dividing {} by {} ", 42, zero, e); + } + } + + @Test + public void givenConfig_MessageFiltered() { + + Logger foobar = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.baeldung.foobar"); + Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.baeldung.logback"); + Logger testslogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.baeldung.logback.tests"); + + foobar.debug("This is logged from foobar"); + logger.debug("This is not logged from logger"); + logger.info("This is logged from logger"); + testslogger.info("This is not logged from tests"); + testslogger.warn("This is logged from tests"); + + + } + + + + + + +} diff --git a/logging-modules/logback/src/test/java/com/baeldung/logback/LogbackTests.java b/logging-modules/logback/src/test/java/com/baeldung/logback/LogbackTests.java deleted file mode 100644 index 85201965dc..0000000000 --- a/logging-modules/logback/src/test/java/com/baeldung/logback/LogbackTests.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.baeldung.logback; - -import ch.qos.logback.classic.Level; -import org.junit.Test; - -import ch.qos.logback.classic.Logger; -import org.slf4j.LoggerFactory; - -public class LogbackTests { - - @Test - public void givenLogHierarchy_MessagesFiltered() { - - ch.qos.logback.classic.Logger parentLogger = - (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.baeldung.logback"); - - parentLogger.setLevel(Level.INFO); - - Logger childlogger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger("com.baeldung.logback.tests"); - - parentLogger.warn("This message is logged because WARN > INFO."); - - // This request is disabled, because DEBUG < INFO. - parentLogger.debug("This message is not logged because DEBUG < INFO."); - - childlogger.info("INFO == INFO"); - - childlogger.debug("DEBUG < INFO"); - - } - - @Test - public void givenRootLevel_MessagesFiltered() { - - ch.qos.logback.classic.Logger logger = - (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.baeldung.logback"); - - logger.debug("Hi there!"); - - Logger rootLogger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); - - logger.debug("This message is logged because DEBUG == DEBUG."); - - rootLogger.setLevel(Level.ERROR); - logger.warn("This message is not logged because WARN < ERROR."); - - logger.error("This is logged."); - - } - - @Test - public void givenParameters_ValuesLogged() { - - Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(LogbackTests.class); - - String message = "This is a String"; - Integer zero = 0; - - try { - logger.debug("Logging message: {}", message); - logger.debug("Going to divide {} by {}", 42, zero); - int result = 42 / zero; - } catch (Exception e) { - logger.error("Error dividing {} by {} ", 42, zero, e); - } - } - - @Test - public void givenConfig_MessageFiltered() { - - Logger foobar = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.baeldung.foobar"); - Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.baeldung.logback"); - Logger testslogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.baeldung.logback.tests"); - - foobar.debug("This is logged from foobar"); - logger.debug("This is not logged from logger"); - logger.info("This is logged from logger"); - testslogger.info("This is not logged from tests"); - testslogger.warn("This is logged from tests"); - - - } - - - - - - -} diff --git a/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderTest.java b/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderTest.java deleted file mode 100644 index a5a938a923..0000000000 --- a/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.logback; - -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.LoggerContext; -import ch.qos.logback.classic.spi.LoggingEvent; -import ch.qos.logback.core.BasicStatusManager; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class MapAppenderTest { - - private LoggerContext ctx; - - private MapAppender mapAppender = new MapAppender(); - - private LoggingEvent event; - - @Before - public void setUp() throws Exception { - ctx = new LoggerContext(); - ctx.setName("test context"); - ctx.setStatusManager(new BasicStatusManager()); - mapAppender.setContext(ctx); - mapAppender.setPrefix("prefix"); - event = new LoggingEvent("fqcn", ctx.getLogger("logger"), Level.INFO, "Test message for logback appender", null, new Object[0]); - ctx.start(); - } - - @After - public void tearDown() throws Exception { - ctx.stop(); - mapAppender.stop(); - } - - @Test - public void whenPrefixIsNull_thenMapAppenderDoesNotLog() throws Exception { - mapAppender.setPrefix(null); - mapAppender.append(event); - assertTrue(mapAppender.getEventMap().isEmpty()); - } - - @Test - public void whenPrefixIsEmpty_thenMapAppenderDoesNotLog() throws Exception { - mapAppender.setPrefix(""); - mapAppender.append(event); - assertTrue(mapAppender.getEventMap().isEmpty()); - } - - @Test - public void whenLogMessageIsEmitted_thenMapAppenderReceivesMessage() throws Exception { - mapAppender.append(event); - assertEquals(mapAppender.getEventMap().size(), 1); - mapAppender.getEventMap().forEach((k, v) -> assertTrue(k.startsWith("prefix"))); - } - -} diff --git a/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderUnitTest.java b/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderUnitTest.java new file mode 100644 index 0000000000..742b219a27 --- /dev/null +++ b/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.logback; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.spi.LoggingEvent; +import ch.qos.logback.core.BasicStatusManager; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class MapAppenderUnitTest { + + private LoggerContext ctx; + + private MapAppender mapAppender = new MapAppender(); + + private LoggingEvent event; + + @Before + public void setUp() throws Exception { + ctx = new LoggerContext(); + ctx.setName("test context"); + ctx.setStatusManager(new BasicStatusManager()); + mapAppender.setContext(ctx); + mapAppender.setPrefix("prefix"); + event = new LoggingEvent("fqcn", ctx.getLogger("logger"), Level.INFO, "Test message for logback appender", null, new Object[0]); + ctx.start(); + } + + @After + public void tearDown() throws Exception { + ctx.stop(); + mapAppender.stop(); + } + + @Test + public void whenPrefixIsNull_thenMapAppenderDoesNotLog() throws Exception { + mapAppender.setPrefix(null); + mapAppender.append(event); + assertTrue(mapAppender.getEventMap().isEmpty()); + } + + @Test + public void whenPrefixIsEmpty_thenMapAppenderDoesNotLog() throws Exception { + mapAppender.setPrefix(""); + mapAppender.append(event); + assertTrue(mapAppender.getEventMap().isEmpty()); + } + + @Test + public void whenLogMessageIsEmitted_thenMapAppenderReceivesMessage() throws Exception { + mapAppender.append(event); + assertEquals(mapAppender.getEventMap().size(), 1); + mapAppender.getEventMap().forEach((k, v) -> assertTrue(k.startsWith("prefix"))); + } + +} diff --git a/lombok/README.md b/lombok/README.md index 4dc1c2d09d..1a787e32c7 100644 --- a/lombok/README.md +++ b/lombok/README.md @@ -1,2 +1,3 @@ ## Relevant Articles: - [Introduction to Project Lombok](http://www.baeldung.com/intro-to-project-lombok) +- [Using Lombok’s @Builder Annotation](http://www.baeldung.com/lombok-builder) diff --git a/lombok/pom.xml b/lombok/pom.xml index e0b0426c58..eba140122a 100644 --- a/lombok/pom.xml +++ b/lombok/pom.xml @@ -1,6 +1,6 @@ 4.0.0 @@ -66,8 +66,7 @@ false - @@ -75,7 +74,6 @@ - UTF-8 1.16.18 diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/Child.java b/lombok/src/main/java/com/baeldung/lombok/builder/Child.java new file mode 100644 index 0000000000..70f6d9c46e --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/Child.java @@ -0,0 +1,19 @@ +package com.baeldung.lombok.builder; + +import lombok.Builder; +import lombok.Getter; + +@Getter +public class Child extends Parent { + + private final String childName; + private final int childAge; + + @Builder(builderMethodName = "childBuilder") + public Child(String parentName, int parentAge, String childName, int childAge) { + super(parentName, parentAge); + this.childName = childName; + this.childAge = childAge; + } + +} diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/ClientBuilder.java b/lombok/src/main/java/com/baeldung/lombok/builder/ClientBuilder.java new file mode 100644 index 0000000000..32c3d4b8ce --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/ClientBuilder.java @@ -0,0 +1,11 @@ +package com.baeldung.lombok.builder; + +import lombok.Builder; + +class ClientBuilder { + + @Builder(builderMethodName = "builder") + public static ImmutableClient newClient(int id, String name) { + return new ImmutableClient(id, name); + } +} diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/ImmutableClient.java b/lombok/src/main/java/com/baeldung/lombok/builder/ImmutableClient.java new file mode 100644 index 0000000000..48782583e2 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/ImmutableClient.java @@ -0,0 +1,11 @@ +package com.baeldung.lombok.builder; + +import lombok.Value; + +@Value +final class ImmutableClient { + + private int id; + private String name; + +} diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/Parent.java b/lombok/src/main/java/com/baeldung/lombok/builder/Parent.java new file mode 100644 index 0000000000..0cf76d4b00 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/Parent.java @@ -0,0 +1,11 @@ +package com.baeldung.lombok.builder; + +import lombok.Builder; +import lombok.Getter; + +@Getter +@Builder +public class Parent { + private final String parentName; + private final int parentAge; +} \ No newline at end of file diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/Widget.java b/lombok/src/main/java/com/baeldung/lombok/builder/Widget.java new file mode 100644 index 0000000000..dbb99f55a4 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/Widget.java @@ -0,0 +1,13 @@ +package com.baeldung.lombok.builder; + +import lombok.Builder; +import lombok.Getter; + +@Getter +@Builder(toBuilder = true) +public class Widget { + + private final String name; + private final int id; + +} diff --git a/lombok/src/main/java/com/baeldung/lombok/getter/GetterBoolean.java b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBoolean.java new file mode 100644 index 0000000000..2191396e5d --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBoolean.java @@ -0,0 +1,15 @@ +package com.baeldung.lombok.getter; + + +import lombok.Getter; + +/** + * Related Article Sections: + * 4. Using @Getter on a Boolean Field + * + */ +public class GetterBoolean { + + @Getter + private Boolean running = true; +} diff --git a/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanPrimitive.java b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanPrimitive.java new file mode 100644 index 0000000000..5601f85b8b --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanPrimitive.java @@ -0,0 +1,16 @@ +package com.baeldung.lombok.getter; + + +import lombok.Getter; + +/** + * Related Article Sections: + * 3. Using @Getter on a boolean Field + * + */ +public class GetterBooleanPrimitive { + + @Getter + private boolean running; + +} diff --git a/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanPrimitiveSameAccessor.java b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanPrimitiveSameAccessor.java new file mode 100644 index 0000000000..af29a33c20 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanPrimitiveSameAccessor.java @@ -0,0 +1,18 @@ +package com.baeldung.lombok.getter; + + +import lombok.Getter; + +/** + * Related Article Sections: + * 3.2. Two boolean Fields With the Same Accessor Name + * + */ +public class GetterBooleanPrimitiveSameAccessor { + + @Getter + boolean running = true; + + @Getter + boolean isRunning = false; +} diff --git a/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanSameAccessor.java b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanSameAccessor.java new file mode 100644 index 0000000000..d972273b71 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanSameAccessor.java @@ -0,0 +1,13 @@ +package com.baeldung.lombok.getter; + +import lombok.Getter; + +/** + * Related Article Sections: + * 3.1. A boolean Field Having the Same Name With Its Accessor + * + */ +public class GetterBooleanSameAccessor { + @Getter + private boolean isRunning = true; +} diff --git a/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanType.java b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanType.java new file mode 100644 index 0000000000..0d3b9a928a --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanType.java @@ -0,0 +1,15 @@ +package com.baeldung.lombok.getter; + + +import lombok.Getter; + +/** + * Related Article Sections: + * 4. Using @Getter on a Boolean Field + * + */ +public class GetterBooleanType { + + @Getter + private Boolean running = true; +} diff --git a/lombok/src/main/resources/logback.xml b/lombok/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/lombok/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/lombok/src/test/java/com/baeldung/lombok/builder/BuilderUnitTest.java b/lombok/src/test/java/com/baeldung/lombok/builder/BuilderUnitTest.java new file mode 100644 index 0000000000..56a380569d --- /dev/null +++ b/lombok/src/test/java/com/baeldung/lombok/builder/BuilderUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.lombok.builder; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +public class BuilderUnitTest { + + @Test + public void givenBuilder_WidgetIsBuilt() { + Widget testWidget = Widget.builder() + .name("foo") + .id(1) + .build(); + assertThat(testWidget.getName()).isEqualTo("foo"); + assertThat(testWidget.getId()).isEqualTo(1); + } + + @Test + public void givenToBuilder_whenToBuilder_BuilderIsCreated() { + + Widget testWidget = Widget.builder() + .name("foo") + .id(1) + .build(); + Widget.WidgetBuilder widgetBuilder = testWidget.toBuilder(); + + Widget newWidget = widgetBuilder.id(2) + .build(); + assertThat(newWidget.getName()).isEqualTo("foo"); + assertThat(newWidget.getId()).isEqualTo(2); + } + + @Test + public void givenBuilderMethod_ClientIsBuilt() { + ImmutableClient testImmutableClient = ClientBuilder.builder() + .name("foo") + .id(1) + .build(); + assertThat(testImmutableClient.getName()).isEqualTo("foo"); + assertThat(testImmutableClient.getId()).isEqualTo(1); + } + + @Test + public void givenBuilderAtMethodLevel_ChildInheritingParentIsBuilt() { + Child child = Child.childBuilder() + .parentName("Andrea") + .parentAge(38) + .childName("Emma") + .childAge(6) + .build(); + + assertThat(child.getChildName()).isEqualTo("Emma"); + assertThat(child.getChildAge()).isEqualTo(6); + assertThat(child.getParentName()).isEqualTo("Andrea"); + assertThat(child.getParentAge()).isEqualTo(38); + } + +} diff --git a/lombok/src/test/java/com/baeldung/lombok/getter/GetterBooleanUnitTest.java b/lombok/src/test/java/com/baeldung/lombok/getter/GetterBooleanUnitTest.java new file mode 100644 index 0000000000..632594d575 --- /dev/null +++ b/lombok/src/test/java/com/baeldung/lombok/getter/GetterBooleanUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.lombok.getter; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class GetterBooleanUnitTest { + + @Test + public void whenBasicBooleanField_thenMethodNamePrefixedWithIsFollowedByFieldName() { + GetterBooleanPrimitive lombokExamples = new GetterBooleanPrimitive(); + assertFalse(lombokExamples.isRunning()); + } + + @Test + public void whenBooleanFieldPrefixedWithIs_thenMethodNameIsSameAsFieldName() { + GetterBooleanSameAccessor lombokExamples = new GetterBooleanSameAccessor(); + assertTrue(lombokExamples.isRunning()); + } + + @Test + public void whenTwoBooleanFieldsCauseNamingConflict_thenLombokMapsToFirstDeclaredField() { + GetterBooleanPrimitiveSameAccessor lombokExamples = new GetterBooleanPrimitiveSameAccessor(); + assertTrue(lombokExamples.isRunning() == lombokExamples.running); + assertFalse(lombokExamples.isRunning() == lombokExamples.isRunning); + } + + @Test + public void whenFieldOfBooleanType_thenLombokPrefixesMethodWithGetInsteadOfIs() { + GetterBooleanType lombokExamples = new GetterBooleanType(); + assertTrue(lombokExamples.getRunning()); + } +} diff --git a/lucene/README.md b/lucene/README.md index b1d33472f4..ea7f715480 100644 --- a/lucene/README.md +++ b/lucene/README.md @@ -2,3 +2,4 @@ - [Introduction to Apache Lucene](http://www.baeldung.com/lucene) - [A Simple File Search with Lucene](http://www.baeldung.com/lucene-file-search) +- [Guide to Lucene Analyzers](https://www.baeldung.com/lucene-analyzers) diff --git a/lucene/pom.xml b/lucene/pom.xml index b8786fadc7..f427cfd8a7 100644 --- a/lucene/pom.xml +++ b/lucene/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 lucene 0.0.1-SNAPSHOT @@ -23,24 +23,22 @@ lucene-queryparser ${lucene.version} - - junit - junit - ${junit.version} - test + org.apache.lucene + lucene-analyzers-common + ${lucene.version} + - UTF-8 1.16.18 1.0.0.Final 1.16.10.0 - 7.1.0 + 7.4.0 \ No newline at end of file diff --git a/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java b/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java index 97b1ec7b5d..8a31d3cb5b 100644 --- a/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java +++ b/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java @@ -4,7 +4,7 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; -import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.SortedDocValuesField; @@ -27,9 +27,9 @@ import org.apache.lucene.util.BytesRef; public class InMemoryLuceneIndex { private Directory memoryIndex; - private StandardAnalyzer analyzer; + private Analyzer analyzer; - public InMemoryLuceneIndex(Directory memoryIndex, StandardAnalyzer analyzer) { + public InMemoryLuceneIndex(Directory memoryIndex, Analyzer analyzer) { super(); this.memoryIndex = memoryIndex; this.analyzer = analyzer; diff --git a/lucene/src/main/java/com/baeldung/lucene/MyCustomAnalyzer.java b/lucene/src/main/java/com/baeldung/lucene/MyCustomAnalyzer.java new file mode 100644 index 0000000000..609e2d09d3 --- /dev/null +++ b/lucene/src/main/java/com/baeldung/lucene/MyCustomAnalyzer.java @@ -0,0 +1,26 @@ +package com.baeldung.lucene; + +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.analysis.LowerCaseFilter; +import org.apache.lucene.analysis.StopFilter; +import org.apache.lucene.analysis.TokenStream; +import org.apache.lucene.analysis.en.PorterStemFilter; +import org.apache.lucene.analysis.miscellaneous.CapitalizationFilter; +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.analysis.standard.StandardFilter; +import org.apache.lucene.analysis.standard.StandardTokenizer; + +public class MyCustomAnalyzer extends Analyzer{ + + @Override + protected TokenStreamComponents createComponents(String fieldName) { + final StandardTokenizer src = new StandardTokenizer(); + TokenStream result = new StandardFilter(src); + result = new LowerCaseFilter(result); + result = new StopFilter(result, StandardAnalyzer.STOP_WORDS_SET); + result = new PorterStemFilter(result); + result = new CapitalizationFilter(result); + return new TokenStreamComponents(src, result); + } + +} diff --git a/lucene/src/main/resources/logback.xml b/lucene/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/lucene/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/lucene/src/test/java/com/baeldung/lucene/LuceneAnalyzerIntegrationTest.java b/lucene/src/test/java/com/baeldung/lucene/LuceneAnalyzerIntegrationTest.java new file mode 100644 index 0000000000..28a87bba8c --- /dev/null +++ b/lucene/src/test/java/com/baeldung/lucene/LuceneAnalyzerIntegrationTest.java @@ -0,0 +1,147 @@ +package com.baeldung.lucene; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.collection.IsIterableContainingInOrder.contains; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.analysis.TokenStream; +import org.apache.lucene.analysis.core.KeywordAnalyzer; +import org.apache.lucene.analysis.core.SimpleAnalyzer; +import org.apache.lucene.analysis.core.StopAnalyzer; +import org.apache.lucene.analysis.core.WhitespaceAnalyzer; +import org.apache.lucene.analysis.custom.CustomAnalyzer; +import org.apache.lucene.analysis.en.EnglishAnalyzer; +import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper; +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; +import org.apache.lucene.document.Document; +import org.apache.lucene.index.Term; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.TermQuery; +import org.apache.lucene.store.RAMDirectory; +import org.junit.Test; + +public class LuceneAnalyzerIntegrationTest { + + private static final String SAMPLE_TEXT = "This is baeldung.com Lucene Analyzers test"; + private static final String FIELD_NAME = "sampleName"; + + @Test + public void whenUseStandardAnalyzer_thenAnalyzed() throws IOException { + List result = analyze(SAMPLE_TEXT, new StandardAnalyzer()); + + assertThat(result, contains("baeldung.com", "lucene", "analyzers", "test")); + } + + @Test + public void whenUseStopAnalyzer_thenAnalyzed() throws IOException { + List result = analyze(SAMPLE_TEXT, new StopAnalyzer()); + + assertThat(result, contains("baeldung", "com", "lucene", "analyzers", "test")); + } + + @Test + public void whenUseSimpleAnalyzer_thenAnalyzed() throws IOException { + List result = analyze(SAMPLE_TEXT, new SimpleAnalyzer()); + + assertThat(result, contains("this", "is", "baeldung", "com", "lucene", "analyzers", "test")); + } + + @Test + public void whenUseWhiteSpaceAnalyzer_thenAnalyzed() throws IOException { + List result = analyze(SAMPLE_TEXT, new WhitespaceAnalyzer()); + + assertThat(result, contains("This", "is", "baeldung.com", "Lucene", "Analyzers", "test")); + } + + @Test + public void whenUseKeywordAnalyzer_thenAnalyzed() throws IOException { + List result = analyze(SAMPLE_TEXT, new KeywordAnalyzer()); + + assertThat(result, contains("This is baeldung.com Lucene Analyzers test")); + } + + @Test + public void whenUseEnglishAnalyzer_thenAnalyzed() throws IOException { + List result = analyze(SAMPLE_TEXT, new EnglishAnalyzer()); + + assertThat(result, contains("baeldung.com", "lucen", "analyz", "test")); + } + + @Test + public void whenUseCustomAnalyzerBuilder_thenAnalyzed() throws IOException { + Analyzer analyzer = CustomAnalyzer.builder() + .withTokenizer("standard") + .addTokenFilter("lowercase") + .addTokenFilter("stop") + .addTokenFilter("porterstem") + .addTokenFilter("capitalization") + .build(); + List result = analyze(SAMPLE_TEXT, analyzer); + + assertThat(result, contains("Baeldung.com", "Lucen", "Analyz", "Test")); + } + + @Test + public void whenUseCustomAnalyzer_thenAnalyzed() throws IOException { + List result = analyze(SAMPLE_TEXT, new MyCustomAnalyzer()); + + assertThat(result, contains("Baeldung.com", "Lucen", "Analyz", "Test")); + } + + // ================= usage example + + @Test + public void givenTermQuery_whenUseCustomAnalyzer_thenCorrect() { + InMemoryLuceneIndex luceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new MyCustomAnalyzer()); + luceneIndex.indexDocument("introduction", "introduction to lucene"); + luceneIndex.indexDocument("analyzers", "guide to lucene analyzers"); + Query query = new TermQuery(new Term("body", "Introduct")); + + List documents = luceneIndex.searchIndex(query); + assertEquals(1, documents.size()); + } + + @Test + public void givenTermQuery_whenUsePerFieldAnalyzerWrapper_thenCorrect() { + Map analyzerMap = new HashMap<>(); + analyzerMap.put("title", new MyCustomAnalyzer()); + analyzerMap.put("body", new EnglishAnalyzer()); + + PerFieldAnalyzerWrapper wrapper = + new PerFieldAnalyzerWrapper(new StandardAnalyzer(), analyzerMap); + InMemoryLuceneIndex luceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), wrapper); + luceneIndex.indexDocument("introduction", "introduction to lucene"); + luceneIndex.indexDocument("analyzers", "guide to lucene analyzers"); + + Query query = new TermQuery(new Term("body", "introduct")); + List documents = luceneIndex.searchIndex(query); + assertEquals(1, documents.size()); + + query = new TermQuery(new Term("title", "Introduct")); + + documents = luceneIndex.searchIndex(query); + assertEquals(1, documents.size()); + } + + // =================================================================== + + public List analyze(String text, Analyzer analyzer) throws IOException { + List result = new ArrayList(); + TokenStream tokenStream = analyzer.tokenStream(FIELD_NAME, text); + CharTermAttribute attr = tokenStream.addAttribute(CharTermAttribute.class); + tokenStream.reset(); + while (tokenStream.incrementToken()) { + result.add(attr.toString()); + } + return result; + } + +} diff --git a/lucene/src/test/java/com/baeldung/lucene/LuceneFileSearchIntegrationTest.java b/lucene/src/test/java/com/baeldung/lucene/LuceneFileSearchIntegrationTest.java new file mode 100644 index 0000000000..7d9bfb9cf5 --- /dev/null +++ b/lucene/src/test/java/com/baeldung/lucene/LuceneFileSearchIntegrationTest.java @@ -0,0 +1,32 @@ +package com.baeldung.lucene; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Paths; +import java.util.List; + +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.document.Document; +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.FSDirectory; +import org.junit.Assert; +import org.junit.Test; + +public class LuceneFileSearchIntegrationTest { + + @Test + public void givenSearchQueryWhenFetchedFileNamehenCorrect() throws IOException, URISyntaxException { + String indexPath = "index"; + String dataPath = "data/file1.txt"; + + Directory directory = FSDirectory.open(Paths.get(indexPath)); + LuceneFileSearch luceneFileSearch = new LuceneFileSearch(directory, new StandardAnalyzer()); + + luceneFileSearch.addFileToIndex(dataPath); + + List docs = luceneFileSearch.searchFiles("contents", "consectetur"); + + Assert.assertEquals("file1.txt", docs.get(0).get("filename")); + } + +} \ No newline at end of file diff --git a/lucene/src/test/java/com/baeldung/lucene/LuceneFileSearchTest.java b/lucene/src/test/java/com/baeldung/lucene/LuceneFileSearchTest.java deleted file mode 100644 index 4345057ff7..0000000000 --- a/lucene/src/test/java/com/baeldung/lucene/LuceneFileSearchTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.lucene; - -import java.io.IOException; -import java.net.URISyntaxException; -import java.nio.file.Paths; -import java.util.List; - -import org.apache.lucene.analysis.standard.StandardAnalyzer; -import org.apache.lucene.document.Document; -import org.apache.lucene.store.Directory; -import org.apache.lucene.store.FSDirectory; -import org.junit.Assert; -import org.junit.Test; - -public class LuceneFileSearchTest { - - @Test - public void givenSearchQueryWhenFetchedFileNamehenCorrect() throws IOException, URISyntaxException { - String indexPath = "index"; - String dataPath = "data/file1.txt"; - - Directory directory = FSDirectory.open(Paths.get(indexPath)); - LuceneFileSearch luceneFileSearch = new LuceneFileSearch(directory, new StandardAnalyzer()); - - luceneFileSearch.addFileToIndex(dataPath); - - List docs = luceneFileSearch.searchFiles("contents", "consectetur"); - - Assert.assertEquals("file1.txt", docs.get(0).get("filename")); - } - -} \ No newline at end of file diff --git a/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchIntegrationTest.java b/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchIntegrationTest.java new file mode 100644 index 0000000000..27893762fd --- /dev/null +++ b/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchIntegrationTest.java @@ -0,0 +1,152 @@ +package com.baeldung.lucene; + +import java.util.List; + +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.document.Document; +import org.apache.lucene.index.Term; +import org.apache.lucene.search.BooleanClause; +import org.apache.lucene.search.BooleanQuery; +import org.apache.lucene.search.FuzzyQuery; +import org.apache.lucene.search.PhraseQuery; +import org.apache.lucene.search.PrefixQuery; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.Sort; +import org.apache.lucene.search.SortField; +import org.apache.lucene.search.TermQuery; +import org.apache.lucene.search.WildcardQuery; +import org.apache.lucene.store.RAMDirectory; +import org.apache.lucene.util.BytesRef; +import org.junit.Assert; +import org.junit.Test; + +public class LuceneInMemorySearchIntegrationTest { + + @Test + public void givenSearchQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("Hello world", "Some hello world "); + + List documents = inMemoryLuceneIndex.searchIndex("body", "world"); + + Assert.assertEquals("Hello world", documents.get(0).get("title")); + } + + @Test + public void givenTermQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("activity", "running in track"); + inMemoryLuceneIndex.indexDocument("activity", "Cars are running on road"); + + Term term = new Term("body", "running"); + Query query = new TermQuery(term); + + List documents = inMemoryLuceneIndex.searchIndex(query); + Assert.assertEquals(2, documents.size()); + } + + @Test + public void givenPrefixQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("article", "Lucene introduction"); + inMemoryLuceneIndex.indexDocument("article", "Introduction to Lucene"); + + Term term = new Term("body", "intro"); + Query query = new PrefixQuery(term); + + List documents = inMemoryLuceneIndex.searchIndex(query); + Assert.assertEquals(2, documents.size()); + } + + @Test + public void givenBooleanQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("Destination", "Las Vegas singapore car"); + inMemoryLuceneIndex.indexDocument("Commutes in singapore", "Bus Car Bikes"); + + Term term1 = new Term("body", "singapore"); + Term term2 = new Term("body", "car"); + + TermQuery query1 = new TermQuery(term1); + TermQuery query2 = new TermQuery(term2); + + BooleanQuery booleanQuery = new BooleanQuery.Builder().add(query1, BooleanClause.Occur.MUST) + .add(query2, BooleanClause.Occur.MUST).build(); + + List documents = inMemoryLuceneIndex.searchIndex(booleanQuery); + Assert.assertEquals(1, documents.size()); + } + + @Test + public void givenPhraseQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("quotes", "A rose by any other name would smell as sweet."); + + Query query = new PhraseQuery(1, "body", new BytesRef("smell"), new BytesRef("sweet")); + List documents = inMemoryLuceneIndex.searchIndex(query); + + Assert.assertEquals(1, documents.size()); + } + + @Test + public void givenFuzzyQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("article", "Halloween Festival"); + inMemoryLuceneIndex.indexDocument("decoration", "Decorations for Halloween"); + + Term term = new Term("body", "hallowen"); + Query query = new FuzzyQuery(term); + + List documents = inMemoryLuceneIndex.searchIndex(query); + Assert.assertEquals(2, documents.size()); + } + + @Test + public void givenWildCardQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("article", "Lucene introduction"); + inMemoryLuceneIndex.indexDocument("article", "Introducing Lucene with Spring"); + + Term term = new Term("body", "intro*"); + Query query = new WildcardQuery(term); + + List documents = inMemoryLuceneIndex.searchIndex(query); + Assert.assertEquals(2, documents.size()); + } + + @Test + public void givenSortFieldWhenSortedThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("Ganges", "River in India"); + inMemoryLuceneIndex.indexDocument("Mekong", "This river flows in south Asia"); + inMemoryLuceneIndex.indexDocument("Amazon", "Rain forest river"); + inMemoryLuceneIndex.indexDocument("Rhine", "Belongs to Europe"); + inMemoryLuceneIndex.indexDocument("Nile", "Longest River"); + + Term term = new Term("body", "river"); + Query query = new WildcardQuery(term); + + SortField sortField = new SortField("title", SortField.Type.STRING_VAL, false); + Sort sortByTitle = new Sort(sortField); + + List documents = inMemoryLuceneIndex.searchIndex(query, sortByTitle); + Assert.assertEquals(4, documents.size()); + Assert.assertEquals("Amazon", documents.get(0).getField("title").stringValue()); + } + + @Test + public void whenDocumentDeletedThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("Ganges", "River in India"); + inMemoryLuceneIndex.indexDocument("Mekong", "This river flows in south Asia"); + + Term term = new Term("title", "ganges"); + inMemoryLuceneIndex.deleteDocument(term); + + Query query = new TermQuery(term); + + List documents = inMemoryLuceneIndex.searchIndex(query); + Assert.assertEquals(0, documents.size()); + } + +} \ No newline at end of file diff --git a/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchTest.java b/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchTest.java deleted file mode 100644 index acf688cb99..0000000000 --- a/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchTest.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.baeldung.lucene; - -import java.util.List; - -import org.apache.lucene.analysis.standard.StandardAnalyzer; -import org.apache.lucene.document.Document; -import org.apache.lucene.index.Term; -import org.apache.lucene.search.BooleanClause; -import org.apache.lucene.search.BooleanQuery; -import org.apache.lucene.search.FuzzyQuery; -import org.apache.lucene.search.PhraseQuery; -import org.apache.lucene.search.PrefixQuery; -import org.apache.lucene.search.Query; -import org.apache.lucene.search.Sort; -import org.apache.lucene.search.SortField; -import org.apache.lucene.search.TermQuery; -import org.apache.lucene.search.WildcardQuery; -import org.apache.lucene.store.RAMDirectory; -import org.apache.lucene.util.BytesRef; -import org.junit.Assert; -import org.junit.Test; - -public class LuceneInMemorySearchTest { - - @Test - public void givenSearchQueryWhenFetchedDocumentThenCorrect() { - InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); - inMemoryLuceneIndex.indexDocument("Hello world", "Some hello world "); - - List documents = inMemoryLuceneIndex.searchIndex("body", "world"); - - Assert.assertEquals("Hello world", documents.get(0).get("title")); - } - - @Test - public void givenTermQueryWhenFetchedDocumentThenCorrect() { - InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); - inMemoryLuceneIndex.indexDocument("activity", "running in track"); - inMemoryLuceneIndex.indexDocument("activity", "Cars are running on road"); - - Term term = new Term("body", "running"); - Query query = new TermQuery(term); - - List documents = inMemoryLuceneIndex.searchIndex(query); - Assert.assertEquals(2, documents.size()); - } - - @Test - public void givenPrefixQueryWhenFetchedDocumentThenCorrect() { - InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); - inMemoryLuceneIndex.indexDocument("article", "Lucene introduction"); - inMemoryLuceneIndex.indexDocument("article", "Introduction to Lucene"); - - Term term = new Term("body", "intro"); - Query query = new PrefixQuery(term); - - List documents = inMemoryLuceneIndex.searchIndex(query); - Assert.assertEquals(2, documents.size()); - } - - @Test - public void givenBooleanQueryWhenFetchedDocumentThenCorrect() { - InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); - inMemoryLuceneIndex.indexDocument("Destination", "Las Vegas singapore car"); - inMemoryLuceneIndex.indexDocument("Commutes in singapore", "Bus Car Bikes"); - - Term term1 = new Term("body", "singapore"); - Term term2 = new Term("body", "car"); - - TermQuery query1 = new TermQuery(term1); - TermQuery query2 = new TermQuery(term2); - - BooleanQuery booleanQuery = new BooleanQuery.Builder().add(query1, BooleanClause.Occur.MUST) - .add(query2, BooleanClause.Occur.MUST).build(); - - List documents = inMemoryLuceneIndex.searchIndex(booleanQuery); - Assert.assertEquals(1, documents.size()); - } - - @Test - public void givenPhraseQueryWhenFetchedDocumentThenCorrect() { - InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); - inMemoryLuceneIndex.indexDocument("quotes", "A rose by any other name would smell as sweet."); - - Query query = new PhraseQuery(1, "body", new BytesRef("smell"), new BytesRef("sweet")); - List documents = inMemoryLuceneIndex.searchIndex(query); - - Assert.assertEquals(1, documents.size()); - } - - @Test - public void givenFuzzyQueryWhenFetchedDocumentThenCorrect() { - InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); - inMemoryLuceneIndex.indexDocument("article", "Halloween Festival"); - inMemoryLuceneIndex.indexDocument("decoration", "Decorations for Halloween"); - - Term term = new Term("body", "hallowen"); - Query query = new FuzzyQuery(term); - - List documents = inMemoryLuceneIndex.searchIndex(query); - Assert.assertEquals(2, documents.size()); - } - - @Test - public void givenWildCardQueryWhenFetchedDocumentThenCorrect() { - InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); - inMemoryLuceneIndex.indexDocument("article", "Lucene introduction"); - inMemoryLuceneIndex.indexDocument("article", "Introducing Lucene with Spring"); - - Term term = new Term("body", "intro*"); - Query query = new WildcardQuery(term); - - List documents = inMemoryLuceneIndex.searchIndex(query); - Assert.assertEquals(2, documents.size()); - } - - @Test - public void givenSortFieldWhenSortedThenCorrect() { - InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); - inMemoryLuceneIndex.indexDocument("Ganges", "River in India"); - inMemoryLuceneIndex.indexDocument("Mekong", "This river flows in south Asia"); - inMemoryLuceneIndex.indexDocument("Amazon", "Rain forest river"); - inMemoryLuceneIndex.indexDocument("Rhine", "Belongs to Europe"); - inMemoryLuceneIndex.indexDocument("Nile", "Longest River"); - - Term term = new Term("body", "river"); - Query query = new WildcardQuery(term); - - SortField sortField = new SortField("title", SortField.Type.STRING_VAL, false); - Sort sortByTitle = new Sort(sortField); - - List documents = inMemoryLuceneIndex.searchIndex(query, sortByTitle); - Assert.assertEquals(4, documents.size()); - Assert.assertEquals("Amazon", documents.get(0).getField("title").stringValue()); - } - - @Test - public void whenDocumentDeletedThenCorrect() { - InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); - inMemoryLuceneIndex.indexDocument("Ganges", "River in India"); - inMemoryLuceneIndex.indexDocument("Mekong", "This river flows in south Asia"); - - Term term = new Term("title", "ganges"); - inMemoryLuceneIndex.deleteDocument(term); - - Query query = new TermQuery(term); - - List documents = inMemoryLuceneIndex.searchIndex(query); - Assert.assertEquals(0, documents.size()); - } - -} \ No newline at end of file diff --git a/mapstruct/pom.xml b/mapstruct/pom.xml index be105b8aa8..6c274dfcf2 100644 --- a/mapstruct/pom.xml +++ b/mapstruct/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 mapstruct mapstruct diff --git a/mapstruct/src/main/resources/logback.xml b/mapstruct/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/mapstruct/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/maven-archetype/README.md b/maven-archetype/README.md new file mode 100644 index 0000000000..71821e3348 --- /dev/null +++ b/maven-archetype/README.md @@ -0,0 +1,4 @@ +### Relevant Articles: +================================ + +- [Guide to Maven Archetype](http://www.baeldung.com/maven-archetype) diff --git a/maven-archetype/pom.xml b/maven-archetype/pom.xml new file mode 100644 index 0000000000..f7871c81ea --- /dev/null +++ b/maven-archetype/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + com.baeldung.archetypes + maven-archetype + 1.0-SNAPSHOT + maven-archetype + Archetype used to generate rest application based on jaxrs 2.1 + + + + + org.apache.maven.archetype + archetype-packaging + ${archetype-packaging.version} + + + + + + + 1.8 + 1.8 + 3.0.1 + + + diff --git a/maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml b/maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml new file mode 100644 index 0000000000..85e1b92d12 --- /dev/null +++ b/maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml @@ -0,0 +1,35 @@ + + + + + resources + + + Hi, I was generated from an archetype! + + + 2.4.2 + + + + + + src/main/java + + **/*.java + + + + src/main/liberty/config + + server.xml + + + + + diff --git a/maven-archetype/src/main/resources/archetype-resources/pom.xml b/maven-archetype/src/main/resources/archetype-resources/pom.xml new file mode 100644 index 0000000000..eb69f64626 --- /dev/null +++ b/maven-archetype/src/main/resources/archetype-resources/pom.xml @@ -0,0 +1,82 @@ + + 4.0.0 + + ${groupId} + ${artifactId} + ${version} + war + + + UTF-8 + 1.8 + 1.8 + false + ${liberty-plugin-version} + 9080 + 9443 + + + + ${artifactId} + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + ${liberty-maven-plugin.version} + + + + https://public.dhe.ibm.com/ibmdl/export/pub/software/openliberty/runtime/nightly/2018-06-18_1442/openliberty-all-20180618-1300.zip + + + true + project + src/main/liberty/config/server.xml + true + + ${defaultHttpPort} + ${defaultHttpsPort} + + + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + + + + + + javax.enterprise + cdi-api + 2.0 + provided + + + + javax.ws.rs + javax.ws.rs-api + 2.1 + provided + + + + + diff --git a/maven-archetype/src/main/resources/archetype-resources/src/main/java/AppConfig.java b/maven-archetype/src/main/resources/archetype-resources/src/main/java/AppConfig.java new file mode 100644 index 0000000000..7e17ab6aac --- /dev/null +++ b/maven-archetype/src/main/resources/archetype-resources/src/main/java/AppConfig.java @@ -0,0 +1,8 @@ +package ${package}; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("${app-path}") +public class AppConfig extends Application { +} diff --git a/maven-archetype/src/main/resources/archetype-resources/src/main/java/PingResource.java b/maven-archetype/src/main/resources/archetype-resources/src/main/java/PingResource.java new file mode 100644 index 0000000000..a2f34a7ac3 --- /dev/null +++ b/maven-archetype/src/main/resources/archetype-resources/src/main/java/PingResource.java @@ -0,0 +1,18 @@ +package ${package}; + +import javax.enterprise.context.RequestScoped; +import javax.inject.Inject; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; + +@Path("ping") +public class PingResource { + + @GET + public Response get() { + return Response.ok("${greeting-msg}").build(); + } + +} \ No newline at end of file diff --git a/maven-archetype/src/main/resources/archetype-resources/src/main/liberty/config/server.xml b/maven-archetype/src/main/resources/archetype-resources/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..c316868b4f --- /dev/null +++ b/maven-archetype/src/main/resources/archetype-resources/src/main/liberty/config/server.xml @@ -0,0 +1,8 @@ + + + cdi-2.0 + jaxrs-2.1 + + + \ No newline at end of file diff --git a/maven-archetype/src/main/resources/logback.xml b/maven-archetype/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/maven-archetype/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/maven/README.md b/maven/README.md index 7c3779143a..2d838bcb76 100644 --- a/maven/README.md +++ b/maven/README.md @@ -7,3 +7,6 @@ - [The Maven Failsafe Plugin](http://www.baeldung.com/maven-failsafe-plugin) - [The Maven Verifier Plugin](http://www.baeldung.com/maven-verifier-plugin) - [The Maven Clean Plugin](http://www.baeldung.com/maven-clean-plugin) +- [Build a Jar with Maven and Ignore the Test Results](http://www.baeldung.com/maven-ignore-test-results) +- [Maven Project with Multiple Source Directories](https://www.baeldung.com/maven-project-multiple-src-directories) +- [Integration Testing with Maven](https://www.baeldung.com/maven-integration-test) diff --git a/maven/pom.xml b/maven/pom.xml index fb7233e7e9..4bec533226 100644 --- a/maven/pom.xml +++ b/maven/pom.xml @@ -4,14 +4,19 @@ com.baeldung maven 0.0.1-SNAPSHOT - - - parent-modules - com.baeldung - 1.0.0-SNAPSHOT - + war + + org.glassfish.jersey.containers + jersey-container-servlet-core + ${jersey.version} + + + org.glassfish.jersey.inject + jersey-hk2 + ${jersey.version} + junit junit @@ -22,6 +27,34 @@ + + org.eclipse.jetty + jetty-maven-plugin + ${jetty.version} + + + 8999 + + quit + 9000 + + + + start-jetty + pre-integration-test + + start + + + + stop-jetty + post-integration-test + + stop + + + + maven-resources-plugin ${maven.resources.version} @@ -42,8 +75,8 @@ maven-compiler-plugin ${maven.compiler.version} - ${maven.compiler.source} - ${maven.compiler.target} + ${java.version} + ${java.version} -Xlint:unchecked @@ -55,10 +88,14 @@ DataTest.java + **/*IntegrationTest + com.baeldung.maven.it.Integration + TestFail.java DataCheck.java + true @@ -101,19 +138,166 @@ + + org.codehaus.mojo + build-helper-maven-plugin + ${maven.build.helper.version} + + + generate-sources + + add-source + + + + src/main/another-src + + + + + add-integration-test-source + generate-test-sources + + add-test-source + + + + src/integration-test/java + + + + + add-integration-test-resource + generate-test-resources + + add-test-resource + + + + + src/integration-test/resources + + + + + + + + + default + + + + maven-surefire-plugin + ${maven.surefire.version} + + + DataTest.java + + + TestFail.java + DataCheck.java + + true + + + + + + + failsafe + + + + maven-failsafe-plugin + ${maven.failsafe.version} + + + **/*RestIT + **/RestITCase + + + + + + integration-test + verify + + + + + + + + + surefire + + + + maven-surefire-plugin + ${maven.surefire.version} + + + integration-test + + test + + + + none + + + **/*IntegrationTest + + + + + + + + + + category + + + + maven-failsafe-plugin + ${maven.failsafe.version} + + + **/* + + com.baeldung.maven.it.Integration + + + + + integration-test + verify + + + + + + + + + + 1.8 3.0.2 - 3.7.0 - 2.21.0 - 2.21.0 + 3.8.0 + 2.22.0 + 2.22.0 1.1 3.0.0 + 3.0.0 Baeldung - 1.8 - 1.8 + 9.4.11.v20180605 + 2.27 + 4.12 - \ No newline at end of file diff --git a/maven/src/integration-test/java/com/baeldung/maven/it/RestITCase.java b/maven/src/integration-test/java/com/baeldung/maven/it/RestITCase.java new file mode 100644 index 0000000000..aaeeedb661 --- /dev/null +++ b/maven/src/integration-test/java/com/baeldung/maven/it/RestITCase.java @@ -0,0 +1,24 @@ +package com.baeldung.maven.it; + +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; +import java.util.Scanner; + +import static org.junit.Assert.assertEquals; + +public class RestITCase { + @Test + public void whenSendingGet_thenMessageIsReturned() throws IOException { + String url = "http://localhost:8999"; + URLConnection connection = new URL(url).openConnection(); + try (InputStream response = connection.getInputStream(); + Scanner scanner = new Scanner(response)) { + String responseBody = scanner.nextLine(); + assertEquals("Welcome to Baeldung!", responseBody); + } + } +} diff --git a/maven/src/main/another-src/com/baeldung/maven/plugins/Foo.java b/maven/src/main/another-src/com/baeldung/maven/plugins/Foo.java new file mode 100644 index 0000000000..f8a6fe9853 --- /dev/null +++ b/maven/src/main/another-src/com/baeldung/maven/plugins/Foo.java @@ -0,0 +1,10 @@ +package com.baeldung.maven.plugins; + +public class Foo { + + public static String foo() { + return "foo"; + } + +} + diff --git a/maven/src/main/java/com/baeldung/maven/it/EndpointConfig.java b/maven/src/main/java/com/baeldung/maven/it/EndpointConfig.java new file mode 100644 index 0000000000..919210ccff --- /dev/null +++ b/maven/src/main/java/com/baeldung/maven/it/EndpointConfig.java @@ -0,0 +1,9 @@ +package com.baeldung.maven.it; + +import org.glassfish.jersey.server.ResourceConfig; + +public class EndpointConfig extends ResourceConfig { + public EndpointConfig() { + register(RestEndpoint.class); + } +} diff --git a/maven/src/main/java/com/baeldung/maven/it/RestEndpoint.java b/maven/src/main/java/com/baeldung/maven/it/RestEndpoint.java new file mode 100644 index 0000000000..c234891865 --- /dev/null +++ b/maven/src/main/java/com/baeldung/maven/it/RestEndpoint.java @@ -0,0 +1,12 @@ +package com.baeldung.maven.it; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; + +@Path("/") +public class RestEndpoint { + @GET + public String hello() { + return "Welcome to Baeldung!"; + } +} diff --git a/maven/src/main/java/com/baeldung/maven/plugins/MultipleSrcFolders.java b/maven/src/main/java/com/baeldung/maven/plugins/MultipleSrcFolders.java new file mode 100644 index 0000000000..d403918dd3 --- /dev/null +++ b/maven/src/main/java/com/baeldung/maven/plugins/MultipleSrcFolders.java @@ -0,0 +1,9 @@ +package com.baeldung.maven.plugins; + +public class MultipleSrcFolders { + + public static void callFoo() { + Foo.foo(); + } + +} diff --git a/maven/src/main/resources/logback.xml b/maven/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/maven/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/maven/src/main/webapp/WEB-INF/web.xml b/maven/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..1751ad17a5 --- /dev/null +++ b/maven/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,17 @@ + + + rest-servlet + org.glassfish.jersey.servlet.ServletContainer + + javax.ws.rs.Application + com.baeldung.maven.it.EndpointConfig + + + + rest-servlet + /* + + \ No newline at end of file diff --git a/maven/src/test/java/com/baeldung/maven/it/Integration.java b/maven/src/test/java/com/baeldung/maven/it/Integration.java new file mode 100644 index 0000000000..112ce178ce --- /dev/null +++ b/maven/src/test/java/com/baeldung/maven/it/Integration.java @@ -0,0 +1,4 @@ +package com.baeldung.maven.it; + +public interface Integration { +} diff --git a/maven/src/test/java/com/baeldung/maven/it/RestIT.java b/maven/src/test/java/com/baeldung/maven/it/RestIT.java new file mode 100644 index 0000000000..0115d34f1e --- /dev/null +++ b/maven/src/test/java/com/baeldung/maven/it/RestIT.java @@ -0,0 +1,24 @@ +package com.baeldung.maven.it; + +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; +import java.util.Scanner; + +import static org.junit.Assert.assertEquals; + +public class RestIT { + @Test + public void whenSendingGet_thenMessageIsReturned() throws IOException { + String url = "http://localhost:8999"; + URLConnection connection = new URL(url).openConnection(); + try (InputStream response = connection.getInputStream(); + Scanner scanner = new Scanner(response)) { + String responseBody = scanner.nextLine(); + assertEquals("Welcome to Baeldung!", responseBody); + } + } +} diff --git a/maven/src/test/java/com/baeldung/maven/it/RestIntegrationTest.java b/maven/src/test/java/com/baeldung/maven/it/RestIntegrationTest.java new file mode 100644 index 0000000000..2f913c8429 --- /dev/null +++ b/maven/src/test/java/com/baeldung/maven/it/RestIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.maven.it; + +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; +import java.util.Scanner; + +import static org.junit.Assert.assertEquals; + +public class RestIntegrationTest { + @Test + public void whenSendingGet_thenMessageIsReturned() throws IOException { + String url = "http://localhost:8999"; + URLConnection connection = new URL(url).openConnection(); + try (InputStream response = connection.getInputStream(); + Scanner scanner = new Scanner(response)) { + String responseBody = scanner.nextLine(); + assertEquals("Welcome to Baeldung!", responseBody); + } + } +} diff --git a/maven/src/test/java/com/baeldung/maven/it/RestJUnitTest.java b/maven/src/test/java/com/baeldung/maven/it/RestJUnitTest.java new file mode 100644 index 0000000000..60995d75bd --- /dev/null +++ b/maven/src/test/java/com/baeldung/maven/it/RestJUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.maven.it; + +import org.junit.Test; +import org.junit.experimental.categories.Category; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; +import java.util.Scanner; + +import static org.junit.Assert.assertEquals; + +@Category(Integration.class) +public class RestJUnitTest { + @Test + public void whenSendingGet_thenMessageIsReturned() throws IOException { + String url = "http://localhost:8999"; + URLConnection connection = new URL(url).openConnection(); + try (InputStream response = connection.getInputStream(); + Scanner scanner = new Scanner(response)) { + String responseBody = scanner.nextLine(); + assertEquals("Welcome to Baeldung!", responseBody); + } + } +} diff --git a/maven/src/test/java/com/baeldung/maven/plugins/DataTest.java b/maven/src/test/java/com/baeldung/maven/plugins/DataTest.java deleted file mode 100644 index 3f03b6f5d6..0000000000 --- a/maven/src/test/java/com/baeldung/maven/plugins/DataTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.maven.plugins; - -import static org.junit.Assert.assertNull; - -import org.junit.Test; - -import com.baeldung.maven.plugins.Data; - -public class DataTest { - @Test - public void whenDataObjectIsNotCreated_thenItIsNull() { - Data data = null; - assertNull(data); - } -} diff --git a/maven/src/test/java/com/baeldung/maven/plugins/DataUnitTest.java b/maven/src/test/java/com/baeldung/maven/plugins/DataUnitTest.java new file mode 100644 index 0000000000..197f977fec --- /dev/null +++ b/maven/src/test/java/com/baeldung/maven/plugins/DataUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.maven.plugins; + +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +import com.baeldung.maven.plugins.Data; + +public class DataUnitTest { + @Test + public void whenDataObjectIsNotCreated_thenItIsNull() { + Data data = null; + assertNull(data); + } +} diff --git a/maven/src/test/java/testfail/TestFail.java b/maven/src/test/java/testfail/TestFail.java new file mode 100644 index 0000000000..3febd21031 --- /dev/null +++ b/maven/src/test/java/testfail/TestFail.java @@ -0,0 +1,18 @@ +package testfail; + +import org.junit.Test; +import org.junit.Ignore; + +import static org.junit.Assert.assertNotNull; + +public class TestFail { + + @Ignore //ignored so the entire tutorials build passes + @Test + public void whenMessageAssigned_thenItIsNotNull() { + String message = "hello there"; + message = null; + assertNotNull(message); + } + +} diff --git a/mesos-marathon/pom.xml b/mesos-marathon/pom.xml index 2b7a238ee8..f92c00892b 100644 --- a/mesos-marathon/pom.xml +++ b/mesos-marathon/pom.xml @@ -1,16 +1,16 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung mesos-marathon 0.0.1-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -25,7 +25,6 @@ org.springframework.boot spring-boot-maven-plugin - 1.5.1.RELEASE diff --git a/mesos-marathon/src/main/resources/logback.xml b/mesos-marathon/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/mesos-marathon/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/metrics/pom.xml b/metrics/pom.xml index e3868eddef..86f197240b 100644 --- a/metrics/pom.xml +++ b/metrics/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 metrics diff --git a/metrics/src/main/resources/logback.xml b/metrics/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/metrics/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasIntegrationTest.java b/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasIntegrationTest.java new file mode 100644 index 0000000000..e7f3d7ec72 --- /dev/null +++ b/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasIntegrationTest.java @@ -0,0 +1,288 @@ +package com.baeldung.metrics.micrometer; + +import static org.hamcrest.CoreMatchers.allOf; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.collection.IsMapContaining.hasEntry; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import io.micrometer.atlas.AtlasMeterRegistry; +import io.micrometer.core.instrument.Clock; +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.DistributionSummary; +import io.micrometer.core.instrument.Gauge; +import io.micrometer.core.instrument.LongTaskTimer; +import io.micrometer.core.instrument.Measurement; +import io.micrometer.core.instrument.Meter.Type; +import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.instrument.Metrics; +import io.micrometer.core.instrument.Tag; +import io.micrometer.core.instrument.Timer; +import io.micrometer.core.instrument.composite.CompositeMeterRegistry; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import io.micrometer.core.instrument.stats.hist.Histogram; +import io.micrometer.core.instrument.stats.quantile.WindowSketchQuantiles; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import org.junit.Before; +import org.junit.Test; + +import com.netflix.spectator.atlas.AtlasConfig; + +/** + * @author aiet + */ +public class MicrometerAtlasIntegrationTest { + + private AtlasConfig atlasConfig; + + @Before + public void init() { + atlasConfig = new AtlasConfig() { + + @Override + public Duration step() { + return Duration.ofSeconds(1); + } + + @Override + public String get(String k) { + return null; + } + }; + } + + @Test + public void givenCompositeRegistries_whenRecordMeter_thenAllRegistriesRecorded() { + CompositeMeterRegistry compositeRegistry = new CompositeMeterRegistry(); + + SimpleMeterRegistry oneSimpleMeter = new SimpleMeterRegistry(); + AtlasMeterRegistry atlasMeterRegistry = new AtlasMeterRegistry(atlasConfig, Clock.SYSTEM); + + compositeRegistry.add(oneSimpleMeter); + compositeRegistry.add(atlasMeterRegistry); + + compositeRegistry.gauge("baeldung.heat", 90); + + Optional oneGauge = oneSimpleMeter + .find("baeldung.heat") + .gauge(); + assertTrue(oneGauge.isPresent()); + Iterator measurements = oneGauge + .get() + .measure() + .iterator(); + + assertTrue(measurements.hasNext()); + assertThat(measurements + .next() + .getValue(), equalTo(90.00)); + + Optional atlasGauge = atlasMeterRegistry + .find("baeldung.heat") + .gauge(); + assertTrue(atlasGauge.isPresent()); + Iterator anotherMeasurements = atlasGauge + .get() + .measure() + .iterator(); + + assertTrue(anotherMeasurements.hasNext()); + assertThat(anotherMeasurements + .next() + .getValue(), equalTo(90.00)); + } + + @Test + public void givenGlobalRegistry_whenIncrementAnywhere_thenCounted() { + class CountedObject { + private CountedObject() { + Metrics + .counter("objects.instance") + .increment(1.0); + } + } + Metrics.addRegistry(new SimpleMeterRegistry()); + + Metrics + .counter("objects.instance") + .increment(); + new CountedObject(); + + Optional counterOptional = Metrics.globalRegistry + .find("objects.instance") + .counter(); + + assertTrue(counterOptional.isPresent()); + assertTrue(counterOptional + .get() + .count() == 2.0); + } + + @Test + public void givenCounter_whenIncrement_thenValueChanged() { + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + Counter counter = Counter + .builder("objects.instance") + .description("indicates instance count of the object") + .tags("dev", "performance") + .register(registry); + + counter.increment(2.0); + assertTrue(counter.count() == 2); + + counter.increment(-1); + assertTrue(counter.count() == 2); + } + + @Test + public void givenTimer_whenWrapTasks_thenTimeRecorded() { + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + Timer timer = registry.timer("app.event"); + timer.record(() -> { + try { + TimeUnit.MILLISECONDS.sleep(15); + } catch (InterruptedException ignored) { + } + }); + + timer.record(30, TimeUnit.MILLISECONDS); + + assertTrue(2 == timer.count()); + assertTrue(50 > timer.totalTime(TimeUnit.MILLISECONDS) && 45 <= timer.totalTime(TimeUnit.MILLISECONDS)); + } + + @Test + public void givenLongTimer_whenRunTasks_thenTimerRecorded() { + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + LongTaskTimer longTaskTimer = LongTaskTimer + .builder("3rdPartyService") + .register(registry); + + long currentTaskId = longTaskTimer.start(); + try { + TimeUnit.MILLISECONDS.sleep(2); + } catch (InterruptedException ignored) { + } + long timeElapsed = longTaskTimer.stop(currentTaskId); + + assertTrue(timeElapsed / (int) 1e6 == 2); + } + + @Test + public void givenGauge_whenMeterListSize_thenCurrentSizeMonitored() { + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + List list = new ArrayList<>(4); + Gauge gauge = Gauge + .builder("cache.size", list, List::size) + .register(registry); + + assertTrue(gauge.value() == 0.0); + + list.add("1"); + assertTrue(gauge.value() == 1.0); + } + + @Test + public void givenDistributionSummary_whenRecord_thenSummarized() { + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + DistributionSummary distributionSummary = DistributionSummary + .builder("request.size") + .baseUnit("bytes") + .register(registry); + distributionSummary.record(3); + distributionSummary.record(4); + distributionSummary.record(5); + + assertTrue(3 == distributionSummary.count()); + assertTrue(12 == distributionSummary.totalAmount()); + } + + @Test + public void givenTimer_whenEnrichWithQuantile_thenQuantilesComputed() { + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + Timer timer = Timer + .builder("test.timer") + .quantiles(WindowSketchQuantiles + .quantiles(0.3, 0.5, 0.95) + .create()) + .register(registry); + + timer.record(2, TimeUnit.SECONDS); + timer.record(2, TimeUnit.SECONDS); + timer.record(3, TimeUnit.SECONDS); + timer.record(4, TimeUnit.SECONDS); + timer.record(8, TimeUnit.SECONDS); + timer.record(13, TimeUnit.SECONDS); + + Map quantileMap = extractTagValueMap(registry, Type.Gauge, 1e9); + assertThat(quantileMap, allOf(hasEntry("quantile=0.3", 2), hasEntry("quantile=0.5", 3), hasEntry("quantile=0.95", 8))); + } + + private Map extractTagValueMap(MeterRegistry registry, Type meterType, double valueDivisor) { + return registry + .getMeters() + .stream() + .filter(meter -> meter.getType() == meterType) + .collect(Collectors.toMap(meter -> { + Tag tag = meter + .getId() + .getTags() + .iterator() + .next(); + return tag.getKey() + "=" + tag.getValue(); + }, meter -> (int) (meter + .measure() + .iterator() + .next() + .getValue() / valueDivisor))); + } + + @Test + public void givenDistributionSummary_whenEnrichWithHistograms_thenDataAggregated() { + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + DistributionSummary hist = DistributionSummary + .builder("summary") + .histogram(Histogram.linear(0, 10, 5)) + .register(registry); + + hist.record(3); + hist.record(8); + hist.record(20); + hist.record(40); + hist.record(13); + hist.record(26); + + Map histograms = extractTagValueMap(registry, Type.Counter, 1.0); + + assertThat(histograms, allOf(hasEntry("bucket=0.0", 0), hasEntry("bucket=10.0", 2), hasEntry("bucket=20.0", 2), hasEntry("bucket=30.0", 1), hasEntry("bucket=40.0", 1), hasEntry("bucket=Infinity", 0))); + } + + @Test + public void givenTimer_whenEnrichWithTimescaleHistogram_thenTimeScaleDataCollected() { + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + Timer timer = Timer + .builder("timer") + .histogram(Histogram.linearTime(TimeUnit.MILLISECONDS, 0, 200, 3)) + .register(registry); + + timer.record(1000, TimeUnit.MILLISECONDS); + timer.record(23, TimeUnit.MILLISECONDS); + timer.record(450, TimeUnit.MILLISECONDS); + timer.record(341, TimeUnit.MILLISECONDS); + timer.record(500, TimeUnit.MILLISECONDS); + + Map histograms = extractTagValueMap(registry, Type.Counter, 1.0); + + assertThat(histograms, allOf(hasEntry("bucket=0.0", 0), hasEntry("bucket=2.0E8", 1), hasEntry("bucket=4.0E8", 1), hasEntry("bucket=Infinity", 3))); + + } + +} diff --git a/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java b/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java deleted file mode 100644 index b76dc40ba0..0000000000 --- a/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java +++ /dev/null @@ -1,288 +0,0 @@ -package com.baeldung.metrics.micrometer; - -import static org.hamcrest.CoreMatchers.allOf; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.collection.IsMapContaining.hasEntry; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import io.micrometer.atlas.AtlasMeterRegistry; -import io.micrometer.core.instrument.Clock; -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.DistributionSummary; -import io.micrometer.core.instrument.Gauge; -import io.micrometer.core.instrument.LongTaskTimer; -import io.micrometer.core.instrument.Measurement; -import io.micrometer.core.instrument.Meter.Type; -import io.micrometer.core.instrument.MeterRegistry; -import io.micrometer.core.instrument.Metrics; -import io.micrometer.core.instrument.Tag; -import io.micrometer.core.instrument.Timer; -import io.micrometer.core.instrument.composite.CompositeMeterRegistry; -import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import io.micrometer.core.instrument.stats.hist.Histogram; -import io.micrometer.core.instrument.stats.quantile.WindowSketchQuantiles; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import org.junit.Before; -import org.junit.Test; - -import com.netflix.spectator.atlas.AtlasConfig; - -/** - * @author aiet - */ -public class MicrometerAtlasTest { - - private AtlasConfig atlasConfig; - - @Before - public void init() { - atlasConfig = new AtlasConfig() { - - @Override - public Duration step() { - return Duration.ofSeconds(1); - } - - @Override - public String get(String k) { - return null; - } - }; - } - - @Test - public void givenCompositeRegistries_whenRecordMeter_thenAllRegistriesRecorded() { - CompositeMeterRegistry compositeRegistry = new CompositeMeterRegistry(); - - SimpleMeterRegistry oneSimpleMeter = new SimpleMeterRegistry(); - AtlasMeterRegistry atlasMeterRegistry = new AtlasMeterRegistry(atlasConfig, Clock.SYSTEM); - - compositeRegistry.add(oneSimpleMeter); - compositeRegistry.add(atlasMeterRegistry); - - compositeRegistry.gauge("baeldung.heat", 90); - - Optional oneGauge = oneSimpleMeter - .find("baeldung.heat") - .gauge(); - assertTrue(oneGauge.isPresent()); - Iterator measurements = oneGauge - .get() - .measure() - .iterator(); - - assertTrue(measurements.hasNext()); - assertThat(measurements - .next() - .getValue(), equalTo(90.00)); - - Optional atlasGauge = atlasMeterRegistry - .find("baeldung.heat") - .gauge(); - assertTrue(atlasGauge.isPresent()); - Iterator anotherMeasurements = atlasGauge - .get() - .measure() - .iterator(); - - assertTrue(anotherMeasurements.hasNext()); - assertThat(anotherMeasurements - .next() - .getValue(), equalTo(90.00)); - } - - @Test - public void givenGlobalRegistry_whenIncrementAnywhere_thenCounted() { - class CountedObject { - private CountedObject() { - Metrics - .counter("objects.instance") - .increment(1.0); - } - } - Metrics.addRegistry(new SimpleMeterRegistry()); - - Metrics - .counter("objects.instance") - .increment(); - new CountedObject(); - - Optional counterOptional = Metrics.globalRegistry - .find("objects.instance") - .counter(); - - assertTrue(counterOptional.isPresent()); - assertTrue(counterOptional - .get() - .count() == 2.0); - } - - @Test - public void givenCounter_whenIncrement_thenValueChanged() { - SimpleMeterRegistry registry = new SimpleMeterRegistry(); - Counter counter = Counter - .builder("objects.instance") - .description("indicates instance count of the object") - .tags("dev", "performance") - .register(registry); - - counter.increment(2.0); - assertTrue(counter.count() == 2); - - counter.increment(-1); - assertTrue(counter.count() == 2); - } - - @Test - public void givenTimer_whenWrapTasks_thenTimeRecorded() { - SimpleMeterRegistry registry = new SimpleMeterRegistry(); - Timer timer = registry.timer("app.event"); - timer.record(() -> { - try { - TimeUnit.MILLISECONDS.sleep(15); - } catch (InterruptedException ignored) { - } - }); - - timer.record(30, TimeUnit.MILLISECONDS); - - assertTrue(2 == timer.count()); - assertTrue(50 > timer.totalTime(TimeUnit.MILLISECONDS) && 45 <= timer.totalTime(TimeUnit.MILLISECONDS)); - } - - @Test - public void givenLongTimer_whenRunTasks_thenTimerRecorded() { - SimpleMeterRegistry registry = new SimpleMeterRegistry(); - LongTaskTimer longTaskTimer = LongTaskTimer - .builder("3rdPartyService") - .register(registry); - - long currentTaskId = longTaskTimer.start(); - try { - TimeUnit.MILLISECONDS.sleep(2); - } catch (InterruptedException ignored) { - } - long timeElapsed = longTaskTimer.stop(currentTaskId); - - assertTrue(timeElapsed / (int) 1e6 == 2); - } - - @Test - public void givenGauge_whenMeterListSize_thenCurrentSizeMonitored() { - SimpleMeterRegistry registry = new SimpleMeterRegistry(); - List list = new ArrayList<>(4); - Gauge gauge = Gauge - .builder("cache.size", list, List::size) - .register(registry); - - assertTrue(gauge.value() == 0.0); - - list.add("1"); - assertTrue(gauge.value() == 1.0); - } - - @Test - public void givenDistributionSummary_whenRecord_thenSummarized() { - SimpleMeterRegistry registry = new SimpleMeterRegistry(); - DistributionSummary distributionSummary = DistributionSummary - .builder("request.size") - .baseUnit("bytes") - .register(registry); - distributionSummary.record(3); - distributionSummary.record(4); - distributionSummary.record(5); - - assertTrue(3 == distributionSummary.count()); - assertTrue(12 == distributionSummary.totalAmount()); - } - - @Test - public void givenTimer_whenEnrichWithQuantile_thenQuantilesComputed() { - SimpleMeterRegistry registry = new SimpleMeterRegistry(); - Timer timer = Timer - .builder("test.timer") - .quantiles(WindowSketchQuantiles - .quantiles(0.3, 0.5, 0.95) - .create()) - .register(registry); - - timer.record(2, TimeUnit.SECONDS); - timer.record(2, TimeUnit.SECONDS); - timer.record(3, TimeUnit.SECONDS); - timer.record(4, TimeUnit.SECONDS); - timer.record(8, TimeUnit.SECONDS); - timer.record(13, TimeUnit.SECONDS); - - Map quantileMap = extractTagValueMap(registry, Type.Gauge, 1e9); - assertThat(quantileMap, allOf(hasEntry("quantile=0.3", 2), hasEntry("quantile=0.5", 3), hasEntry("quantile=0.95", 8))); - } - - private Map extractTagValueMap(MeterRegistry registry, Type meterType, double valueDivisor) { - return registry - .getMeters() - .stream() - .filter(meter -> meter.getType() == meterType) - .collect(Collectors.toMap(meter -> { - Tag tag = meter - .getId() - .getTags() - .iterator() - .next(); - return tag.getKey() + "=" + tag.getValue(); - }, meter -> (int) (meter - .measure() - .iterator() - .next() - .getValue() / valueDivisor))); - } - - @Test - public void givenDistributionSummary_whenEnrichWithHistograms_thenDataAggregated() { - SimpleMeterRegistry registry = new SimpleMeterRegistry(); - DistributionSummary hist = DistributionSummary - .builder("summary") - .histogram(Histogram.linear(0, 10, 5)) - .register(registry); - - hist.record(3); - hist.record(8); - hist.record(20); - hist.record(40); - hist.record(13); - hist.record(26); - - Map histograms = extractTagValueMap(registry, Type.Counter, 1.0); - - assertThat(histograms, allOf(hasEntry("bucket=0.0", 0), hasEntry("bucket=10.0", 2), hasEntry("bucket=20.0", 2), hasEntry("bucket=30.0", 1), hasEntry("bucket=40.0", 1), hasEntry("bucket=Infinity", 0))); - } - - @Test - public void givenTimer_whenEnrichWithTimescaleHistogram_thenTimeScaleDataCollected() { - SimpleMeterRegistry registry = new SimpleMeterRegistry(); - Timer timer = Timer - .builder("timer") - .histogram(Histogram.linearTime(TimeUnit.MILLISECONDS, 0, 200, 3)) - .register(registry); - - timer.record(1000, TimeUnit.MILLISECONDS); - timer.record(23, TimeUnit.MILLISECONDS); - timer.record(450, TimeUnit.MILLISECONDS); - timer.record(341, TimeUnit.MILLISECONDS); - timer.record(500, TimeUnit.MILLISECONDS); - - Map histograms = extractTagValueMap(registry, Type.Counter, 1.0); - - assertThat(histograms, allOf(hasEntry("bucket=0.0", 0), hasEntry("bucket=2.0E8", 1), hasEntry("bucket=4.0E8", 1), hasEntry("bucket=Infinity", 3))); - - } - -} diff --git a/micronaut/.mvn/jvm.config b/micronaut/.mvn/jvm.config new file mode 100644 index 0000000000..4967c447ae --- /dev/null +++ b/micronaut/.mvn/jvm.config @@ -0,0 +1 @@ +-noverify -XX:TieredStopAtLevel=1 \ No newline at end of file diff --git a/micronaut/.mvn/wrapper/MavenWrapperDownloader.java b/micronaut/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000000..66a3132a52 --- /dev/null +++ b/micronaut/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,109 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. +*/ + +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = + "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.0/maven-wrapper-0.4.0.jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: : " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } +} diff --git a/micronaut/.mvn/wrapper/maven-wrapper.jar b/micronaut/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000000..08ebbb67f0 Binary files /dev/null and b/micronaut/.mvn/wrapper/maven-wrapper.jar differ diff --git a/micronaut/.mvn/wrapper/maven-wrapper.properties b/micronaut/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..42fa4da219 --- /dev/null +++ b/micronaut/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip \ No newline at end of file diff --git a/micronaut/Dockerfile b/micronaut/Dockerfile new file mode 100644 index 0000000000..ed4be82e8e --- /dev/null +++ b/micronaut/Dockerfile @@ -0,0 +1,4 @@ +FROM java:openjdk-8u111-alpine +RUN apk --no-cache add curl +COPY build/libs/*-all.jar hello-world-server.jar +CMD java ${JAVA_OPTS} -jar hello-world-server.jar \ No newline at end of file diff --git a/micronaut/README.md b/micronaut/README.md new file mode 100644 index 0000000000..10a68ff2f8 --- /dev/null +++ b/micronaut/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to Micronaut Framework](http://www.baeldung.com/micronaut) diff --git a/micronaut/micronaut-cli.yml b/micronaut/micronaut-cli.yml new file mode 100644 index 0000000000..fe56560074 --- /dev/null +++ b/micronaut/micronaut-cli.yml @@ -0,0 +1,5 @@ +profile: service +defaultPackage: hello.world.server +--- +testFramework: junit +sourceLanguage: java \ No newline at end of file diff --git a/micronaut/mvnw b/micronaut/mvnw new file mode 100755 index 0000000000..961a825001 --- /dev/null +++ b/micronaut/mvnw @@ -0,0 +1,286 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.0/maven-wrapper-0.4.0.jar" + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/micronaut/mvnw.cmd b/micronaut/mvnw.cmd new file mode 100755 index 0000000000..03d90e960b --- /dev/null +++ b/micronaut/mvnw.cmd @@ -0,0 +1,161 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.0/maven-wrapper-0.4.0.jar" +FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/micronaut/pom.xml b/micronaut/pom.xml new file mode 100644 index 0000000000..7b722306b6 --- /dev/null +++ b/micronaut/pom.xml @@ -0,0 +1,141 @@ + + 4.0.0 + com.baeldung.micronaut + micronaut + 0.1 + micronaut + + + com.baeldung.micronaut.helloworld.server.ServerApplication + 1.0.0.M2 + 9 + + + + jcenter.bintray.com + http://jcenter.bintray.com + + + + + + io.micronaut + bom + ${micronaut.version} + pom + import + + + + + + io.micronaut + http-client + compile + + + io.micronaut + http-server-netty + compile + + + io.micronaut + inject + compile + + + io.micronaut + runtime + compile + + + javax.annotation + javax.annotation-api + 1.3.2 + compile + + + io.micronaut + inject-java + provided + + + ch.qos.logback + logback-classic + 1.2.3 + runtime + + + junit + junit + 4.12 + test + + + io.projectreactor + reactor-core + 3.1.6.RELEASE + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.1.0 + + + package + + shade + + + + + ${exec.mainClass} + + + + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + java + + -classpath + + ${exec.mainClass} + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + ${jdk.version} + ${jdk.version} + + -parameters + + + + io.micronaut + inject-java + ${micronaut.version} + + + + + + + + diff --git a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java new file mode 100644 index 0000000000..d4051cef52 --- /dev/null +++ b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java @@ -0,0 +1,28 @@ +package com.baeldung.micronaut.helloworld.client; + +import io.micronaut.http.HttpRequest; +import io.micronaut.http.client.Client; +import io.micronaut.http.client.RxHttpClient; +import io.reactivex.Single; + +import javax.inject.Singleton; + +@Singleton +public class ConcreteGreetingClient +{ + private RxHttpClient httpClient; + + public ConcreteGreetingClient(@Client("/") RxHttpClient httpClient) { + this.httpClient = httpClient; + } + + public String greet(String name) { + HttpRequest req = HttpRequest.GET("/greet/" + name); + return httpClient.retrieve(req).blockingFirst(); + } + + public Single greetAsync(String name) { + HttpRequest req = HttpRequest.GET("/async/greet/" + name); + return httpClient.retrieve(req).first("An error as occurred"); + } +} diff --git a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java new file mode 100644 index 0000000000..8a691d5b06 --- /dev/null +++ b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java @@ -0,0 +1,14 @@ +package com.baeldung.micronaut.helloworld.client; + +import io.micronaut.http.annotation.Get; +import io.micronaut.http.client.Client; +import io.micronaut.http.client.RxHttpClient; + +import javax.inject.Inject; + +@Client("/greet") +public interface GreetingClient { + + @Get("/{name}") + String greet(String name); +} diff --git a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/ServerApplication.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/ServerApplication.java new file mode 100644 index 0000000000..c5936051dd --- /dev/null +++ b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/ServerApplication.java @@ -0,0 +1,10 @@ +package com.baeldung.micronaut.helloworld.server; + +import io.micronaut.runtime.Micronaut; + +public class ServerApplication { + + public static void main(String[] args) { + Micronaut.run(ServerApplication.class); + } +} \ No newline at end of file diff --git a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/controller/AsyncGreetController.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/controller/AsyncGreetController.java new file mode 100644 index 0000000000..4d86b9dfed --- /dev/null +++ b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/controller/AsyncGreetController.java @@ -0,0 +1,20 @@ +package com.baeldung.micronaut.helloworld.server.controller; + +import com.baeldung.micronaut.helloworld.server.service.GreetingService; +import io.micronaut.http.annotation.Controller; +import io.micronaut.http.annotation.Get; +import io.reactivex.Single; + +import javax.inject.Inject; + +@Controller("/async/greet") +public class AsyncGreetController { + + @Inject + private GreetingService greetingService; + + @Get("/{name}") + public Single greet(String name) { + return Single.just(greetingService.getGreeting() + name); + } +} diff --git a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/controller/GreetController.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/controller/GreetController.java new file mode 100644 index 0000000000..c890c037e4 --- /dev/null +++ b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/controller/GreetController.java @@ -0,0 +1,28 @@ +package com.baeldung.micronaut.helloworld.server.controller; + +import com.baeldung.micronaut.helloworld.server.service.GreetingService; +import io.micronaut.http.MediaType; +import io.micronaut.http.annotation.Body; +import io.micronaut.http.annotation.Controller; +import io.micronaut.http.annotation.Get; +import io.micronaut.http.annotation.Post; + +import javax.inject.Inject; + +@Controller("/greet") +public class GreetController { + + @Inject + private GreetingService greetingService; + + @Get("/{name}") + public String greet(String name) { + return greetingService.getGreeting() + name; + } + + @Post(value = "/{name}", consumes = MediaType.TEXT_PLAIN) + public String setGreeting(@Body String name) + { + return greetingService.getGreeting() + name; + } +} diff --git a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/service/EnglishGreetingService.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/service/EnglishGreetingService.java new file mode 100644 index 0000000000..8ea5172cf6 --- /dev/null +++ b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/service/EnglishGreetingService.java @@ -0,0 +1,14 @@ +package com.baeldung.micronaut.helloworld.server.service; + +import io.micronaut.context.annotation.Primary; + +import javax.inject.Singleton; + +@Primary +@Singleton +public class EnglishGreetingService implements GreetingService { + @Override + public String getGreeting() { + return "Hello "; + } +} diff --git a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/service/GreetingService.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/service/GreetingService.java new file mode 100644 index 0000000000..6e28baaebe --- /dev/null +++ b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/service/GreetingService.java @@ -0,0 +1,6 @@ +package com.baeldung.micronaut.helloworld.server.service; + +public interface GreetingService { + + String getGreeting(); +} diff --git a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/service/SpanishGreetingService.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/service/SpanishGreetingService.java new file mode 100644 index 0000000000..1ec53d8b2d --- /dev/null +++ b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/server/service/SpanishGreetingService.java @@ -0,0 +1,11 @@ +package com.baeldung.micronaut.helloworld.server.service; + +import javax.inject.Singleton; + +@Singleton +public class SpanishGreetingService implements GreetingService { + @Override + public String getGreeting() { + return "Hola "; + } +} diff --git a/micronaut/src/main/resources/application.yml b/micronaut/src/main/resources/application.yml new file mode 100644 index 0000000000..4119026dd6 --- /dev/null +++ b/micronaut/src/main/resources/application.yml @@ -0,0 +1,5 @@ +micronaut: + application: + name: hello-world-server + server: + port: 9080 \ No newline at end of file diff --git a/micronaut/src/main/resources/logback.xml b/micronaut/src/main/resources/logback.xml new file mode 100644 index 0000000000..afaebf8e17 --- /dev/null +++ b/micronaut/src/main/resources/logback.xml @@ -0,0 +1,14 @@ + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + \ No newline at end of file diff --git a/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClientTest.java b/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClientTest.java new file mode 100644 index 0000000000..c8c1d6b12a --- /dev/null +++ b/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClientTest.java @@ -0,0 +1,38 @@ +package com.baeldung.micronaut.helloworld.client; + +import io.micronaut.context.ApplicationContext; +import io.micronaut.runtime.server.EmbeddedServer; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static junit.framework.TestCase.assertEquals; + +public class ConcreteGreetingClientTest +{ + private EmbeddedServer server; + private ConcreteGreetingClient client; + + @Before + public void setup() + { + server = ApplicationContext.run(EmbeddedServer.class); + client = server.getApplicationContext().getBean(ConcreteGreetingClient.class); + } + + @After + public void cleanup() + { + server.stop(); + } + + @Test + public void testGreeting() { + assertEquals(client.greet("Mike"), "Hello Mike"); + } + + @Test + public void testGreetingAsync() { + assertEquals(client.greetAsync("Mike").blockingGet(), "Hello Mike"); + } +} diff --git a/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/GreetingClientTest.java b/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/GreetingClientTest.java new file mode 100644 index 0000000000..0f2ca460ac --- /dev/null +++ b/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/GreetingClientTest.java @@ -0,0 +1,32 @@ +package com.baeldung.micronaut.helloworld.client; + +import io.micronaut.context.ApplicationContext; +import io.micronaut.runtime.server.EmbeddedServer; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static junit.framework.TestCase.assertEquals; + +public class GreetingClientTest { + private EmbeddedServer server; + private GreetingClient client; + + @Before + public void setup() + { + server = ApplicationContext.run(EmbeddedServer.class); + client = server.getApplicationContext().getBean(GreetingClient.class); + } + + @After + public void cleanup() + { + server.stop(); + } + + @Test + public void testGreeting() { + assertEquals(client.greet("Mike"), "Hello Mike"); + } +} diff --git a/microprofile/pom.xml b/microprofile/pom.xml index 27d234b73a..d75b6443ed 100644 --- a/microprofile/pom.xml +++ b/microprofile/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.baeldung microprofile @@ -80,8 +79,6 @@ - UTF-8 - UTF-8 library ${project.build.directory}/${app.name}-service.jar runnable diff --git a/microprofile/src/main/resources/logback.xml b/microprofile/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/microprofile/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/msf4j/README.md b/msf4j/README.md new file mode 100644 index 0000000000..7c66b8dc5f --- /dev/null +++ b/msf4j/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Introduction to Java Microservices with MSF4J](http://www.baeldung.com/msf4j) diff --git a/msf4j/pom.xml b/msf4j/pom.xml new file mode 100644 index 0000000000..9a6483772b --- /dev/null +++ b/msf4j/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + com.baeldung.msf4j + msf4j + 0.0.1-SNAPSHOT + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + + org.wso2.msf4j + msf4j-service + ${msf4j.version} + pom + + + + + + org.wso2.msf4j + msf4j-spring + ${msf4j.version} + + + org.wso2.msf4j + msf4j-mustache-template + ${msf4j.version} + + + + + com.baeldung.msf4j.msf4jintro.Application + 2.6.3 + + + \ No newline at end of file diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Application.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Application.java new file mode 100644 index 0000000000..c4cf136536 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Application.java @@ -0,0 +1,11 @@ +package com.baeldung.msf4j.msf4japi; + +import org.wso2.msf4j.MicroservicesRunner; + +public class Application { + public static void main(String[] args) { + new MicroservicesRunner() + .deploy(new MenuService()) + .start(); + } +} \ No newline at end of file diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Meal.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Meal.java new file mode 100644 index 0000000000..d17a7a1034 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Meal.java @@ -0,0 +1,20 @@ +package com.baeldung.msf4j.msf4japi; + +public class Meal { + private String name; + private Float price; + + public Meal(String name, Float price) { + this.name = name; + this.price = price; + } + + public String getName() { + return name; + } + + public Float getPrice() { + return price; + } + +} diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/MenuService.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/MenuService.java new file mode 100644 index 0000000000..4f880a1393 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/MenuService.java @@ -0,0 +1,78 @@ +package com.baeldung.msf4j.msf4japi; + +import java.util.ArrayList; +import java.util.List; + +import javax.ws.rs.Consumes; +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.Response; + +import com.google.gson.Gson; + +@Path("/menu") +public class MenuService { + + private List meals = new ArrayList(); + + public MenuService() { + meals.add(new Meal("Java beans",42.0f)); + } + + @GET + @Path("/") + @Produces({ "application/json" }) + public Response index() { + return Response.ok() + .entity(meals) + .build(); + } + + @GET + @Path("/{id}") + @Produces({ "application/json" }) + public Response meal(@PathParam("id") int id) { + return Response.ok() + .entity(meals.get(id)) + .build(); + } + + + @POST + @Path("/") + @Consumes("application/json") + @Produces({ "application/json" }) + public Response create(Meal meal) { + meals.add(meal); + return Response.ok() + .entity(meal) + .build(); + } + + @PUT + @Path("/{id}") + @Consumes("application/json") + @Produces({ "application/json" }) + public Response update(@PathParam("id") int id, Meal meal) { + meals.set(id, meal); + return Response.ok() + .entity(meal) + .build(); + } + + @DELETE + @Path("/{id}") + @Produces({ "application/json" }) + public Response delete(@PathParam("id") int id) { + Meal meal = meals.get(id); + meals.remove(id); + return Response.ok() + .entity(meal) + .build(); + } +} diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/Application.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/Application.java new file mode 100644 index 0000000000..dc4a060056 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/Application.java @@ -0,0 +1,11 @@ +package com.baeldung.msf4j.msf4jintro; + +import org.wso2.msf4j.MicroservicesRunner; + +public class Application { + public static void main(String[] args) { + new MicroservicesRunner() + .deploy(new SimpleService()) + .start(); + } +} \ No newline at end of file diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/SimpleService.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/SimpleService.java new file mode 100644 index 0000000000..bcb52859b5 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/SimpleService.java @@ -0,0 +1,21 @@ +package com.baeldung.msf4j.msf4jintro; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; + +@Path("/") +public class SimpleService { + + @GET + public String index() { + return "Default content"; + } + + @GET + @Path("/say/{name}") + public String say(@PathParam("name") String name) { + return "Hello " + name; + } + +} diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/Application.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/Application.java new file mode 100644 index 0000000000..2a5232a7e6 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/Application.java @@ -0,0 +1,10 @@ +package com.baeldung.msf4j.msf4jspring; + +import org.wso2.msf4j.spring.MSF4JSpringApplication; + +public class Application { + + public static void main(String[] args) { + MSF4JSpringApplication.run(Application.class, args); + } +} \ No newline at end of file diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/configuration/PortConfiguration.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/configuration/PortConfiguration.java new file mode 100644 index 0000000000..c3313fc3b1 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/configuration/PortConfiguration.java @@ -0,0 +1,15 @@ +package com.baeldung.msf4j.msf4jspring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.wso2.msf4j.spring.transport.HTTPTransportConfig; + +@Configuration +public class PortConfiguration { + + @Bean + public HTTPTransportConfig http() { + return new HTTPTransportConfig(9090); + } + +} \ No newline at end of file diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/domain/Meal.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/domain/Meal.java new file mode 100644 index 0000000000..99de0abc4c --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/domain/Meal.java @@ -0,0 +1,20 @@ +package com.baeldung.msf4j.msf4jspring.domain; + +public class Meal { + private String name; + private Float price; + + public Meal(String name, Float price) { + this.name = name; + this.price = price; + } + + public String getName() { + return name; + } + + public Float getPrice() { + return price; + } + +} diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/repositories/MealRepository.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/repositories/MealRepository.java new file mode 100644 index 0000000000..4d9e54348e --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/repositories/MealRepository.java @@ -0,0 +1,37 @@ +package com.baeldung.msf4j.msf4jspring.repositories; + +import java.util.ArrayList; +import java.util.List; +import org.springframework.stereotype.Component; +import com.baeldung.msf4j.msf4jspring.domain.Meal; + +@Component +public class MealRepository { + + private List meals = new ArrayList(); + + public MealRepository() { + meals.add(new Meal("Salad", 4.2f)); + meals.add(new Meal("Litre of cola", 2.99f)); + } + + public void create(Meal meal) { + meals.add(meal); + } + + public void remove(Meal meal) { + meals.remove(meal); + } + + public Meal find(int id) { + return meals.get(id); + } + + public List findAll() { + return meals; + } + + public void update(int id, Meal meal) { + meals.set(id, meal); + } +} \ No newline at end of file diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/resources/MealResource.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/resources/MealResource.java new file mode 100644 index 0000000000..9c617257cb --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/resources/MealResource.java @@ -0,0 +1,47 @@ +package com.baeldung.msf4j.msf4jspring.resources; + +import java.util.Collections; +import java.util.Map; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.wso2.msf4j.template.MustacheTemplateEngine; + +import com.baeldung.msf4j.msf4jspring.services.MealService; + +@Component +@Path("/meal") +public class MealResource { + + @Autowired + private MealService mealService; + + @GET + @Path("/") + public Response all() { + Map map = Collections.singletonMap("meals", mealService.findAll()); + String html = MustacheTemplateEngine.instance() + .render("meals.mustache", map); + return Response.ok() + .type(MediaType.TEXT_HTML) + .entity(html) + .build(); + } + + @GET + @Path("/{id}") + @Produces({ "text/xml" }) + public Response meal(@PathParam("id") int id) { + return Response.ok() + .entity(mealService.find(id)) + .build(); + } + +} diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/services/MealService.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/services/MealService.java new file mode 100644 index 0000000000..fd6a519999 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/services/MealService.java @@ -0,0 +1,27 @@ +package com.baeldung.msf4j.msf4jspring.services; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.baeldung.msf4j.msf4jspring.domain.Meal; +import com.baeldung.msf4j.msf4jspring.repositories.MealRepository; + +@Service +public class MealService { + @Autowired + private MealRepository mealRepository; + + public Meal find(int id) { + return mealRepository.find(id); + } + + public List findAll() { + return mealRepository.findAll(); + } + + public void create(Meal meal) { + mealRepository.create(meal); + } +} diff --git a/msf4j/src/main/resources/application.properties b/msf4j/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/msf4j/src/main/resources/logback.xml b/msf4j/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/msf4j/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/msf4j/src/main/resources/templates/meals.mustache b/msf4j/src/main/resources/templates/meals.mustache new file mode 100644 index 0000000000..f4bdfaccf9 --- /dev/null +++ b/msf4j/src/main/resources/templates/meals.mustache @@ -0,0 +1,13 @@ + + + Meals + + +
    +

    Today's Meals

    + {{#meals}} +
    {{name}}: {{price}}$
    + {{/meals}} +
    + + \ No newline at end of file diff --git a/muleesb/pom.xml b/muleesb/pom.xml index a3b9869eb4..b34123567a 100644 --- a/muleesb/pom.xml +++ b/muleesb/pom.xml @@ -1,5 +1,6 @@ - + 4.0.0 com.mycompany @@ -14,94 +15,6 @@ 1.0.0-SNAPSHOT - - - - org.mule.tools.maven - mule-app-maven-plugin - ${mule.tools.version} - true - - true - - - - org.mule.tools - muleesb-maven-plugin - 1.0 - - 3.7.0 - /home/abir/AnypointStudio/workspace/variablescopetest - - - - deploy - - start - - - - - - org.codehaus.mojo - build-helper-maven-plugin - 1.7 - - - add-resource - generate-resources - - add-resource - - - - - src/main/app/ - - - mappings/ - - - src/main/api/ - - - - - - - - com.mulesoft.munit.tools - munit-maven-plugin - ${munit.version} - - - test - test - - test - - - - - - true - - html - - - - - - - - src/test/munit - - - src/test/resources - - - - @@ -182,6 +95,94 @@ + + + + org.mule.tools.maven + mule-app-maven-plugin + ${mule.tools.version} + true + + true + + + + org.mule.tools + muleesb-maven-plugin + ${muleesb-maven-plugin.version} + + ${mule.version} + /home/abir/AnypointStudio/workspace/variablescopetest + + + + deploy + + start + + + + + + org.codehaus.mojo + build-helper-maven-plugin + ${build-helper-maven-plugin.version} + + + add-resource + generate-resources + + add-resource + + + + + src/main/app/ + + + mappings/ + + + src/main/api/ + + + + + + + + com.mulesoft.munit.tools + munit-maven-plugin + ${munit.version} + + + test + test + + test + + + + + + true + + html + + + + + + + + src/test/munit + + + src/test/resources + + + + Central @@ -210,12 +211,12 @@ - UTF-8 - UTF-8 3.8.1 1.2 1.3.6 3.9.0 + 1.0 + 1.7 diff --git a/mustache/pom.xml b/mustache/pom.xml index 88d87758cd..d385246182 100644 --- a/mustache/pom.xml +++ b/mustache/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 mustache @@ -8,11 +8,10 @@ mustache - org.springframework.boot - spring-boot-starter-parent - 1.5.4.RELEASE - - + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-1 @@ -95,6 +94,7 @@ **/*IntegrationTest.java + **/*IntTest.java
    @@ -125,6 +125,7 @@ **/*LiveTest.java **/*IntegrationTest.java + **/*IntTest.java **/AutoconfigurationTest.java @@ -152,7 +153,7 @@ 3.7.0 - 2.19.1 + 2.21.0 0.8 3.3.7 1.8 diff --git a/mustache/src/main/resources/logback.xml b/mustache/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/mustache/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ 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 deleted file mode 100644 index 0df2f7f8a4..0000000000 --- a/mustache/src/test/java/com/baeldung/mustache/TodoMustacheServiceTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.baeldung.mustache; - -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.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.assertj.core.api.Assertions.assertThat; - -public class TodoMustacheServiceTest { - - 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 { - StringWriter writer = new StringWriter(); - m.execute(writer, todo).flush(); - return writer.toString(); - } - - @Test - 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 { - 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 { - 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") - ); - 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 { - Mustache m = MustacheUtil.getMustacheFactory().compile("todos.mustache"); - - Map context = new HashMap<>(); - assertThat(executeTemplate(m, context)).isEmpty(); - ; - } - - @Test - 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 { - 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") - ); - 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/mustache/TodoMustacheServiceUnitTest.java b/mustache/src/test/java/com/baeldung/mustache/TodoMustacheServiceUnitTest.java new file mode 100644 index 0000000000..0c192b30bc --- /dev/null +++ b/mustache/src/test/java/com/baeldung/mustache/TodoMustacheServiceUnitTest.java @@ -0,0 +1,100 @@ +package com.baeldung.mustache; + +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.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +public class TodoMustacheServiceUnitTest { + + 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 { + StringWriter writer = new StringWriter(); + m.execute(writer, todo).flush(); + return writer.toString(); + } + + @Test + 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 { + 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 { + 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") + ); + 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 { + Mustache m = MustacheUtil.getMustacheFactory().compile("todos.mustache"); + + Map context = new HashMap<>(); + assertThat(executeTemplate(m, context)).isEmpty(); + ; + } + + @Test + 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 { + 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") + ); + 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/mvn-wrapper/pom.xml b/mvn-wrapper/pom.xml index 6fb9bfeffc..7f45fe218d 100644 --- a/mvn-wrapper/pom.xml +++ b/mvn-wrapper/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 mvn-wrapper 0.0.1-SNAPSHOT @@ -9,10 +9,10 @@ Setting up the Maven Wrapper - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -35,9 +35,4 @@ - - UTF-8 - UTF-8 - - diff --git a/mvn-wrapper/src/main/resources/logback.xml b/mvn-wrapper/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/mvn-wrapper/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/mybatis/pom.xml b/mybatis/pom.xml index b167d94ed8..aa9ff9e288 100644 --- a/mybatis/pom.xml +++ b/mybatis/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung mybatis diff --git a/mybatis/src/main/resources/logback.xml b/mybatis/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/mybatis/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/noexception/pom.xml b/noexception/pom.xml index c825449452..f632f1e3a9 100644 --- a/noexception/pom.xml +++ b/noexception/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung noexception diff --git a/noexception/src/main/resources/logback.xml b/noexception/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/noexception/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/optaplanner/pom.xml b/optaplanner/pom.xml new file mode 100644 index 0000000000..22abbedc8c --- /dev/null +++ b/optaplanner/pom.xml @@ -0,0 +1,27 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + optaplanner + + + + org.optaplanner + optaplanner-core + 7.9.0.Final + + + + + + + + + \ No newline at end of file diff --git a/optaplanner/src/main/java/com/baeldung/optaplanner/CourseSchedule.java b/optaplanner/src/main/java/com/baeldung/optaplanner/CourseSchedule.java new file mode 100644 index 0000000000..8a820ab56e --- /dev/null +++ b/optaplanner/src/main/java/com/baeldung/optaplanner/CourseSchedule.java @@ -0,0 +1,63 @@ +package com.baeldung.optaplanner; + +import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty; +import org.optaplanner.core.api.domain.solution.PlanningScore; +import org.optaplanner.core.api.domain.solution.PlanningSolution; +import org.optaplanner.core.api.domain.solution.drools.ProblemFactCollectionProperty; +import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider; +import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +@PlanningSolution +public class CourseSchedule { + + Logger logger = LoggerFactory.getLogger("CourseSchedule"); + + private List roomList; + private List periodList; + private List lectureList; + private HardSoftScore score; + + public CourseSchedule(){ + roomList = new ArrayList<>(); + periodList = new ArrayList<>(); + lectureList = new ArrayList<>(); + } + + @ValueRangeProvider(id = "availableRooms") + @ProblemFactCollectionProperty + public List getRoomList() { + return roomList; + } + + @ValueRangeProvider(id = "availablePeriods") + @ProblemFactCollectionProperty + public List getPeriodList() { + return periodList; + } + + @PlanningEntityCollectionProperty + public List getLectureList() { + return lectureList; + } + + @PlanningScore + public HardSoftScore getScore() { + return score; + } + + public void setScore(HardSoftScore score) { + this.score = score; + } + + public void printCourseSchedule() { + lectureList.stream() + .map(c -> "Lecture in Room " + c.getRoomNumber().toString() + " during Period " + c.getPeriod().toString()) + .forEach(k -> logger.info(k)); + } + +} diff --git a/optaplanner/src/main/java/com/baeldung/optaplanner/Lecture.java b/optaplanner/src/main/java/com/baeldung/optaplanner/Lecture.java new file mode 100644 index 0000000000..48af4e89d1 --- /dev/null +++ b/optaplanner/src/main/java/com/baeldung/optaplanner/Lecture.java @@ -0,0 +1,30 @@ +package com.baeldung.optaplanner; + +import org.optaplanner.core.api.domain.entity.PlanningEntity; +import org.optaplanner.core.api.domain.variable.PlanningVariable; + +@PlanningEntity +public class Lecture { + + private Integer roomNumber; + private Integer period; + + @PlanningVariable(valueRangeProviderRefs = {"availablePeriods"}) + public Integer getPeriod() { + return period; + } + + @PlanningVariable(valueRangeProviderRefs = {"availableRooms"}) + public Integer getRoomNumber() { + return roomNumber; + } + + public void setPeriod(Integer period) { + this.period = period; + } + + public void setRoomNumber(Integer roomNumber) { + this.roomNumber = roomNumber; + } + +} diff --git a/optaplanner/src/main/java/com/baeldung/optaplanner/ScoreCalculator.java b/optaplanner/src/main/java/com/baeldung/optaplanner/ScoreCalculator.java new file mode 100644 index 0000000000..11e5e4a5be --- /dev/null +++ b/optaplanner/src/main/java/com/baeldung/optaplanner/ScoreCalculator.java @@ -0,0 +1,32 @@ +package com.baeldung.optaplanner; + +import org.optaplanner.core.api.score.Score; +import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore; +import org.optaplanner.core.impl.score.director.easy.EasyScoreCalculator; + +import java.util.HashSet; + +public class ScoreCalculator implements EasyScoreCalculator { + + @Override + public Score calculateScore(CourseSchedule courseSchedule) { + int hardScore = 0; + int softScore = 0; + + HashSet occupiedRooms = new HashSet<>(); + for (Lecture lecture : courseSchedule.getLectureList()) { + if(lecture.getPeriod() != null && lecture.getRoomNumber() != null) { + String roomInUse = lecture.getPeriod().toString() + ":" + lecture.getRoomNumber().toString(); + if (occupiedRooms.contains(roomInUse)) { + hardScore += -1; + } else { + occupiedRooms.add(roomInUse); + } + } else { + hardScore += -1; + } + } + + return HardSoftScore.valueOf(hardScore, softScore); + } +} diff --git a/optaplanner/src/main/resources/courseSchedule.drl b/optaplanner/src/main/resources/courseSchedule.drl new file mode 100644 index 0000000000..9372a24976 --- /dev/null +++ b/optaplanner/src/main/resources/courseSchedule.drl @@ -0,0 +1,14 @@ +package com.baeldung.optaplanner + +import com.baeldung.optaplanner.Lecture; +import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScoreHolder; + +global HardSoftScoreHolder scoreHolder; + +rule "noNullRoomPeriod" + when + Lecture( roomNumber == null ); + Lecture( period == null ); + then + scoreHolder.addHardConstraintMatch(kcontext, -1); +end \ No newline at end of file diff --git a/optaplanner/src/main/resources/courseScheduleSolverConfigDrools.xml b/optaplanner/src/main/resources/courseScheduleSolverConfigDrools.xml new file mode 100644 index 0000000000..7cf95fdcd3 --- /dev/null +++ b/optaplanner/src/main/resources/courseScheduleSolverConfigDrools.xml @@ -0,0 +1,12 @@ + + + + + + courseSchedule.drl + + + + 10 + + \ No newline at end of file diff --git a/optaplanner/src/main/resources/courseScheduleSolverConfiguration.xml b/optaplanner/src/main/resources/courseScheduleSolverConfiguration.xml new file mode 100644 index 0000000000..0ad2264dcd --- /dev/null +++ b/optaplanner/src/main/resources/courseScheduleSolverConfiguration.xml @@ -0,0 +1,12 @@ + + + + + + com.baeldung.optaplanner.ScoreCalculator + + + + 10 + + \ No newline at end of file diff --git a/optaplanner/src/main/resources/logback.xml b/optaplanner/src/main/resources/logback.xml new file mode 100644 index 0000000000..c109aa19e2 --- /dev/null +++ b/optaplanner/src/main/resources/logback.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/optaplanner/src/test/java/com/baeldung/optaplanner/test/OptaPlannerUnitTest.java b/optaplanner/src/test/java/com/baeldung/optaplanner/test/OptaPlannerUnitTest.java new file mode 100644 index 0000000000..2847a233a5 --- /dev/null +++ b/optaplanner/src/test/java/com/baeldung/optaplanner/test/OptaPlannerUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.optaplanner.test; + +import com.baeldung.optaplanner.CourseSchedule; +import com.baeldung.optaplanner.Lecture; +import org.junit.Assert; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.optaplanner.core.api.solver.Solver; +import org.optaplanner.core.api.solver.SolverFactory; +import java.util.Arrays; + +public class OptaPlannerUnitTest { + + static CourseSchedule unsolvedCourseSchedule; + + @BeforeAll + public static void setUp() { + + unsolvedCourseSchedule = new CourseSchedule(); + + for(int i = 0; i < 10; i++){ + unsolvedCourseSchedule.getLectureList().add(new Lecture()); + } + + unsolvedCourseSchedule.getPeriodList().addAll(Arrays.asList(new Integer[] { 1, 2, 3 })); + unsolvedCourseSchedule.getRoomList().addAll(Arrays.asList(new Integer[] { 1, 2 })); + } + + @Test + public void test_whenCustomJavaSolver() { + + SolverFactory solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfiguration.xml"); + Solver solver = solverFactory.buildSolver(); + CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule); + + Assert.assertNotNull(solvedCourseSchedule.getScore()); + Assert.assertEquals(-4, solvedCourseSchedule.getScore().getHardScore()); + } + + @Test + public void test_whenDroolsSolver() { + + SolverFactory solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfigDrools.xml"); + Solver solver = solverFactory.buildSolver(); + CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule); + + Assert.assertNotNull(solvedCourseSchedule.getScore()); + Assert.assertEquals(0, solvedCourseSchedule.getScore().getHardScore()); + } +} diff --git a/orientdb/pom.xml b/orientdb/pom.xml index 317c469005..e1c7ac42bb 100644 --- a/orientdb/pom.xml +++ b/orientdb/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 orientdb 0.0.1-SNAPSHOT @@ -36,22 +36,11 @@ ${blueprints.version} - - junit - junit - ${junit.version} - test - -
    - + - UTF-8 - UTF-8 - 1.8 2.2.31 2.6.0 - 4.12
    diff --git a/orientdb/src/main/resources/logback.xml b/orientdb/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/orientdb/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBDocumentAPILiveTest.java b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBDocumentAPILiveTest.java new file mode 100644 index 0000000000..be79394292 --- /dev/null +++ b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBDocumentAPILiveTest.java @@ -0,0 +1,60 @@ +package com.baeldung.orientdb; + +import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; +import com.orientechnologies.orient.core.record.impl.ODocument; +import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +import static junit.framework.Assert.assertEquals; + +public class OrientDBDocumentAPILiveTest { + private static ODatabaseDocumentTx db = null; + + // @BeforeClass + public static void setup() { + String orientDBFolder = System.getenv("ORIENTDB_HOME"); + db = new ODatabaseDocumentTx("plocal:" + orientDBFolder + "/databases/BaeldungDBTwo").open("admin", "admin"); + } + + // @Test + public void givenDB_whenSavingDocument_thenClassIsAutoCreated() { + ODocument author = new ODocument("Author"); + author.field("firstName", "Paul"); + author.field("lastName", "Smith"); + author.field("country", "USA"); + author.field("publicProfile", false); + author.field("level", 7); + author.save(); + + assertEquals("Author", author.getSchemaClass().getName()); + } + + // @Test + public void givenDB_whenSavingAuthors_thenWeGetOnesWithLevelSeven() { + for (ODocument author : db.browseClass("Author")) author.delete(); + + ODocument authorOne = new ODocument("Author"); + authorOne.field("firstName", "Leo"); + authorOne.field("level", 7); + authorOne.save(); + + ODocument authorTwo = new ODocument("Author"); + authorTwo.field("firstName", "Lucien"); + authorTwo.field("level", 9); + authorTwo.save(); + + List result = db.query( + new OSQLSynchQuery("select * from Author where level = 7")); + + assertEquals(1, result.size()); + } + + // @AfterClass + public static void closeDB() { + db.close(); + } +} diff --git a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBDocumentAPITest.java b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBDocumentAPITest.java deleted file mode 100644 index c51ff6928f..0000000000 --- a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBDocumentAPITest.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.orientdb; - -import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.util.List; - -import static junit.framework.Assert.assertEquals; - -public class OrientDBDocumentAPITest { - private static ODatabaseDocumentTx db = null; - - // @BeforeClass - public static void setup() { - String orientDBFolder = System.getenv("ORIENTDB_HOME"); - db = new ODatabaseDocumentTx("plocal:" + orientDBFolder + "/databases/BaeldungDBTwo").open("admin", "admin"); - } - - // @Test - public void givenDB_whenSavingDocument_thenClassIsAutoCreated() { - ODocument author = new ODocument("Author"); - author.field("firstName", "Paul"); - author.field("lastName", "Smith"); - author.field("country", "USA"); - author.field("publicProfile", false); - author.field("level", 7); - author.save(); - - assertEquals("Author", author.getSchemaClass().getName()); - } - - // @Test - public void givenDB_whenSavingAuthors_thenWeGetOnesWithLevelSeven() { - for (ODocument author : db.browseClass("Author")) author.delete(); - - ODocument authorOne = new ODocument("Author"); - authorOne.field("firstName", "Leo"); - authorOne.field("level", 7); - authorOne.save(); - - ODocument authorTwo = new ODocument("Author"); - authorTwo.field("firstName", "Lucien"); - authorTwo.field("level", 9); - authorTwo.save(); - - List result = db.query( - new OSQLSynchQuery("select * from Author where level = 7")); - - assertEquals(1, result.size()); - } - - // @AfterClass - public static void closeDB() { - db.close(); - } -} diff --git a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBGraphAPILiveTest.java b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBGraphAPILiveTest.java new file mode 100644 index 0000000000..69926e5ed6 --- /dev/null +++ b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBGraphAPILiveTest.java @@ -0,0 +1,89 @@ +package com.baeldung.orientdb; + +import com.orientechnologies.orient.core.metadata.schema.OType; +import com.tinkerpop.blueprints.Vertex; +import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx; +import com.tinkerpop.blueprints.impls.orient.OrientVertexType; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import static junit.framework.Assert.assertEquals; + +public class OrientDBGraphAPILiveTest { + private static OrientGraphNoTx graph = null; + + // @BeforeClass + public static void setup() { + String orientDBFolder = System.getenv("ORIENTDB_HOME"); + graph = new OrientGraphNoTx("plocal:" + orientDBFolder + "/databases/BaeldungDB", "admin", "admin"); + } + + // @BeforeClass + public static void init() { + graph.createVertexType("Article"); + + OrientVertexType writerType = graph.createVertexType("Writer"); + writerType.setStrictMode(true); + writerType.createProperty("firstName", OType.STRING); + writerType.createProperty("lastName", OType.STRING); + writerType.createProperty("country", OType.STRING); + + OrientVertexType authorType = graph.createVertexType("Author", "Writer"); + authorType.createProperty("level", OType.INTEGER).setMax("3"); + + OrientVertexType editorType = graph.createVertexType("Editor", "Writer"); + editorType.createProperty("level", OType.INTEGER).setMin("3"); + + Vertex vEditor = graph.addVertex("class:Editor"); + vEditor.setProperty("firstName", "Maxim"); + vEditor.setProperty("lastName", "Mink's"); + vEditor.setProperty("country", "Cameroon"); + vEditor.setProperty("publicProfile", true); + vEditor.setProperty("level", "7"); + + Vertex vAuthor = graph.addVertex("class:Author"); + vAuthor.setProperty("firstName", "Jerome"); + vAuthor.setProperty("country", "Romania"); + vAuthor.setProperty("publicProfile", false); + vAuthor.setProperty("level", "3"); + + Vertex vArticle = graph.addVertex("class:Article"); + vArticle.setProperty("title", "Introduction to the OrientDB Java APIs."); + vArticle.setProperty("priority", "High"); + vArticle.setProperty("type", "Article"); + vArticle.setProperty("level", "+L4"); + + graph.addEdge(null, vAuthor, vEditor, "has"); + graph.addEdge(null, vAuthor, vArticle, "wrote"); + } + + // @Test + public void givenBaeldungDB_checkWeHaveThreeRecords() { + long size = graph.countVertices(); + + assertEquals(3, size); + } + + // @Test + public void givenBaeldungDB_checkWeHaveTwoWriters() { + long size = graph.countVertices("Writer"); + + assertEquals(2, size); + } + + // @Test + public void givenBaeldungDB_getEditorWithLevelSeven() { + String onlyEditor = ""; + for(Vertex v : graph.getVertices("Editor.level", 7)) { + onlyEditor = v.getProperty("firstName").toString(); + } + + assertEquals("Maxim", onlyEditor); + } + + // @AfterClass + public static void closeDB() { + graph.getRawGraph().getStorage().close(true, false); + } +} diff --git a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBGraphAPITest.java b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBGraphAPITest.java deleted file mode 100644 index fe16564755..0000000000 --- a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBGraphAPITest.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.baeldung.orientdb; - -import com.orientechnologies.orient.core.metadata.schema.OType; -import com.tinkerpop.blueprints.Vertex; -import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx; -import com.tinkerpop.blueprints.impls.orient.OrientVertexType; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import static junit.framework.Assert.assertEquals; - -public class OrientDBGraphAPITest { - private static OrientGraphNoTx graph = null; - - // @BeforeClass - public static void setup() { - String orientDBFolder = System.getenv("ORIENTDB_HOME"); - graph = new OrientGraphNoTx("plocal:" + orientDBFolder + "/databases/BaeldungDB", "admin", "admin"); - } - - // @BeforeClass - public static void init() { - graph.createVertexType("Article"); - - OrientVertexType writerType = graph.createVertexType("Writer"); - writerType.setStrictMode(true); - writerType.createProperty("firstName", OType.STRING); - writerType.createProperty("lastName", OType.STRING); - writerType.createProperty("country", OType.STRING); - - OrientVertexType authorType = graph.createVertexType("Author", "Writer"); - authorType.createProperty("level", OType.INTEGER).setMax("3"); - - OrientVertexType editorType = graph.createVertexType("Editor", "Writer"); - editorType.createProperty("level", OType.INTEGER).setMin("3"); - - Vertex vEditor = graph.addVertex("class:Editor"); - vEditor.setProperty("firstName", "Maxim"); - vEditor.setProperty("lastName", "Mink's"); - vEditor.setProperty("country", "Cameroon"); - vEditor.setProperty("publicProfile", true); - vEditor.setProperty("level", "7"); - - Vertex vAuthor = graph.addVertex("class:Author"); - vAuthor.setProperty("firstName", "Jerome"); - vAuthor.setProperty("country", "Romania"); - vAuthor.setProperty("publicProfile", false); - vAuthor.setProperty("level", "3"); - - Vertex vArticle = graph.addVertex("class:Article"); - vArticle.setProperty("title", "Introduction to the OrientDB Java APIs."); - vArticle.setProperty("priority", "High"); - vArticle.setProperty("type", "Article"); - vArticle.setProperty("level", "+L4"); - - graph.addEdge(null, vAuthor, vEditor, "has"); - graph.addEdge(null, vAuthor, vArticle, "wrote"); - } - - // @Test - public void givenBaeldungDB_checkWeHaveThreeRecords() { - long size = graph.countVertices(); - - assertEquals(3, size); - } - - // @Test - public void givenBaeldungDB_checkWeHaveTwoWriters() { - long size = graph.countVertices("Writer"); - - assertEquals(2, size); - } - - // @Test - public void givenBaeldungDB_getEditorWithLevelSeven() { - String onlyEditor = ""; - for(Vertex v : graph.getVertices("Editor.level", 7)) { - onlyEditor = v.getProperty("firstName").toString(); - } - - assertEquals("Maxim", onlyEditor); - } - - // @AfterClass - public static void closeDB() { - graph.getRawGraph().getStorage().close(true, false); - } -} diff --git a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBObjectAPILiveTest.java b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBObjectAPILiveTest.java new file mode 100644 index 0000000000..61dad39050 --- /dev/null +++ b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBObjectAPILiveTest.java @@ -0,0 +1,56 @@ +package com.baeldung.orientdb; + +import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; +import com.orientechnologies.orient.object.db.OObjectDatabaseTx; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +import static junit.framework.Assert.assertEquals; + +public class OrientDBObjectAPILiveTest { + private static OObjectDatabaseTx db = null; + + // @BeforeClass + public static void setup() { + String orientDBFolder = System.getenv("ORIENTDB_HOME"); + db = new OObjectDatabaseTx("plocal:" + orientDBFolder + "/databases/BaeldungDBThree").open("admin", "admin"); + db.setSaveOnlyDirty(true); + db.getEntityManager().registerEntityClass(Author.class); + } + + // @Test + public void givenDB_whenSavingObject_thenHisIdExists() { + Author author = db.newInstance(Author.class); + author.setFirstName("Luke"); + author.setLastName("Sky"); + author.setLevel(9); + + long authors = db.countClass(Author.class); + + db.save(author); + } + + // @Test + public void givenDB_whenSavingAuthors_thenWeGetOnesWithLevelSeven() { + for (Author author : db.browseClass(Author.class)) db.delete(author); + + Author authorOne = db.newInstance(Author.class, "Leo", "Marta", 7); + db.save(authorOne); + + Author authorTwo = db.newInstance(Author.class, "Lucien", "Aurelien", 9); + db.save(authorTwo); + + List result = db.query( + new OSQLSynchQuery("select * from Author where level = 7")); + + assertEquals(1, result.size()); + } + + // @AfterClass + public static void closeDB() { + db.close(); + } +} diff --git a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBObjectAPITest.java b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBObjectAPITest.java deleted file mode 100644 index 71be159107..0000000000 --- a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBObjectAPITest.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.orientdb; - -import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; -import com.orientechnologies.orient.object.db.OObjectDatabaseTx; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.util.List; - -import static junit.framework.Assert.assertEquals; - -public class OrientDBObjectAPITest { - private static OObjectDatabaseTx db = null; - - // @BeforeClass - public static void setup() { - String orientDBFolder = System.getenv("ORIENTDB_HOME"); - db = new OObjectDatabaseTx("plocal:" + orientDBFolder + "/databases/BaeldungDBThree").open("admin", "admin"); - db.setSaveOnlyDirty(true); - db.getEntityManager().registerEntityClass(Author.class); - } - - // @Test - public void givenDB_whenSavingObject_thenHisIdExists() { - Author author = db.newInstance(Author.class); - author.setFirstName("Luke"); - author.setLastName("Sky"); - author.setLevel(9); - - long authors = db.countClass(Author.class); - - db.save(author); - } - - // @Test - public void givenDB_whenSavingAuthors_thenWeGetOnesWithLevelSeven() { - for (Author author : db.browseClass(Author.class)) db.delete(author); - - Author authorOne = db.newInstance(Author.class, "Leo", "Marta", 7); - db.save(authorOne); - - Author authorTwo = db.newInstance(Author.class, "Lucien", "Aurelien", 9); - db.save(authorTwo); - - List result = db.query( - new OSQLSynchQuery("select * from Author where level = 7")); - - assertEquals(1, result.size()); - } - - // @AfterClass - public static void closeDB() { - db.close(); - } -} diff --git a/orika/pom.xml b/orika/pom.xml index 1a54440ffe..e4da5955bf 100644 --- a/orika/pom.xml +++ b/orika/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung orika diff --git a/orika/src/main/resources/logback.xml b/orika/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/orika/src/main/resources/logback.xml +++ b/orika/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/osgi/osgi-intro-sample-activator/pom.xml b/osgi/osgi-intro-sample-activator/pom.xml index 1584913627..77d7198698 100644 --- a/osgi/osgi-intro-sample-activator/pom.xml +++ b/osgi/osgi-intro-sample-activator/pom.xml @@ -1,20 +1,17 @@ - + + 4.0.0 + + bundle + osgi-intro-sample-activator - osgi-intro + osgi com.baeldung 1.0-SNAPSHOT - 4.0.0 - - - bundle - - osgi-intro-sample-activator @@ -38,11 +35,8 @@ com.baeldung.osgi.sample.activator.HelloWorld - + com.baeldung.osgi.sample.activator diff --git a/osgi/osgi-intro-sample-activator/src/main/resources/logback.xml b/osgi/osgi-intro-sample-activator/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/osgi/osgi-intro-sample-activator/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/osgi/osgi-intro-sample-client/pom.xml b/osgi/osgi-intro-sample-client/pom.xml index 4096674d7d..7f5faedb30 100644 --- a/osgi/osgi-intro-sample-client/pom.xml +++ b/osgi/osgi-intro-sample-client/pom.xml @@ -2,23 +2,22 @@ + 4.0.0 + + osgi-intro-sample-client + bundle + - osgi-intro + osgi com.baeldung 1.0-SNAPSHOT - 4.0.0 - - - osgi-intro-sample-client - - bundle com.baeldung osgi-intro-sample-service - 1.0-SNAPSHOT + ${osgi-intro-sample-service.version} org.osgi @@ -46,4 +45,7 @@ + + 1.0-SNAPSHOT + \ No newline at end of file diff --git a/osgi/osgi-intro-sample-client/src/main/resources/logback.xml b/osgi/osgi-intro-sample-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/osgi/osgi-intro-sample-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/osgi/osgi-intro-sample-service/pom.xml b/osgi/osgi-intro-sample-service/pom.xml index cbc660bb74..8f81645ad4 100644 --- a/osgi/osgi-intro-sample-service/pom.xml +++ b/osgi/osgi-intro-sample-service/pom.xml @@ -1,20 +1,17 @@ - + + 4.0.0 + osgi-intro-sample-service + + bundle - osgi-intro + osgi com.baeldung 1.0-SNAPSHOT - 4.0.0 - - osgi-intro-sample-service - - - bundle diff --git a/osgi/osgi-intro-sample-service/src/main/resources/logback.xml b/osgi/osgi-intro-sample-service/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/osgi/osgi-intro-sample-service/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/osgi/pom.xml b/osgi/pom.xml index 704a738d24..9ebcb09091 100644 --- a/osgi/pom.xml +++ b/osgi/pom.xml @@ -1,11 +1,11 @@ - + 4.0.0 - osgi-intro + osgi pom 1.0-SNAPSHOT + osgi com.baeldung @@ -45,22 +45,22 @@ com.squareup.okhttp3 okhttp - 3.9.0 + ${okhttp.version} javax.json javax.json-api - 1.1 + ${javax.json.version} org.glassfish javax.json - 1.1 + ${javax.json.version} org.osgi org.osgi.core - 6.0.0 + ${osgi.version} provided @@ -72,11 +72,18 @@ org.apache.felix maven-bundle-plugin - 3.3.0 + ${maven-bundle-plugin.version} true + + 3.9.0 + 1.1 + 6.0.0 + 3.3.0 + + \ No newline at end of file diff --git a/out/production/generated-sources8/src.main.resources.reladomo.ReladomoClassList.xml.log b/out/production/generated-sources8/src.main.resources.reladomo.ReladomoClassList.xml.log deleted file mode 100644 index 0bd4e29a45..0000000000 --- a/out/production/generated-sources8/src.main.resources.reladomo.ReladomoClassList.xml.log +++ /dev/null @@ -1,2 +0,0 @@ -f5a6ba3b942a82fcbfb72e61502d5c30 -9201deea diff --git a/out/production/introduction/views/index.scala.html b/out/production/introduction/views/index.scala.html deleted file mode 100644 index 4539f5a10b..0000000000 --- a/out/production/introduction/views/index.scala.html +++ /dev/null @@ -1,20 +0,0 @@ -@* - * This template takes a single argument, a String containing a - * message to display. - *@ -@(message: String) - -@* - * Call the `main` template with two arguments. The first - * argument is a `String` with the title of the page, the second - * argument is an `Html` object containing the body of the page. - *@ -@main("Welcome to Play") { - - @* - * Get an `Html` object by calling the built-in Play welcome - * template and passing a `String` message. - *@ - @play20.welcome(message, style = "Java") - -} diff --git a/out/production/introduction/views/main.scala.html b/out/production/introduction/views/main.scala.html deleted file mode 100644 index 9414f4be6e..0000000000 --- a/out/production/introduction/views/main.scala.html +++ /dev/null @@ -1,23 +0,0 @@ -@* - * This template is called from the `index` template. This template - * handles the rendering of the page header and body tags. It takes - * two arguments, a `String` for the title of the page and an `Html` - * object to insert into the body of the page. - *@ -@(title: String)(content: Html) - - - - - @* Here's where we render the page title `String`. *@ - @title - - - - - - @* And here's where we render the `Html` object containing - * the page content. *@ - @content - - diff --git a/out/production/main/com/baeldung/.gitignore b/out/production/main/com/baeldung/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/out/production/main/com/baeldung/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/out/production/main151/com/baeldung/README.md b/out/production/main/com/baeldung/README.md similarity index 100% rename from out/production/main151/com/baeldung/README.md rename to out/production/main/com/baeldung/README.md diff --git a/out/production/main330/com/baeldung/enums/README.md b/out/production/main/com/baeldung/enums/README.md similarity index 100% rename from out/production/main330/com/baeldung/enums/README.md rename to out/production/main/com/baeldung/enums/README.md diff --git a/out/production/main330/com/baeldung/networking/README.md b/out/production/main/com/baeldung/networking/README.md similarity index 100% rename from out/production/main330/com/baeldung/networking/README.md rename to out/production/main/com/baeldung/networking/README.md diff --git a/out/production/main/com/baeldung/objectsize/MANIFEST.MF b/out/production/main/com/baeldung/objectsize/MANIFEST.MF new file mode 100644 index 0000000000..b814f624d0 --- /dev/null +++ b/out/production/main/com/baeldung/objectsize/MANIFEST.MF @@ -0,0 +1 @@ +Premain-class: com.baeldung.objectsize.InstrumentationAgent diff --git a/out/production/main330/com/baeldung/printscreen/README.md b/out/production/main/com/baeldung/printscreen/README.md similarity index 100% rename from out/production/main330/com/baeldung/printscreen/README.md rename to out/production/main/com/baeldung/printscreen/README.md diff --git a/out/production/main/javac-args/arguments b/out/production/main/javac-args/arguments new file mode 100644 index 0000000000..51639800a7 --- /dev/null +++ b/out/production/main/javac-args/arguments @@ -0,0 +1,2 @@ +-d javac-target -verbose +com/baeldung/javac/Data.java \ No newline at end of file diff --git a/out/production/main/javac-args/options b/out/production/main/javac-args/options new file mode 100644 index 0000000000..f02f2344ff --- /dev/null +++ b/out/production/main/javac-args/options @@ -0,0 +1,2 @@ +-d javac-target +-verbose \ No newline at end of file diff --git a/out/production/main/javac-args/types b/out/production/main/javac-args/types new file mode 100644 index 0000000000..ef2d861f84 --- /dev/null +++ b/out/production/main/javac-args/types @@ -0,0 +1 @@ +com/baeldung/javac/Data.java \ No newline at end of file diff --git a/out/production/main/javac-args/xlint-ops b/out/production/main/javac-args/xlint-ops new file mode 100644 index 0000000000..cdccbc0cce --- /dev/null +++ b/out/production/main/javac-args/xlint-ops @@ -0,0 +1,3 @@ +-d javac-target +-Xlint:rawtypes,unchecked,static,cast,serial,fallthrough +com/baeldung/javac/Data.java \ No newline at end of file diff --git a/out/production/main173/log4j.properties b/out/production/main/log4j.properties similarity index 100% rename from out/production/main173/log4j.properties rename to out/production/main/log4j.properties diff --git a/out/production/main237/com/baeldung/datetime/README.md b/out/production/main1/com/baeldung/datetime/README.md similarity index 100% rename from out/production/main237/com/baeldung/datetime/README.md rename to out/production/main1/com/baeldung/datetime/README.md diff --git a/out/production/main155/com/baeldung/git/README.md b/out/production/main155/com/baeldung/git/README.md deleted file mode 100644 index 7e6a597c28..0000000000 --- a/out/production/main155/com/baeldung/git/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [Injecting Git Information Into Spring](http://www.baeldung.com/spring-git-information) diff --git a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt b/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt deleted file mode 100644 index bffe24e485..0000000000 --- a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt +++ /dev/null @@ -1,76 +0,0 @@ -About the application ---------------------- -This application demonstrates the usage of JavaEE Web Annotations. - - -Contents of the application ---------------------------- -1. AccountServlet.java - Demonstrates the @WebServlet and @ServletSecurity annotation. - -NOTES: @WebServlet annotation designates the AccountServlet class as a Servlet component. - The usage of its parameters 'urlPatterns' & 'initParams' can be observed. - An initialization parameter 'type' is being set to denote the type of the bank account. - - @ServletSecurity annotation imposes security constraints on the AccountServlet based on - the tomcat-users.xml. -   - This code assumes that your tomcat-users.xml looks as follows: - - - - - - - -   -N.B : To see @ServletSecurity annotation in action, please uncomment the annotation code - for @ServletSecurity. - - -2. BankAppServletContextListener.java - Demonstrates the @WebListener annotation for denoting a class as a ServletContextListener. - -NOTES: Sets a Servlet context attribute ATTR_DEFAULT_LANGUAGE to 'english' on web application start up, - which can then be used throughout the application. - - -3. LogInFilter.java - Demonstrates the @WebFilter annotation. - -NOTES: @WebFilter annotation designates the LogInFilter class as a Filter component. - It filters all requests to the bank account servlet and redirects them to - the login page. - -N.B : To see @WebFilter annotation in action, please uncomment the annotation code for @WebFilter. - - -4. UploadCustomerDocumentsServlet.java - Demonstrates the @MultipartConfig annotation. - -NOTES: @MultipartConfig anotation designates the UploadCustomerDocumentsServlet Servlet component, - to handle multipart/form-data requests. - To see it in action, deploy the web application an access the url: http://:/JavaEEAnnotationsSample/upload.jsp - Once you upload a file from here, it will get uploaded to D:/custDocs (assuming such a folder exists). - - -5. index.jsp - This is the welcome page. - -NOTES: You can enter a deposit amount here and click on the 'Deposit' button to see the AccountServlet in action. - -6. login.jsp - All requests to the AccountServlet are redirected to this page, if the LogInFilter is imposed. - -7. upload.jsp - Demonstrates the usage of handling multipart/form-data requests by the UploadCustomerDocumentsServlet. - - -Building and Running the application ------------------------------------- -To build the application: - -1. Open the project in eclipse -2. Right click on it in eclispe and choose Run As > Maven build -3. Give 'clean install' under Goals -4. This should build the WAR file of the application - -To run the application: - -1. Right click on the project -2. Run as > Run on Server -3. This will start you Tomcat server and deploy the application (Provided that you have configured Tomcat in your eclipse) -4. You should now be able to access the url : http://:/JavaEEAnnotationsSample diff --git a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml b/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml deleted file mode 100644 index 2835f6f416..0000000000 --- a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml +++ /dev/null @@ -1,48 +0,0 @@ - - 4.0.0 - com.baeldung.javaeeannotations - JavaEEAnnotationsSample - 0.0.1-SNAPSHOT - war - JavaEEAnnotationsSample - JavaEEAnnotationsSample - - - - - javax.annotation - javax.annotation-api - 1.3 - - - - javax.servlet - javax.servlet-api - 3.1.0 - - - - javax.servlet.jsp - jsp-api - 2.1 - - - - - - - - org.apache.maven.plugins - maven-war-plugin - 2.4 - - src/main/webapp - SpringFieldConstructorInjection - false - - - - - JavaEEAnnotationsSample - - \ No newline at end of file diff --git a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml b/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index a92885ec11..0000000000 --- a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - BASIC - default - - diff --git a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp b/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp deleted file mode 100644 index c49dec859e..0000000000 --- a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp +++ /dev/null @@ -1,16 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> - - - - -My Account - - -
    - Amount: -    - -
    - - \ No newline at end of file diff --git a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp b/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp deleted file mode 100644 index 6892cb0420..0000000000 --- a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp +++ /dev/null @@ -1,12 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> - - - - -Login - - -Login Here... - - \ No newline at end of file diff --git a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/upload.jsp b/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/upload.jsp deleted file mode 100644 index 3601322ef0..0000000000 --- a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/upload.jsp +++ /dev/null @@ -1,16 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> - - - - -Insert title here - - -
    - -
    - -
    - - \ No newline at end of file diff --git a/out/production/main180/com/baeldung/jaxws/wsdl/employeeservicetopdown.wsdl b/out/production/main180/com/baeldung/jaxws/wsdl/employeeservicetopdown.wsdl deleted file mode 100644 index 426717f90e..0000000000 --- a/out/production/main180/com/baeldung/jaxws/wsdl/employeeservicetopdown.wsdl +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/out/production/main195/com/baeldung/java/nio/selector/README.md b/out/production/main195/com/baeldung/java/nio/selector/README.md deleted file mode 100644 index b28aae1397..0000000000 --- a/out/production/main195/com/baeldung/java/nio/selector/README.md +++ /dev/null @@ -1,2 +0,0 @@ -###Relevant Articles: -- [Introduction to the Java NIO Selector](http://www.baeldung.com/java-nio-selector) diff --git a/out/production/main216/com/baeldung/googlehttpclientguide/logging.properties b/out/production/main216/com/baeldung/googlehttpclientguide/logging.properties deleted file mode 100644 index 02489378df..0000000000 --- a/out/production/main216/com/baeldung/googlehttpclientguide/logging.properties +++ /dev/null @@ -1,10 +0,0 @@ -# Properties file which configures the operation of the JDK logging facility. -# The system will look for this config file to be specified as a system property: -# -Djava.util.logging.config.file=${project_loc:dailymotion-simple-cmdline-sample}/logging.properties - -# Set up the console handler (uncomment "level" to show more fine-grained messages) -handlers = java.util.logging.ConsoleHandler -java.util.logging.ConsoleHandler.level = ALL - -# Set up logging of HTTP requests and responses (uncomment "level" to show) -com.google.api.client.http.level = ALL diff --git a/out/production/main231/com/baeldung/wicket/examples/HelloWorld.html b/out/production/main231/com/baeldung/wicket/examples/HelloWorld.html deleted file mode 100644 index 497e98e01a..0000000000 --- a/out/production/main231/com/baeldung/wicket/examples/HelloWorld.html +++ /dev/null @@ -1,52 +0,0 @@ - - - - -Wicket Intro Examples - - - -
    -
    -
    -

    Wicket Introduction Examples:

    - - Hello World! -
    -
    - Cafes -
    -
    -
    -
    - - diff --git a/out/production/main231/com/baeldung/wicket/examples/cafeaddress/CafeAddress.html b/out/production/main231/com/baeldung/wicket/examples/cafeaddress/CafeAddress.html deleted file mode 100644 index c5ada2323d..0000000000 --- a/out/production/main231/com/baeldung/wicket/examples/cafeaddress/CafeAddress.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - -Cafes - - -
    - -

    - Address: address -

    -
    - - diff --git a/out/production/main231/com/baeldung/wicket/examples/helloworld/HelloWorld.html b/out/production/main231/com/baeldung/wicket/examples/helloworld/HelloWorld.html deleted file mode 100644 index c56d07fc10..0000000000 --- a/out/production/main231/com/baeldung/wicket/examples/helloworld/HelloWorld.html +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/out/production/main234/com/baeldung/activiti/security.rar b/out/production/main234/com/baeldung/activiti/security.rar deleted file mode 100644 index 38c4946168..0000000000 Binary files a/out/production/main234/com/baeldung/activiti/security.rar and /dev/null differ diff --git a/out/production/main291/xml-bean-config.xml b/out/production/main291/xml-bean-config.xml deleted file mode 100644 index 3b880bbd70..0000000000 --- a/out/production/main291/xml-bean-config.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/out/production/main30/com/baeldung/factorybean/README.md b/out/production/main30/com/baeldung/factorybean/README.md deleted file mode 100644 index 13f9f379e0..0000000000 --- a/out/production/main30/com/baeldung/factorybean/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean) diff --git a/out/production/main330/com/baeldung/README.md b/out/production/main330/com/baeldung/README.md deleted file mode 100644 index 51809b2882..0000000000 --- a/out/production/main330/com/baeldung/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [SHA-256 Hashing in Java](http://www.baeldung.com/sha-256-hashing-java) diff --git a/out/production/main330/log4j.properties b/out/production/main330/log4j.properties deleted file mode 100644 index 5fe42d854c..0000000000 --- a/out/production/main330/log4j.properties +++ /dev/null @@ -1,9 +0,0 @@ -# Set root logger level to DEBUG and its only appender to A1. -log4j.rootLogger=DEBUG, A1 - -# A1 is set to be a ConsoleAppender. -log4j.appender.A1=org.apache.log4j.ConsoleAppender - -# A1 uses PatternLayout. -log4j.appender.A1.layout=org.apache.log4j.PatternLayout -log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n diff --git a/out/production/main351/com/baeldung/produceimage/README.md b/out/production/main351/com/baeldung/produceimage/README.md deleted file mode 100644 index acd546598d..0000000000 --- a/out/production/main351/com/baeldung/produceimage/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant articles - -- [Returning an Image or a File with Spring](http://www.baeldung.com/spring-controller-return-image-file) diff --git a/out/production/main96/com/baeldung/git/README.md b/out/production/main96/com/baeldung/git/README.md deleted file mode 100644 index 7e6a597c28..0000000000 --- a/out/production/main96/com/baeldung/git/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [Injecting Git Information Into Spring](http://www.baeldung.com/spring-git-information) diff --git a/out/production/routing-in-play/views/index.scala.html b/out/production/routing-in-play/views/index.scala.html deleted file mode 100644 index 4539f5a10b..0000000000 --- a/out/production/routing-in-play/views/index.scala.html +++ /dev/null @@ -1,20 +0,0 @@ -@* - * This template takes a single argument, a String containing a - * message to display. - *@ -@(message: String) - -@* - * Call the `main` template with two arguments. The first - * argument is a `String` with the title of the page, the second - * argument is an `Html` object containing the body of the page. - *@ -@main("Welcome to Play") { - - @* - * Get an `Html` object by calling the built-in Play welcome - * template and passing a `String` message. - *@ - @play20.welcome(message, style = "Java") - -} diff --git a/out/production/routing-in-play/views/main.scala.html b/out/production/routing-in-play/views/main.scala.html deleted file mode 100644 index 9414f4be6e..0000000000 --- a/out/production/routing-in-play/views/main.scala.html +++ /dev/null @@ -1,23 +0,0 @@ -@* - * This template is called from the `index` template. This template - * handles the rendering of the page header and body tags. It takes - * two arguments, a `String` for the title of the page and an `Html` - * object to insert into the body of the page. - *@ -@(title: String)(content: Html) - - - - - @* Here's where we render the page title `String`. *@ - @title - - - - - - @* And here's where we render the `Html` object containing - * the page content. *@ - @content - - diff --git a/out/test/test95/com/baeldung/hexToAscii/README.md b/out/test/test/com/baeldung/hexToAscii/README.md similarity index 100% rename from out/test/test95/com/baeldung/hexToAscii/README.md rename to out/test/test/com/baeldung/hexToAscii/README.md diff --git a/out/test/test95/com/baeldung/java/conversion/README.md b/out/test/test/com/baeldung/java/conversion/README.md similarity index 100% rename from out/test/test95/com/baeldung/java/conversion/README.md rename to out/test/test/com/baeldung/java/conversion/README.md diff --git a/out/test/test/com/baeldung/stringisnumeric.zip b/out/test/test/com/baeldung/stringisnumeric.zip new file mode 100644 index 0000000000..b8a7b9b35a Binary files /dev/null and b/out/test/test/com/baeldung/stringisnumeric.zip differ diff --git a/out/test/test105/com/baeldung/cglib/proxy/README.md b/out/test/test105/com/baeldung/cglib/proxy/README.md deleted file mode 100644 index abeabc6162..0000000000 --- a/out/test/test105/com/baeldung/cglib/proxy/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant articles - -- [Introduction to cglib](http://www.baeldung.com/cglib) diff --git a/out/test/test143/com/baeldung/java9/README.MD b/out/test/test143/com/baeldung/java9/README.MD deleted file mode 100644 index 2f44a2336b..0000000000 --- a/out/test/test143/com/baeldung/java9/README.MD +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Artiles: -- [Filtering a Stream of Optionals in Java](http://www.baeldung.com/java-filter-stream-of-optional) diff --git a/out/test/test174/org/baeldung/hamcrest/README.md b/out/test/test174/org/baeldung/hamcrest/README.md deleted file mode 100644 index 7266ecda3a..0000000000 --- a/out/test/test174/org/baeldung/hamcrest/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [Testing with Hamcrest](http://www.baeldung.com/java-junit-hamcrest-guide) diff --git a/out/test/test191/com/baeldung/web/controller/README.md b/out/test/test191/com/baeldung/web/controller/README.md deleted file mode 100644 index 9923962dde..0000000000 --- a/out/test/test191/com/baeldung/web/controller/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [WebAppConfiguration in Spring Tests](http://www.baeldung.com/spring-webappconfiguration) diff --git a/out/test/test197/com/baeldung/java/nio2/README.md b/out/test/test197/com/baeldung/java/nio2/README.md deleted file mode 100644 index 569be82d27..0000000000 --- a/out/test/test197/com/baeldung/java/nio2/README.md +++ /dev/null @@ -1,11 +0,0 @@ -### Relevant Articles: -- [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api) -- [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path) -- [A Guide To NIO2 Asynchronous File Channel](http://www.baeldung.com/java-nio2-async-file-channel) -- [Guide to Selenium with JUnit / TestNG](http://www.baeldung.com/java-selenium-with-junit-and-testng) -- [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel) -- [A Guide To NIO2 FileVisitor](http://www.baeldung.com/java-nio2-file-visitor) -- [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute) -- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean) -- [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice) -- [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels) diff --git a/out/test/test237/META-INF/persistence.xml b/out/test/test237/META-INF/persistence.xml deleted file mode 100644 index 922aedbc39..0000000000 --- a/out/test/test237/META-INF/persistence.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - org.baeldung.persistence.model.Foo - org.baeldung.persistence.model.Bar - - - - - - - - - - - - - diff --git a/out/test/test95/org/baeldung/java/collections/README.md b/out/test/test95/org/baeldung/java/collections/README.md deleted file mode 100644 index 317d81fae7..0000000000 --- a/out/test/test95/org/baeldung/java/collections/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: -- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split) -- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets) diff --git a/out/test/test95/org/baeldung/java/lists/README.md b/out/test/test95/org/baeldung/java/lists/README.md deleted file mode 100644 index 2a1e8aeeaa..0000000000 --- a/out/test/test95/org/baeldung/java/lists/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality) diff --git a/out/test/test98/com/baeldung/applicationcontext/README.md b/out/test/test98/com/baeldung/applicationcontext/README.md deleted file mode 100644 index 211007e0cf..0000000000 --- a/out/test/test98/com/baeldung/applicationcontext/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: -- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets) -- [Intro to the Spring ClassPathXmlApplicationContext](http://www.baeldung.com/spring-classpathxmlapplicationcontext) diff --git a/out/test/test98/com/baeldung/beanfactory/README.md b/out/test/test98/com/baeldung/beanfactory/README.md deleted file mode 100644 index cff20a184b..0000000000 --- a/out/test/test98/com/baeldung/beanfactory/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [Guide to the Spring BeanFactory](http://www.baeldung.com/spring-beanfactory) diff --git a/enterprise-patterns/README.md b/parent-boot-1/README.md similarity index 100% rename from enterprise-patterns/README.md rename to parent-boot-1/README.md diff --git a/parent-boot-1/pom.xml b/parent-boot-1/pom.xml new file mode 100644 index 0000000000..7742841d07 --- /dev/null +++ b/parent-boot-1/pom.xml @@ -0,0 +1,55 @@ + + 4.0.0 + parent-boot-1 + 0.0.1-SNAPSHOT + pom + Parent for all Spring Boot 1.x modules + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + org.springframework.boot + spring-boot-dependencies + 1.5.15.RELEASE + pom + import + + + + + + io.rest-assured + rest-assured + ${rest-assured.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + 1.5.15.RELEASE + + + + + + + 3.1.0 + + + \ No newline at end of file diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index a9c54dece9..de6cb5d068 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -1,31 +1,33 @@ + 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 parent-boot-2 0.0.1-SNAPSHOT pom - Parent Boot 2 - Parent for all spring boot 2 modules + Parent for all Spring Boot 2 modules - org.springframework.boot - spring-boot-starter-parent - 2.0.1.RELEASE - + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + org.springframework.boot + spring-boot-dependencies + 2.0.4.RELEASE + pom + import + + + - - junit - junit - test - io.rest-assured rest-assured - ${rest-assured.version} - +
    org.springframework.boot spring-boot-starter-test @@ -33,74 +35,34 @@
    - - - - 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 - **/*LiveTest.java - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - - - - - + + + + + org.springframework.boot + spring-boot-maven-plugin + 2.0.4.RELEASE + + + + + - integration + thin-jar - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - **/*LiveTest.java - **/AutoconfigurationTest.java - **/*UnitTest.java - - - **/*IntegrationTest.java - */EthControllerTestOne.java - **/*IntTest.java - **/*EntryPointsTest.java - - - - - - - json - - + org.springframework.boot + spring-boot-maven-plugin + + + + org.springframework.boot.experimental + spring-boot-thin-layout + ${thin.version} + + @@ -108,13 +70,9 @@ - UTF-8 - UTF-8 - 1.8 3.1.0 - 1.8 - 1.8 + 1.0.11.RELEASE
    \ No newline at end of file diff --git a/parent-boot-5/pom.xml b/parent-boot-5/pom.xml deleted file mode 100644 index 32bb2eab04..0000000000 --- a/parent-boot-5/pom.xml +++ /dev/null @@ -1,122 +0,0 @@ - - 4.0.0 - com.baeldung - parent-boot-5 - 0.0.1-SNAPSHOT - pom - Parent Boot 5 - Parent for all spring boot 1.5 modules - - - org.springframework.boot - spring-boot-starter-parent - 1.5.10.RELEASE - - - - - - junit - junit - test - - - io.rest-assured - rest-assured - ${rest-assured.version} - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/*LiveTest.java - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - - - - - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - **/*LiveTest.java - **/AutoconfigurationTest.java - **/*UnitTest.java - - - **/*IntegrationTest.java - */EthControllerTestOne.java - **/*IntTest.java - **/*EntryPointsTest.java - - - - - - - json - - - - - - - - - - UTF-8 - UTF-8 - 1.8 - 3.0.6 - - 2.20.1 - 3.7.0 - 1.8 - 1.8 - - - \ No newline at end of file diff --git a/parent-java/pom.xml b/parent-java/pom.xml index 40df31d1c7..86be34d508 100644 --- a/parent-java/pom.xml +++ b/parent-java/pom.xml @@ -1,5 +1,5 @@ + 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 parent-java diff --git a/parent-kotlin/pom.xml b/parent-kotlin/pom.xml new file mode 100644 index 0000000000..7fd18e4fa4 --- /dev/null +++ b/parent-kotlin/pom.xml @@ -0,0 +1,194 @@ + + + 4.0.0 + parent-kotlin + pom + parent-kotlin + Parent for all kotlin modules + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + jcenter + http://jcenter.bintray.com + + + kotlin-ktor + https://dl.bintray.com/kotlin/ktor/ + + + + + + + org.springframework.boot + spring-boot-dependencies + 2.0.1.RELEASE + pom + import + + + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-reflect + ${kotlin.version} + + + + org.jetbrains.kotlinx + kotlinx-coroutines-core + ${kotlinx.version} + + + + io.ktor + ktor-server-netty + ${ktor.io.version} + + + io.ktor + ktor-gson + ${ktor.io.version} + + + + org.jetbrains.kotlin + kotlin-test-junit + ${kotlin.version} + test + + + + + + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin.version} + + + compile + + compile + + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/main/java + + ${java.version} + + + + test-compile + + test-compile + + + + ${project.basedir}/src/test/kotlin + ${project.basedir}/src/test/java + + ${java.version} + + + + + + spring + + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + + + + + default-compile + none + + + + default-testCompile + none + + + java-compile + compile + + compile + + + + java-test-compile + test-compile + + testCompile + + + + + + maven-failsafe-plugin + ${maven-failsafe-plugin.version} + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + + + + + junit5 + + integration-test + verify + + + + **/*Test5.java + + + + + + + + + + 1.2.61 + 0.25.0 + 0.9.3 + 3.11.0 + 1.2.0 + + diff --git a/parent-boot-5/README.md b/parent-spring-4/README.md similarity index 100% rename from parent-boot-5/README.md rename to parent-spring-4/README.md diff --git a/parent-spring-4/pom.xml b/parent-spring-4/pom.xml new file mode 100644 index 0000000000..d1b1298013 --- /dev/null +++ b/parent-spring-4/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + com.baeldung + parent-spring-4 + 0.0.1-SNAPSHOT + pom + parent-spring-4 + Parent for all spring 4 core modules + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.springframework + spring-core + ${spring.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + + + + + 4.3.17.RELEASE + 5.0.2 + + + \ No newline at end of file diff --git a/parent-spring/README.md b/parent-spring-5/README.md similarity index 100% rename from parent-spring/README.md rename to parent-spring-5/README.md diff --git a/parent-spring-5/pom.xml b/parent-spring-5/pom.xml new file mode 100644 index 0000000000..6a15f38884 --- /dev/null +++ b/parent-spring-5/pom.xml @@ -0,0 +1,39 @@ + + 4.0.0 + com.baeldung + parent-spring-5 + 0.0.1-SNAPSHOT + pom + parent-spring-5 + Parent for all spring 5 core modules + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.springframework + spring-core + ${spring.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + + + + + 5.0.6.RELEASE + 5.0.2 + 2.9.6 + 2.9.6 + 5.0.6.RELEASE + + + \ No newline at end of file diff --git a/parent-spring/pom.xml b/parent-spring/pom.xml deleted file mode 100644 index 547c43dc27..0000000000 --- a/parent-spring/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - 4.0.0 - com.baeldung - parent-spring - 0.0.1-SNAPSHOT - pom - parent-spring - Parent for all spring core modules - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - org.springframework - spring-core - ${spring.version} - - - org.junit.jupiter - junit-jupiter-engine - ${junit.jupiter.version} - test - - - - - 4.3.6.RELEASE - 5.0.2 - - - \ No newline at end of file diff --git a/patterns/README.md b/patterns/README.md index df39b39224..221cba6456 100644 --- a/patterns/README.md +++ b/patterns/README.md @@ -1,7 +1,8 @@ -###Relevant Articles: +### Relevant Articles: - [A Guide to the Front Controller Pattern in Java](http://www.baeldung.com/java-front-controller-pattern) - [Introduction to Intercepting Filter Pattern in Java](http://www.baeldung.com/intercepting-filter-pattern-in-java) - [Implementing the Template Method Pattern in Java](http://www.baeldung.com/java-template-method-pattern) - [Chain of Responsibility Design Pattern in Java](http://www.baeldung.com/chain-of-responsibility-pattern) - [The Command Pattern in Java](http://www.baeldung.com/java-command-pattern) +- [The DAO Pattern in Java](http://www.baeldung.com/java-dao-pattern) diff --git a/patterns/design-patterns/README.md b/patterns/design-patterns/README.md index fb80f4bd6a..75f7cec73a 100644 --- a/patterns/design-patterns/README.md +++ b/patterns/design-patterns/README.md @@ -8,4 +8,7 @@ - [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern) - [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking) - [Composite Design Pattern in Java](http://www.baeldung.com/java-composite-pattern) - +- [Visitor Design Pattern in Java](http://www.baeldung.com/java-visitor-pattern) +- [The DAO Pattern in Java](http://www.baeldung.com/java-dao-pattern) +- [Interpreter Design Pattern in Java](http://www.baeldung.com/java-interpreter-pattern) +- [State Design Pattern in Java](https://www.baeldung.com/java-state-design-pattern) diff --git a/patterns/design-patterns/pom.xml b/patterns/design-patterns/pom.xml index 87db08ab32..dc2631b36e 100644 --- a/patterns/design-patterns/pom.xml +++ b/patterns/design-patterns/pom.xml @@ -1,42 +1,46 @@ - + 4.0.0 - com.baeldung design-patterns 1.0 jar com.baeldung - patterns-parent + patterns 1.0.0-SNAPSHOT .. - junit - junit - 4.12 - test - - - org.hamcrest - hamcrest-core - 1.3 + org.assertj + assertj-core + ${assertj-core.version} test - org.assertj - assertj-core - 3.8.0 - test + javax + javaee-api + ${javaee.version} - + + org.hibernate + hibernate-core + ${hibernate-core.version} + + + mysql + mysql-connector-java + ${mysql-connector.version} + jar + + log4j log4j ${log4j.version} - + com.googlecode.grep4j grep4j ${grep4j.version} @@ -46,7 +50,10 @@ UTF-8 1.8 1.8 - 1.2.17 - 1.8.7 + 1.8.7 + 3.9.1 + 8.0 + 5.2.16.Final + 6.0.6
    -
    \ No newline at end of file + diff --git a/patterns/design-patterns/src/main/java/com/baeldung/daopattern/application/UserApplication.java b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/application/UserApplication.java new file mode 100644 index 0000000000..3a5c049992 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/application/UserApplication.java @@ -0,0 +1,53 @@ +package com.baeldung.daopattern.application; + +import com.baeldung.daopattern.config.JpaEntityManagerFactory; +import com.baeldung.daopattern.daos.Dao; +import com.baeldung.daopattern.daos.JpaUserDao; +import com.baeldung.daopattern.entities.User; +import java.util.List; +import java.util.Optional; +import javax.persistence.EntityManager; +import javax.persistence.Persistence; + +public class UserApplication { + + private static JpaUserDao jpaUserDao; + + public static void main(String[] args) { + User user1 = getUser(1); + System.out.println(user1); + updateUser(user1, new String[]{"John", "john@domain.com"}); + saveUser(new User("Monica", "monica@domain.com")); + deleteUser(getUser(2)); + getAllUsers().forEach(user -> System.out.println(user.getName())); + } + + private static class JpaUserDaoHolder { + private static final JpaUserDao jpaUserDao = new JpaUserDao(new JpaEntityManagerFactory().getEntityManager()); + } + + public static Dao getJpaUserDao() { + return JpaUserDaoHolder.jpaUserDao; + } + + public static User getUser(long id) { + Optional user = getJpaUserDao().get(id); + return user.orElseGet(()-> {return new User("non-existing user", "no-email");}); + } + + public static List getAllUsers() { + return getJpaUserDao().getAll(); + } + + public static void updateUser(User user, String[] params){ + getJpaUserDao().update(user, params); + } + + public static void saveUser(User user) { + getJpaUserDao().save(user); + } + + public static void deleteUser(User user) { + getJpaUserDao().delete(user); + } +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/daopattern/config/JpaEntityManagerFactory.java b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/config/JpaEntityManagerFactory.java new file mode 100644 index 0000000000..11718d5612 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/config/JpaEntityManagerFactory.java @@ -0,0 +1,65 @@ +package com.baeldung.daopattern.config; + +import com.baeldung.daopattern.entities.User; +import com.mysql.cj.jdbc.MysqlDataSource; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; +import javax.persistence.EntityManager; +import javax.sql.DataSource; +import javax.persistence.EntityManagerFactory; +import javax.persistence.spi.PersistenceUnitInfo; +import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; +import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor; + +public class JpaEntityManagerFactory { + + private final String DB_URL = "jdbc:mysql://databaseurl"; + private final String DB_USER_NAME = "username"; + private final String DB_PASSWORD = "password"; + + public EntityManager getEntityManager() { + return getEntityManagerFactory().createEntityManager(); + } + + protected EntityManagerFactory getEntityManagerFactory() { + PersistenceUnitInfo persistenceUnitInfo = getPersistenceUnitInfo(getClass().getSimpleName()); + Map configuration = new HashMap<>(); + return new EntityManagerFactoryBuilderImpl(new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration) + .build(); + } + + protected PersistenceUnitInfoImpl getPersistenceUnitInfo(String name) { + return new PersistenceUnitInfoImpl(name, getEntityClassNames(), getProperties()); + } + + protected List getEntityClassNames() { + return Arrays.asList(getEntities()) + .stream() + .map(Class::getName) + .collect(Collectors.toList()); + } + + protected Properties getProperties() { + Properties properties = new Properties(); + properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); + properties.put("hibernate.id.new_generator_mappings", false); + properties.put("hibernate.connection.datasource", getMysqlDataSource()); + return properties; + } + + protected Class[] getEntities() { + return new Class[]{User.class}; + } + + protected DataSource getMysqlDataSource() { + MysqlDataSource mysqlDataSource = new MysqlDataSource(); + mysqlDataSource.setURL(DB_URL); + mysqlDataSource.setUser(DB_USER_NAME); + mysqlDataSource.setPassword(DB_PASSWORD); + return mysqlDataSource; + } +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/daopattern/config/PersistenceUnitInfoImpl.java b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/config/PersistenceUnitInfoImpl.java new file mode 100644 index 0000000000..f3277da0cf --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/config/PersistenceUnitInfoImpl.java @@ -0,0 +1,130 @@ +package com.baeldung.daopattern.config; + +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import javax.sql.DataSource; +import javax.persistence.SharedCacheMode; +import javax.persistence.ValidationMode; +import javax.persistence.spi.ClassTransformer; +import javax.persistence.spi.PersistenceUnitInfo; +import javax.persistence.spi.PersistenceUnitTransactionType; +import org.hibernate.jpa.HibernatePersistenceProvider; + +public class PersistenceUnitInfoImpl implements PersistenceUnitInfo { + + public static final String JPA_VERSION = "2.1"; + private final String persistenceUnitName; + private PersistenceUnitTransactionType transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; + private final List managedClassNames; + private final List mappingFileNames = new ArrayList<>(); + private final Properties properties; + private DataSource jtaDataSource; + private DataSource nonJtaDataSource; + + public PersistenceUnitInfoImpl(String persistenceUnitName, List managedClassNames, Properties properties) { + this.persistenceUnitName = persistenceUnitName; + this.managedClassNames = managedClassNames; + this.properties = properties; + } + + @Override + public String getPersistenceUnitName() { + return persistenceUnitName; + } + + @Override + public String getPersistenceProviderClassName() { + return HibernatePersistenceProvider.class.getName(); + } + + @Override + public PersistenceUnitTransactionType getTransactionType() { + return transactionType; + } + + @Override + public DataSource getJtaDataSource() { + return jtaDataSource; + } + + public PersistenceUnitInfoImpl setJtaDataSource(DataSource jtaDataSource) { + this.jtaDataSource = jtaDataSource; + this.nonJtaDataSource = null; + transactionType = PersistenceUnitTransactionType.JTA; + return this; + } + + @Override + public DataSource getNonJtaDataSource() { + return nonJtaDataSource; + } + + public PersistenceUnitInfoImpl setNonJtaDataSource(DataSource nonJtaDataSource) { + this.nonJtaDataSource = nonJtaDataSource; + this.jtaDataSource = null; + transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; + return this; + } + + @Override + public List getMappingFileNames() { + return mappingFileNames; + } + + @Override + public List getJarFileUrls() { + return Collections.emptyList(); + } + + @Override + public URL getPersistenceUnitRootUrl() { + return null; + } + + @Override + public List getManagedClassNames() { + return managedClassNames; + } + + @Override + public boolean excludeUnlistedClasses() { + return false; + } + + @Override + public SharedCacheMode getSharedCacheMode() { + return SharedCacheMode.UNSPECIFIED; + } + + @Override + public ValidationMode getValidationMode() { + return ValidationMode.AUTO; + } + + public Properties getProperties() { + return properties; + } + + @Override + public String getPersistenceXMLSchemaVersion() { + return JPA_VERSION; + } + + @Override + public ClassLoader getClassLoader() { + return Thread.currentThread().getContextClassLoader(); + } + + @Override + public void addTransformer(ClassTransformer transformer) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public ClassLoader getNewTempClassLoader() { + return null; + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/daopattern/daos/Dao.java b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/daos/Dao.java new file mode 100644 index 0000000000..35aa763097 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/daos/Dao.java @@ -0,0 +1,17 @@ +package com.baeldung.daopattern.daos; + +import java.util.List; +import java.util.Optional; + +public interface Dao { + + Optional get(long id); + + List getAll(); + + void save(T t); + + void update(T t, String[] params); + + void delete(T t); +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/daopattern/daos/JpaUserDao.java b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/daos/JpaUserDao.java new file mode 100644 index 0000000000..f4d80c0ee9 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/daos/JpaUserDao.java @@ -0,0 +1,60 @@ +package com.baeldung.daopattern.daos; + +import com.baeldung.daopattern.entities.User; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Consumer; +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.persistence.Query; + +public class JpaUserDao implements Dao { + + private final EntityManager entityManager; + + public JpaUserDao(EntityManager entityManager) { + this.entityManager = entityManager; + } + + @Override + public Optional get(long id) { + return Optional.ofNullable(entityManager.find(User.class, id)); + } + + @Override + public List getAll() { + Query query = entityManager.createQuery("SELECT e FROM User e"); + return query.getResultList(); + } + + @Override + public void save(User user) { + executeInsideTransaction(entityManager -> entityManager.persist(user)); + } + + @Override + public void update(User user, String[] params) { + user.setName(Objects.requireNonNull(params[0], "Name cannot be null")); + user.setEmail(Objects.requireNonNull(params[1], "Email cannot be null")); + executeInsideTransaction(entityManager -> entityManager.merge(user)); + } + + @Override + public void delete(User user) { + executeInsideTransaction(entityManager -> entityManager.remove(user)); + } + + private void executeInsideTransaction(Consumer action) { + final EntityTransaction tx = entityManager.getTransaction(); + try { + tx.begin(); + action.accept(entityManager); + tx.commit(); + } + catch (RuntimeException e) { + tx.rollback(); + throw e; + } + } +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/daopattern/daos/UserDao.java b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/daos/UserDao.java new file mode 100644 index 0000000000..2fd4047772 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/daos/UserDao.java @@ -0,0 +1,44 @@ +package com.baeldung.daopattern.daos; + +import com.baeldung.daopattern.entities.User; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +public class UserDao implements Dao { + + private List users = new ArrayList<>(); + + public UserDao() { + users.add(new User("John", "john@domain.com")); + users.add(new User("Susan", "susan@domain.com")); + } + + @Override + public Optional get(long id) { + return Optional.ofNullable(users.get((int) id)); + } + + @Override + public List getAll() { + return users; + } + + @Override + public void save(User user) { + users.add(user); + } + + @Override + public void update(User user, String[] params) { + user.setName(Objects.requireNonNull(params[0], "Name cannot be null")); + user.setEmail(Objects.requireNonNull(params[1], "Email cannot be null")); + users.add(user); + } + + @Override + public void delete(User user) { + users.remove(user); + } +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/daopattern/entities/User.java b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/entities/User.java new file mode 100644 index 0000000000..58d8ffb28b --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/entities/User.java @@ -0,0 +1,45 @@ +package com.baeldung.daopattern.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + private String name; + private String email; + + public User(){} + + public User(String name, String email) { + this.name = name; + this.email = email; + } + + public void setName(String name) { + this.name = name; + } + + public void setEmail(String email) { + this.email = email; + } + + public long getId() { + return id; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/interpreter/Context.java b/patterns/design-patterns/src/main/java/com/baeldung/interpreter/Context.java new file mode 100644 index 0000000000..f2416988ea --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/interpreter/Context.java @@ -0,0 +1,107 @@ +package com.baeldung.interpreter; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +class Context { + + private static Map> tables = new HashMap<>(); + + static { + List list = new ArrayList<>(); + list.add(new Row("John", "Doe")); + list.add(new Row("Jan", "Kowalski")); + list.add(new Row("Dominic", "Doom")); + + tables.put("people", list); + } + + private String table; + private String column; + + /** + * Index of column to be shown in result. + * Calculated in {@link #setColumnMapper()} + */ + private int colIndex = -1; + + /** + * Default setup, used for clearing the context for next queries. + * See {@link Context#clear()} + */ + private static final Predicate matchAnyString = s -> s.length() > 0; + private static final Function> matchAllColumns = Stream::of; + /** + * Varies based on setup in subclasses of {@link Expression} + */ + private Predicate whereFilter = matchAnyString; + private Function> columnMapper = matchAllColumns; + + void setColumn(String column) { + this.column = column; + setColumnMapper(); + } + + void setTable(String table) { + this.table = table; + } + + void setFilter(Predicate filter) { + whereFilter = filter; + } + + /** + * Clears the context to defaults. + * No filters, match all columns. + */ + void clear() { + column = ""; + columnMapper = matchAllColumns; + whereFilter = matchAnyString; + } + + List search() { + + List result = tables.entrySet() + .stream() + .filter(entry -> entry.getKey().equalsIgnoreCase(table)) + .flatMap(entry -> Stream.of(entry.getValue())) + .flatMap(Collection::stream) + .map(Row::toString) + .flatMap(columnMapper) + .filter(whereFilter) + .collect(Collectors.toList()); + + clear(); + + return result; + } + + /** + * Sets column mapper based on {@link #column} attribute. + * Note: If column is unknown, will remain to look for all columns. + */ + private void setColumnMapper() { + switch (column) { + case "*": + colIndex = -1; + break; + case "name": + colIndex = 0; + break; + case "surname": + colIndex = 1; + break; + } + if (colIndex != -1) { + columnMapper = s -> Stream.of(s.split(" ")[colIndex]); + } + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/interpreter/Expression.java b/patterns/design-patterns/src/main/java/com/baeldung/interpreter/Expression.java new file mode 100644 index 0000000000..7f0893e719 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/interpreter/Expression.java @@ -0,0 +1,7 @@ +package com.baeldung.interpreter; + +import java.util.List; + +interface Expression { + List interpret(Context ctx); +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/interpreter/From.java b/patterns/design-patterns/src/main/java/com/baeldung/interpreter/From.java new file mode 100644 index 0000000000..d0690e3e85 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/interpreter/From.java @@ -0,0 +1,27 @@ +package com.baeldung.interpreter; + +import java.util.List; + +class From implements Expression { + + private String table; + private Where where; + + From(String table) { + this.table = table; + } + + From(String table, Where where) { + this.table = table; + this.where = where; + } + + @Override + public List interpret(Context ctx) { + ctx.setTable(table); + if (where == null) { + return ctx.search(); + } + return where.interpret(ctx); + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/interpreter/InterpreterDemo.java b/patterns/design-patterns/src/main/java/com/baeldung/interpreter/InterpreterDemo.java new file mode 100644 index 0000000000..9b37037bb9 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/interpreter/InterpreterDemo.java @@ -0,0 +1,23 @@ +package com.baeldung.interpreter; + +import java.util.List; + + +public class InterpreterDemo { + + public static void main(String[] args) { + + Expression query = new Select("name", new From("people")); + Context ctx = new Context(); + List result = query.interpret(ctx); + System.out.println(result); + + Expression query2 = new Select("*", new From("people")); + List result2 = query2.interpret(ctx); + System.out.println(result2); + + Expression query3 = new Select("name", new From("people", new Where(name -> name.toLowerCase().startsWith("d")))); + List result3 = query3.interpret(ctx); + System.out.println(result3); + } +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/interpreter/Row.java b/patterns/design-patterns/src/main/java/com/baeldung/interpreter/Row.java new file mode 100644 index 0000000000..00fd2d993a --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/interpreter/Row.java @@ -0,0 +1,17 @@ +package com.baeldung.interpreter; + +class Row { + + private String name; + private String surname; + + Row(String name, String surname) { + this.name = name; + this.surname = surname; + } + + @Override + public String toString() { + return name + " " + surname; + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/interpreter/Select.java b/patterns/design-patterns/src/main/java/com/baeldung/interpreter/Select.java new file mode 100644 index 0000000000..f235ce2a87 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/interpreter/Select.java @@ -0,0 +1,20 @@ +package com.baeldung.interpreter; + +import java.util.List; + +class Select implements Expression { + + private String column; + private From from; + + Select(String column, From from) { + this.column = column; + this.from = from; + } + + @Override + public List interpret(Context ctx) { + ctx.setColumn(column); + return from.interpret(ctx); + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/interpreter/Where.java b/patterns/design-patterns/src/main/java/com/baeldung/interpreter/Where.java new file mode 100644 index 0000000000..b31fa54cff --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/interpreter/Where.java @@ -0,0 +1,19 @@ +package com.baeldung.interpreter; + +import java.util.List; +import java.util.function.Predicate; + +class Where implements Expression { + + private Predicate filter; + + Where(Predicate filter) { + this.filter = filter; + } + + @Override + public List interpret(Context ctx) { + ctx.setFilter(filter); + return ctx.search(); + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/state/DeliveredState.java b/patterns/design-patterns/src/main/java/com/baeldung/state/DeliveredState.java new file mode 100644 index 0000000000..9f5e4d8fc4 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/state/DeliveredState.java @@ -0,0 +1,25 @@ +package com.baeldung.state; + +public class DeliveredState implements PackageState { + + @Override + public void next(Package pkg) { + pkg.setState(new ReceivedState()); + } + + @Override + public void prev(Package pkg) { + pkg.setState(new OrderedState()); + } + + @Override + public void printStatus() { + System.out.println("Package delivered to post office, not received yet."); + } + + @Override + public String toString() { + return "DeliveredState{}"; + } + +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/state/OrderedState.java b/patterns/design-patterns/src/main/java/com/baeldung/state/OrderedState.java new file mode 100644 index 0000000000..0642c4c73c --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/state/OrderedState.java @@ -0,0 +1,24 @@ +package com.baeldung.state; + +public class OrderedState implements PackageState { + + @Override + public void next(Package pkg) { + pkg.setState(new DeliveredState()); + } + + @Override + public void prev(Package pkg) { + System.out.println("The package is in it's root state."); + } + + @Override + public void printStatus() { + System.out.println("Package ordered, not delivered to the office yet."); + } + + @Override + public String toString() { + return "OrderedState{}"; + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/state/Package.java b/patterns/design-patterns/src/main/java/com/baeldung/state/Package.java new file mode 100644 index 0000000000..f3dfbb3fa7 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/state/Package.java @@ -0,0 +1,26 @@ +package com.baeldung.state; + +public class Package { + + private PackageState state = new OrderedState(); + + public PackageState getState() { + return state; + } + + public void setState(PackageState state) { + this.state = state; + } + + public void previousState() { + state.prev(this); + } + + public void nextState() { + state.next(this); + } + + public void printStatus() { + state.printStatus(); + } +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/state/PackageState.java b/patterns/design-patterns/src/main/java/com/baeldung/state/PackageState.java new file mode 100644 index 0000000000..d6656c78ac --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/state/PackageState.java @@ -0,0 +1,10 @@ +package com.baeldung.state; + +public interface PackageState { + + void next(Package pkg); + + void prev(Package pkg); + + void printStatus(); +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/state/ReceivedState.java b/patterns/design-patterns/src/main/java/com/baeldung/state/ReceivedState.java new file mode 100644 index 0000000000..84136fa48e --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/state/ReceivedState.java @@ -0,0 +1,24 @@ +package com.baeldung.state; + +public class ReceivedState implements PackageState { + + @Override + public void next(Package pkg) { + System.out.println("This package is already received by a client."); + } + + @Override + public void prev(Package pkg) { + pkg.setState(new DeliveredState()); + } + + @Override + public void printStatus() { + System.out.println("Package was received by client."); + } + + @Override + public String toString() { + return "ReceivedState{}"; + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/state/StateDemo.java b/patterns/design-patterns/src/main/java/com/baeldung/state/StateDemo.java new file mode 100644 index 0000000000..1a63ea3ddf --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/state/StateDemo.java @@ -0,0 +1,19 @@ +package com.baeldung.state; + +public class StateDemo { + + public static void main(String[] args) { + + Package pkg = new Package(); + pkg.printStatus(); + + pkg.nextState(); + pkg.printStatus(); + + pkg.nextState(); + pkg.printStatus(); + + pkg.nextState(); + pkg.printStatus(); + } +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/visitor/Document.java b/patterns/design-patterns/src/main/java/com/baeldung/visitor/Document.java new file mode 100644 index 0000000000..575146a8e0 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/visitor/Document.java @@ -0,0 +1,20 @@ +package com.baeldung.visitor; + +import java.util.ArrayList; +import java.util.List; + +public class Document extends Element { + + List elements = new ArrayList<>(); + + public Document(String uuid) { + super(uuid); + } + + @Override + public void accept(Visitor v) { + for (Element e : this.elements) { + e.accept(v); + } + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/visitor/Element.java b/patterns/design-patterns/src/main/java/com/baeldung/visitor/Element.java new file mode 100644 index 0000000000..70c96c99e1 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/visitor/Element.java @@ -0,0 +1,12 @@ +package com.baeldung.visitor; + +public abstract class Element { + + public String uuid; + + public Element(String uuid) { + this.uuid = uuid; + } + + public abstract void accept(Visitor v); +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/visitor/ElementVisitor.java b/patterns/design-patterns/src/main/java/com/baeldung/visitor/ElementVisitor.java new file mode 100644 index 0000000000..f8af42d554 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/visitor/ElementVisitor.java @@ -0,0 +1,14 @@ +package com.baeldung.visitor; + +public class ElementVisitor implements Visitor { + + @Override + public void visit(XmlElement xe) { + System.out.println("processing xml element with uuid: " + xe.uuid); + } + + @Override + public void visit(JsonElement je) { + System.out.println("processing json element with uuid: " + je.uuid); + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/visitor/JsonElement.java b/patterns/design-patterns/src/main/java/com/baeldung/visitor/JsonElement.java new file mode 100644 index 0000000000..a65fe277f1 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/visitor/JsonElement.java @@ -0,0 +1,12 @@ +package com.baeldung.visitor; + +public class JsonElement extends Element { + + public JsonElement(String uuid) { + super(uuid); + } + + public void accept(Visitor v) { + v.visit(this); + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/visitor/Visitor.java b/patterns/design-patterns/src/main/java/com/baeldung/visitor/Visitor.java new file mode 100644 index 0000000000..1cd94911a3 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/visitor/Visitor.java @@ -0,0 +1,8 @@ +package com.baeldung.visitor; + +public interface Visitor { + + void visit(XmlElement xe); + + void visit(JsonElement je); +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/visitor/VisitorDemo.java b/patterns/design-patterns/src/main/java/com/baeldung/visitor/VisitorDemo.java new file mode 100644 index 0000000000..ee3436616a --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/visitor/VisitorDemo.java @@ -0,0 +1,23 @@ +package com.baeldung.visitor; + +import java.util.UUID; + +public class VisitorDemo { + + public static void main(String[] args) { + + Visitor v = new ElementVisitor(); + + Document d = new Document(generateUuid()); + d.elements.add(new JsonElement(generateUuid())); + d.elements.add(new JsonElement(generateUuid())); + d.elements.add(new XmlElement(generateUuid())); + + d.accept(v); + } + + private static String generateUuid() { + return UUID.randomUUID() + .toString(); + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/visitor/XmlElement.java b/patterns/design-patterns/src/main/java/com/baeldung/visitor/XmlElement.java new file mode 100644 index 0000000000..41998de428 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/visitor/XmlElement.java @@ -0,0 +1,12 @@ +package com.baeldung.visitor; + +public class XmlElement extends Element { + + public XmlElement(String uuid) { + super(uuid); + } + + public void accept(Visitor v) { + v.visit(this); + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/resources/META-INF/persistence.xml b/patterns/design-patterns/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..e67a25e467 --- /dev/null +++ b/patterns/design-patterns/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,17 @@ + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.pattern.daopattern.entities.User + + + + + + + + + + + + diff --git a/patterns/design-patterns/src/main/resources/log4jstructuraldp.properties b/patterns/design-patterns/src/main/resources/log4jstructuraldp.properties new file mode 100644 index 0000000000..5bc2bfe4b9 --- /dev/null +++ b/patterns/design-patterns/src/main/resources/log4jstructuraldp.properties @@ -0,0 +1,9 @@ + +# Root logger +log4j.rootLogger=INFO, file, stdout + +# Write to console +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java b/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java new file mode 100644 index 0000000000..824b104f81 --- /dev/null +++ b/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java @@ -0,0 +1,42 @@ +package com.baeldung.chainofresponsibility; + +import org.junit.Test; +import com.baeldung.pattern.chainofresponsibility.AuthenticationProcessor; +import com.baeldung.pattern.chainofresponsibility.OAuthAuthenticationProcessor; +import com.baeldung.pattern.chainofresponsibility.OAuthTokenProvider; +import com.baeldung.pattern.chainofresponsibility.UsernamePasswordProvider; +import com.baeldung.pattern.chainofresponsibility.SamlAuthenticationProvider; +import com.baeldung.pattern.chainofresponsibility.UsernamePasswordAuthenticationProcessor; +import static org.junit.Assert.assertTrue; + +public class ChainOfResponsibilityIntegrationTest { + + private static AuthenticationProcessor getChainOfAuthProcessor() { + + AuthenticationProcessor oAuthProcessor = new OAuthAuthenticationProcessor(null); + AuthenticationProcessor unamePasswordProcessor = new UsernamePasswordAuthenticationProcessor(oAuthProcessor); + return unamePasswordProcessor; + } + + @Test + public void givenOAuthProvider_whenCheckingAuthorized_thenSuccess() { + AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor(); + boolean isAuthorized = authProcessorChain.isAuthorized(new OAuthTokenProvider()); + assertTrue(isAuthorized); + } + + @Test + public void givenUsernamePasswordProvider_whenCheckingAuthorized_thenSuccess() { + AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor(); + boolean isAuthorized = authProcessorChain.isAuthorized(new UsernamePasswordProvider()); + assertTrue(isAuthorized); + } + + @Test + public void givenSamlAuthProvider_whenCheckingAuthorized_thenFailure() { + AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor(); + boolean isAuthorized = authProcessorChain.isAuthorized(new SamlAuthenticationProvider()); + assertTrue(!isAuthorized); + } + +} diff --git a/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityTest.java b/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityTest.java deleted file mode 100644 index a84f9dd8e5..0000000000 --- a/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.pattern.chainofresponsibility; - -import org.junit.Test; - -import static org.junit.Assert.assertTrue; - -public class ChainOfResponsibilityTest { - - private static AuthenticationProcessor getChainOfAuthProcessor() { - - AuthenticationProcessor oAuthProcessor = new OAuthAuthenticationProcessor(null); - AuthenticationProcessor unamePasswordProcessor = new UsernamePasswordAuthenticationProcessor(oAuthProcessor); - return unamePasswordProcessor; - } - - @Test - public void givenOAuthProvider_whenCheckingAuthorized_thenSuccess() { - AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor(); - boolean isAuthorized = authProcessorChain.isAuthorized(new OAuthTokenProvider()); - assertTrue(isAuthorized); - } - - @Test - public void givenUsernamePasswordProvider_whenCheckingAuthorized_thenSuccess() { - AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor(); - boolean isAuthorized = authProcessorChain.isAuthorized(new UsernamePasswordProvider()); - assertTrue(isAuthorized); - } - - @Test - public void givenSamlAuthProvider_whenCheckingAuthorized_thenFailure() { - AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor(); - boolean isAuthorized = authProcessorChain.isAuthorized(new SamlAuthenticationProvider()); - assertTrue(!isAuthorized); - } - -} diff --git a/patterns/design-patterns/src/test/java/com/baeldung/daopattern/test/UserDaoUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/daopattern/test/UserDaoUnitTest.java new file mode 100644 index 0000000000..683e626600 --- /dev/null +++ b/patterns/design-patterns/src/test/java/com/baeldung/daopattern/test/UserDaoUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.daopattern.test; + +import com.baeldung.daopattern.daos.UserDao; +import com.baeldung.daopattern.entities.User; +import java.util.List; +import java.util.Optional; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +public class UserDaoUnitTest { + + private static UserDao userDao; + + + @BeforeClass + public static void setUpUserDaoInstance() { + userDao = new UserDao(); + } + + @Test + public void givenUserDaoInstance_whenCalledget_thenOneAssertion() { + assertThat(userDao.get(0)).isInstanceOf(Optional.class); + } + + @Test + public void givenUserDaoInstance_whenCalledgetAll_thenOneAssertion() { + assertThat(userDao.getAll()).isInstanceOf(List.class); + } + + @Test + public void givenUserDaoInstance_whenCalledupdate_thenTwoAssertions() { + User user = new User("Julie", "julie@domain.com"); + userDao.update(user, new String[] {"Julie", "julie@domain.com"}); + assertThat(userDao.get(2).get().getName()).isEqualTo("Julie"); + assertThat(userDao.get(2).get().getEmail()).isEqualTo("julie@domain.com"); + } + + @Test + public void givenUserDaoInstance_whenCalledsave_thenTwoAssertions() { + User user = new User("Julie", "julie@domain.com"); + userDao.save(user); + assertThat(userDao.get(2).get().getName()).isEqualTo("Julie"); + assertThat(userDao.get(2).get().getEmail()).isEqualTo("julie@domain.com"); + } + + @Test + public void givenUserDaoInstance_whenCalleddelete_thenOneAssertion() { + User user = new User("Julie", "julie@domain.com"); + userDao.delete(user); + assertThat(userDao.getAll().size()).isEqualTo(2); + } +} diff --git a/patterns/design-patterns/src/test/java/com/baeldung/facade/CarEngineFacadeIntegrationTest.java b/patterns/design-patterns/src/test/java/com/baeldung/facade/CarEngineFacadeIntegrationTest.java new file mode 100644 index 0000000000..ab4c0717d9 --- /dev/null +++ b/patterns/design-patterns/src/test/java/com/baeldung/facade/CarEngineFacadeIntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.facade; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.*; + +public class CarEngineFacadeIntegrationTest { + + + private InMemoryCustomTestAppender appender; + + + @Before + public void setUp() { + appender = new InMemoryCustomTestAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + + @Test + public void whenStartEngine_thenAllNecessaryActionsPerformed() { + CarEngineFacade carEngineFacade = new CarEngineFacade(); + carEngineFacade.startEngine(); + assertTrue(appender.logContains("Fuel injector ready to inject fuel.")); + assertTrue(appender.logContains("Getting air measurements..")); + assertTrue(appender.logContains("Air provided!")); + assertTrue(appender.logContains("Fuel injector ready to inject fuel.")); + assertTrue(appender.logContains("Fuel Pump is pumping fuel..")); + assertTrue(appender.logContains("Fuel injected.")); + assertTrue(appender.logContains("Starting..")); + assertTrue(appender.logContains("Setting temperature upper limit to 90")); + assertTrue(appender.logContains("Cooling Controller ready!")); + assertTrue(appender.logContains("Setting radiator speed to 10")); + assertTrue(appender.logContains("Catalytic Converter switched on!")); + } + + + @Test + public void whenStopEngine_thenAllNecessaryActionsPerformed() { + CarEngineFacade carEngineFacade = new CarEngineFacade(); + carEngineFacade.stopEngine(); + assertTrue(appender.logContains("Stopping Fuel injector..")); + assertTrue(appender.logContains("Catalytic Converter switched off!")); + assertTrue(appender.logContains("Scheduled cooling with maximum allowed temperature 50")); + assertTrue(appender.logContains("Getting temperature from the sensor..")); + assertTrue(appender.logContains("Radiator switched on!")); + assertTrue(appender.logContains("Stopping Cooling Controller..")); + assertTrue(appender.logContains("Radiator switched off!")); + assertTrue(appender.logContains("Air controller switched off.")); + } + + private class InMemoryCustomTestAppender extends AppenderBase { + + private List logs = new ArrayList<>(); + + public InMemoryCustomTestAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + logs.add(eventObject); + } + + public boolean logContains(String message) { + return logs.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + } + } + + +} \ No newline at end of file diff --git a/patterns/design-patterns/src/test/java/com/baeldung/facade/CarEngineFacadeTest.java b/patterns/design-patterns/src/test/java/com/baeldung/facade/CarEngineFacadeTest.java deleted file mode 100644 index 88c5d3c9bc..0000000000 --- a/patterns/design-patterns/src/test/java/com/baeldung/facade/CarEngineFacadeTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.facade; - -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.AppenderBase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.*; - -public class CarEngineFacadeTest { - - - private InMemoryCustomTestAppender appender; - - - @Before - public void setUp() { - appender = new InMemoryCustomTestAppender(); - } - - @After - public void tearDown() { - appender.stop(); - } - - - @Test - public void whenStartEngine_thenAllNecessaryActionsPerformed() { - CarEngineFacade carEngineFacade = new CarEngineFacade(); - carEngineFacade.startEngine(); - assertTrue(appender.logContains("Fuel injector ready to inject fuel.")); - assertTrue(appender.logContains("Getting air measurements..")); - assertTrue(appender.logContains("Air provided!")); - assertTrue(appender.logContains("Fuel injector ready to inject fuel.")); - assertTrue(appender.logContains("Fuel Pump is pumping fuel..")); - assertTrue(appender.logContains("Fuel injected.")); - assertTrue(appender.logContains("Starting..")); - assertTrue(appender.logContains("Setting temperature upper limit to 90")); - assertTrue(appender.logContains("Cooling Controller ready!")); - assertTrue(appender.logContains("Setting radiator speed to 10")); - assertTrue(appender.logContains("Catalytic Converter switched on!")); - } - - - @Test - public void whenStopEngine_thenAllNecessaryActionsPerformed() { - CarEngineFacade carEngineFacade = new CarEngineFacade(); - carEngineFacade.stopEngine(); - assertTrue(appender.logContains("Stopping Fuel injector..")); - assertTrue(appender.logContains("Catalytic Converter switched off!")); - assertTrue(appender.logContains("Scheduled cooling with maximum allowed temperature 50")); - assertTrue(appender.logContains("Getting temperature from the sensor..")); - assertTrue(appender.logContains("Radiator switched on!")); - assertTrue(appender.logContains("Stopping Cooling Controller..")); - assertTrue(appender.logContains("Radiator switched off!")); - assertTrue(appender.logContains("Air controller switched off.")); - } - - private class InMemoryCustomTestAppender extends AppenderBase { - - private List logs = new ArrayList<>(); - - public InMemoryCustomTestAppender() { - ((Logger) LoggerFactory.getLogger("root")).addAppender(this); - start(); - } - - @Override - protected void append(ILoggingEvent eventObject) { - logs.add(eventObject); - } - - public boolean logContains(String message) { - return logs.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); - } - } - - -} \ No newline at end of file diff --git a/patterns/design-patterns/src/test/java/com/baeldung/singleton/synchronization/SingletonSynchronizationIntegrationTest.java b/patterns/design-patterns/src/test/java/com/baeldung/singleton/synchronization/SingletonSynchronizationIntegrationTest.java new file mode 100644 index 0000000000..de3d31ed9f --- /dev/null +++ b/patterns/design-patterns/src/test/java/com/baeldung/singleton/synchronization/SingletonSynchronizationIntegrationTest.java @@ -0,0 +1,119 @@ +package com.baeldung.singleton.synchronization; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Unit tests for the singleton synchronization package with the same name. + * + * @author Donato Rimenti + * + */ +public class SingletonSynchronizationIntegrationTest { + + /** + * Size of the thread pools used. + */ + private static final int POOL_SIZE = 1_000; + + /** + * Number of tasks to submit. + */ + private static final int TASKS_TO_SUBMIT = 1_000_000; + + /** + * Tests the thread-safety of {@link DraconianSingleton}. + */ + @Test + public void givenDraconianSingleton_whenMultithreadInstancesEquals_thenTrue() { + ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); + Set resultSet = Collections.synchronizedSet(new HashSet<>()); + + // Submits the instantiation tasks. + for (int i = 0; i < TASKS_TO_SUBMIT; i++) { + executor.submit(() -> resultSet.add(DraconianSingleton.getInstance())); + } + + // Since the instance of the object we inserted into the set is always + // the same, the size should be one. + Assert.assertEquals(1, resultSet.size()); + } + + /** + * Tests the thread-safety of {@link DclSingleton}. + */ + @Test + public void givenDclSingleton_whenMultithreadInstancesEquals_thenTrue() { + ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); + Set resultSet = Collections.synchronizedSet(new HashSet<>()); + + // Submits the instantiation tasks. + for (int i = 0; i < TASKS_TO_SUBMIT; i++) { + executor.submit(() -> resultSet.add(DclSingleton.getInstance())); + } + + // Since the instance of the object we inserted into the set is always + // the same, the size should be one. + Assert.assertEquals(1, resultSet.size()); + } + + /** + * Tests the thread-safety of {@link EarlyInitSingleton}. + */ + @Test + public void givenEarlyInitSingleton_whenMultithreadInstancesEquals_thenTrue() { + ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); + Set resultSet = Collections.synchronizedSet(new HashSet<>()); + + // Submits the instantiation tasks. + for (int i = 0; i < TASKS_TO_SUBMIT; i++) { + executor.submit(() -> resultSet.add(EarlyInitSingleton.getInstance())); + } + + // Since the instance of the object we inserted into the set is always + // the same, the size should be one. + Assert.assertEquals(1, resultSet.size()); + } + + /** + * Tests the thread-safety of {@link InitOnDemandSingleton}. + */ + @Test + public void givenInitOnDemandSingleton_whenMultithreadInstancesEquals_thenTrue() { + ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); + Set resultSet = Collections.synchronizedSet(new HashSet<>()); + + // Submits the instantiation tasks. + for (int i = 0; i < TASKS_TO_SUBMIT; i++) { + executor.submit(() -> resultSet.add(InitOnDemandSingleton.getInstance())); + } + + // Since the instance of the object we inserted into the set is always + // the same, the size should be one. + Assert.assertEquals(1, resultSet.size()); + } + + /** + * Tests the thread-safety of {@link EnumSingleton}. + */ + @Test + public void givenEnumSingleton_whenMultithreadInstancesEquals_thenTrue() { + ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); + Set resultSet = Collections.synchronizedSet(new HashSet<>()); + + // Submits the instantiation tasks. + for (int i = 0; i < TASKS_TO_SUBMIT; i++) { + executor.submit(() -> resultSet.add(EnumSingleton.INSTANCE)); + } + + // Since the instance of the object we inserted into the set is always + // the same, the size should be one. + Assert.assertEquals(1, resultSet.size()); + } +} diff --git a/patterns/design-patterns/src/test/java/com/baeldung/singleton/synchronization/SingletonSynchronizationUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/singleton/synchronization/SingletonSynchronizationUnitTest.java deleted file mode 100644 index 08a70f6056..0000000000 --- a/patterns/design-patterns/src/test/java/com/baeldung/singleton/synchronization/SingletonSynchronizationUnitTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.baeldung.singleton.synchronization; - -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import org.junit.Assert; -import org.junit.Test; - -/** - * Unit tests for the singleton synchronization package with the same name. - * - * @author Donato Rimenti - * - */ -public class SingletonSynchronizationUnitTest { - - /** - * Size of the thread pools used. - */ - private static final int POOL_SIZE = 1_000; - - /** - * Number of tasks to submit. - */ - private static final int TASKS_TO_SUBMIT = 1_000_000; - - /** - * Tests the thread-safety of {@link DraconianSingleton}. - */ - @Test - public void givenDraconianSingleton_whenMultithreadInstancesEquals_thenTrue() { - ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); - Set resultSet = Collections.synchronizedSet(new HashSet()); - - // Submits the instantiation tasks. - for (int i = 0; i < TASKS_TO_SUBMIT; i++) { - executor.submit(() -> resultSet.add(DraconianSingleton.getInstance())); - } - - // Since the instance of the object we inserted into the set is always - // the same, the size should be one. - Assert.assertEquals(1, resultSet.size()); - } - - /** - * Tests the thread-safety of {@link DclSingleton}. - */ - @Test - public void givenDclSingleton_whenMultithreadInstancesEquals_thenTrue() { - ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); - Set resultSet = Collections.synchronizedSet(new HashSet()); - - // Submits the instantiation tasks. - for (int i = 0; i < TASKS_TO_SUBMIT; i++) { - executor.submit(() -> resultSet.add(DclSingleton.getInstance())); - } - - // Since the instance of the object we inserted into the set is always - // the same, the size should be one. - Assert.assertEquals(1, resultSet.size()); - } - - /** - * Tests the thread-safety of {@link EarlyInitSingleton}. - */ - @Test - public void givenEarlyInitSingleton_whenMultithreadInstancesEquals_thenTrue() { - ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); - Set resultSet = Collections.synchronizedSet(new HashSet()); - - // Submits the instantiation tasks. - for (int i = 0; i < TASKS_TO_SUBMIT; i++) { - executor.submit(() -> resultSet.add(EarlyInitSingleton.getInstance())); - } - - // Since the instance of the object we inserted into the set is always - // the same, the size should be one. - Assert.assertEquals(1, resultSet.size()); - } - - /** - * Tests the thread-safety of {@link InitOnDemandSingleton}. - */ - @Test - public void givenInitOnDemandSingleton_whenMultithreadInstancesEquals_thenTrue() { - ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); - Set resultSet = Collections.synchronizedSet(new HashSet()); - - // Submits the instantiation tasks. - for (int i = 0; i < TASKS_TO_SUBMIT; i++) { - executor.submit(() -> resultSet.add(InitOnDemandSingleton.getInstance())); - } - - // Since the instance of the object we inserted into the set is always - // the same, the size should be one. - Assert.assertEquals(1, resultSet.size()); - } - - /** - * Tests the thread-safety of {@link EnumSingleton}. - */ - @Test - public void givenEnumSingleton_whenMultithreadInstancesEquals_thenTrue() { - ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); - Set resultSet = Collections.synchronizedSet(new HashSet()); - - // Submits the instantiation tasks. - for (int i = 0; i < TASKS_TO_SUBMIT; i++) { - executor.submit(() -> resultSet.add(EnumSingleton.INSTANCE)); - } - - // Since the instance of the object we inserted into the set is always - // the same, the size should be one. - Assert.assertEquals(1, resultSet.size()); - } -} diff --git a/patterns/design-patterns/src/test/java/com/baeldung/state/StatePatternUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/state/StatePatternUnitTest.java new file mode 100644 index 0000000000..731974f92b --- /dev/null +++ b/patterns/design-patterns/src/test/java/com/baeldung/state/StatePatternUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.state; + +import com.baeldung.state.Package; + +import static org.junit.Assert.assertThat; +import static org.hamcrest.CoreMatchers.instanceOf; + +import org.junit.Test; + +public class StatePatternUnitTest { + + @Test + public void givenNewPackage_whenPackageReceived_thenStateReceived() { + Package pkg = new Package(); + + assertThat(pkg.getState(), instanceOf(OrderedState.class)); + pkg.nextState(); + + assertThat(pkg.getState(), instanceOf(DeliveredState.class)); + pkg.nextState(); + + assertThat(pkg.getState(), instanceOf(ReceivedState.class)); + } + + @Test + public void givenDeliveredPackage_whenPrevState_thenStateOrdered() { + Package pkg = new Package(); + pkg.setState(new DeliveredState()); + pkg.previousState(); + + assertThat(pkg.getState(), instanceOf(OrderedState.class)); + } +} diff --git a/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java b/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java new file mode 100644 index 0000000000..4ad4debb27 --- /dev/null +++ b/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java @@ -0,0 +1,87 @@ +package com.baeldung.templatemethod.test; + +import com.baeldung.pattern.templatemethod.model.Computer; +import com.baeldung.pattern.templatemethod.model.HighEndComputerBuilder; +import com.baeldung.pattern.templatemethod.model.StandardComputerBuilder; +import org.junit.Assert; +import static org.junit.Assert.assertEquals; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.junit.Assert.assertThat; + +public class TemplateMethodPatternIntegrationTest { + + private static StandardComputerBuilder standardComputerBuilder; + private static HighEndComputerBuilder highEndComputerBuilder; + + @BeforeClass + public static void setUpStandardComputerBuilderInstance() { + standardComputerBuilder = new StandardComputerBuilder(); + } + + @BeforeClass + public static void setUpHighEndComputerBuilderInstance() { + highEndComputerBuilder = new HighEndComputerBuilder(); + } + + @Test + public void givenStandardMotherBoard_whenAddingMotherBoard_thenEqualAssertion() { + standardComputerBuilder.addMotherboard(); + assertEquals("Standard Motherboard", standardComputerBuilder.getComputerParts().get("Motherboard")); + } + + @Test + public void givenStandardMotherboard_whenSetup_thenTwoEqualAssertions() { + standardComputerBuilder.setupMotherboard(); + assertEquals("Screwing the standard motherboard to the case.", standardComputerBuilder.getMotherboardSetupStatus().get(0)); + assertEquals("Pluging in the power supply connectors.", standardComputerBuilder.getMotherboardSetupStatus().get(1)); + } + + @Test + public void givenStandardProcessor_whenAddingProcessor_thenEqualAssertion() { + standardComputerBuilder.addProcessor(); + assertEquals("Standard Processor", standardComputerBuilder.getComputerParts().get("Processor")); + } + + @Test + public void givenAllStandardParts_whenBuildingComputer_thenTwoParts() { + standardComputerBuilder.buildComputer(); + assertEquals(2, standardComputerBuilder.getComputerParts().size()); + } + + @Test + public void givenAllStandardParts_whenComputerisBuilt_thenComputerInstance() { + assertThat(standardComputerBuilder.buildComputer(), instanceOf(Computer.class)); + } + + @Test + public void givenHighEnddMotherBoard_whenAddingMotherBoard_thenEqualAssertion() { + highEndComputerBuilder.addMotherboard(); + Assert.assertEquals("High-end Motherboard", highEndComputerBuilder.getComputerParts().get("Motherboard")); + } + + @Test + public void givenHighEnddMotheroboard_whenSetup_thenTwoEqualAssertions() { + highEndComputerBuilder.setupMotherboard(); + assertEquals("Screwing the high-end motherboard to the case.", highEndComputerBuilder.getMotherboardSetupStatus().get(0)); + assertEquals("Pluging in the power supply connectors.", highEndComputerBuilder.getMotherboardSetupStatus().get(1)); + } + + @Test + public void givenHightEndProcessor_whenAddingProcessor_thenEqualAssertion() { + highEndComputerBuilder.addProcessor(); + assertEquals("High-end Processor", highEndComputerBuilder.getComputerParts().get("Processor")); + } + + @Test + public void givenAllHighEnddParts_whenBuildingComputer_thenTwoParts() { + highEndComputerBuilder.buildComputer(); + assertEquals(2, highEndComputerBuilder.getComputerParts().size()); + } + + @Test + public void givenAllHighEndParts_whenComputerisBuilt_thenComputerInstance() { + assertThat(standardComputerBuilder.buildComputer(), instanceOf(Computer.class)); + } +} diff --git a/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternTest.java b/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternTest.java deleted file mode 100644 index 679559af9f..0000000000 --- a/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.baeldung.pattern.templatemethod.test; - -import com.baeldung.pattern.templatemethod.model.Computer; -import com.baeldung.pattern.templatemethod.model.HighEndComputerBuilder; -import com.baeldung.pattern.templatemethod.model.StandardComputerBuilder; -import org.junit.Assert; -import static org.junit.Assert.assertEquals; -import org.junit.BeforeClass; -import org.junit.Test; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertThat; - -public class TemplateMethodPatternTest { - - private static StandardComputerBuilder standardComputerBuilder; - private static HighEndComputerBuilder highEndComputerBuilder; - - @BeforeClass - public static void setUpStandardComputerBuilderInstance() { - standardComputerBuilder = new StandardComputerBuilder(); - } - - @BeforeClass - public static void setUpHighEndComputerBuilderInstance() { - highEndComputerBuilder = new HighEndComputerBuilder(); - } - - @Test - public void givenStandardMotherBoard_whenAddingMotherBoard_thenEqualAssertion() { - standardComputerBuilder.addMotherboard(); - assertEquals("Standard Motherboard", standardComputerBuilder.getComputerParts().get("Motherboard")); - } - - @Test - public void givenStandardMotherboard_whenSetup_thenTwoEqualAssertions() { - standardComputerBuilder.setupMotherboard(); - assertEquals("Screwing the standard motherboard to the case.", standardComputerBuilder.getMotherboardSetupStatus().get(0)); - assertEquals("Pluging in the power supply connectors.", standardComputerBuilder.getMotherboardSetupStatus().get(1)); - } - - @Test - public void givenStandardProcessor_whenAddingProcessor_thenEqualAssertion() { - standardComputerBuilder.addProcessor(); - assertEquals("Standard Processor", standardComputerBuilder.getComputerParts().get("Processor")); - } - - @Test - public void givenAllStandardParts_whenBuildingComputer_thenTwoParts() { - standardComputerBuilder.buildComputer(); - assertEquals(2, standardComputerBuilder.getComputerParts().size()); - } - - @Test - public void givenAllStandardParts_whenComputerisBuilt_thenComputerInstance() { - assertThat(standardComputerBuilder.buildComputer(), instanceOf(Computer.class)); - } - - @Test - public void givenHighEnddMotherBoard_whenAddingMotherBoard_thenEqualAssertion() { - highEndComputerBuilder.addMotherboard(); - Assert.assertEquals("High-end Motherboard", highEndComputerBuilder.getComputerParts().get("Motherboard")); - } - - @Test - public void givenHighEnddMotheroboard_whenSetup_thenTwoEqualAssertions() { - highEndComputerBuilder.setupMotherboard(); - assertEquals("Screwing the high-end motherboard to the case.", highEndComputerBuilder.getMotherboardSetupStatus().get(0)); - assertEquals("Pluging in the power supply connectors.", highEndComputerBuilder.getMotherboardSetupStatus().get(1)); - } - - @Test - public void givenHightEndProcessor_whenAddingProcessor_thenEqualAssertion() { - highEndComputerBuilder.addProcessor(); - assertEquals("High-end Processor", highEndComputerBuilder.getComputerParts().get("Processor")); - } - - @Test - public void givenAllHighEnddParts_whenBuildingComputer_thenTwoParts() { - highEndComputerBuilder.buildComputer(); - assertEquals(2, highEndComputerBuilder.getComputerParts().size()); - } - - @Test - public void givenAllHighEndParts_whenComputerisBuilt_thenComputerInstance() { - assertThat(standardComputerBuilder.buildComputer(), instanceOf(Computer.class)); - } -} diff --git a/patterns/front-controller/pom.xml b/patterns/front-controller/pom.xml index a12d606165..435b0dd9cd 100644 --- a/patterns/front-controller/pom.xml +++ b/patterns/front-controller/pom.xml @@ -1,12 +1,12 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 front-controller war - patterns-parent + patterns com.baeldung 1.0.0-SNAPSHOT .. diff --git a/patterns/front-controller/src/main/resources/logback.xml b/patterns/front-controller/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/patterns/front-controller/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/patterns/intercepting-filter/pom.xml b/patterns/intercepting-filter/pom.xml index 8c68302315..fa94d5d1fd 100644 --- a/patterns/intercepting-filter/pom.xml +++ b/patterns/intercepting-filter/pom.xml @@ -8,7 +8,7 @@ com.baeldung - patterns-parent + patterns 1.0.0-SNAPSHOT .. @@ -21,7 +21,7 @@ org.slf4j slf4j-api - ${slf4j.version} + ${org.slf4j.version} @@ -30,10 +30,10 @@ org.apache.maven.plugins maven-compiler-plugin - 3.7.0 + ${maven-compiler-plugin.version} - 1.8 - 1.8 + ${java.version} + ${java.version} @@ -55,7 +55,4 @@ - - 1.7.21 - diff --git a/patterns/intercepting-filter/src/main/resources/logback.xml b/patterns/intercepting-filter/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/patterns/intercepting-filter/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/patterns/pom.xml b/patterns/pom.xml index a811664b86..df09f1836a 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -1,9 +1,8 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung - patterns-parent + patterns pom diff --git a/pdf/pom.xml b/pdf/pom.xml index 01b2e15652..bf5d475163 100644 --- a/pdf/pom.xml +++ b/pdf/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 pdf pdf @@ -74,7 +73,6 @@ - UTF-8 2.0.3 1.6 5.5.10 diff --git a/pdf/src/main/resources/logback.xml b/pdf/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/pdf/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/performance-tests/README.md b/performance-tests/README.md new file mode 100644 index 0000000000..5af735b708 --- /dev/null +++ b/performance-tests/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Performance of Java Mapping Frameworks](http://www.baeldung.com/java-performance-mapping-frameworks) diff --git a/performance-tests/pom.xml b/performance-tests/pom.xml index 3f25796516..8c9d027724 100644 --- a/performance-tests/pom.xml +++ b/performance-tests/pom.xml @@ -2,72 +2,73 @@ + 4.0.0 + performance-tests + parent-modules com.baeldung 1.0.0-SNAPSHOT - 4.0.0 - - performancetests ma.glasnost.orika orika-core - 1.5.2 + ${orika.version} net.sf.dozer dozer - 5.5.1 + ${dozer.version} io.craftsman dozer-jdk8-support - 1.0.2 + ${dozer-jdk8-support.version} org.mapstruct mapstruct-jdk8 - 1.2.0.Final + ${mapstruct-jdk8.version} org.modelmapper modelmapper - 1.1.0 + ${modelmapper.version} com.googlecode.jmapper-framework jmapper-core - 1.6.0.1 + ${jmapper.version} org.openjdk.jmh jmh-core - 1.20 + ${jmh.version} org.openjdk.jmh jmh-generator-annprocess - 1.20 + ${jmh.version} + org.apache.maven.plugins maven-compiler-plugin - 3.5.1 + ${maven-compiler-plugin.version} - 1.8 - 1.8 + ${java.version} + ${java.version} org.mapstruct mapstruct-processor - 1.2.0.Final + ${mapstruct-processor.version} @@ -75,5 +76,16 @@ + + + 1.5.2 + 5.5.1 + 1.0.2 + 1.2.0.Final + 1.1.0 + 1.6.0.1 + 1.20 + 1.2.0.Final + \ No newline at end of file diff --git a/performance-tests/src/main/resources/logback.xml b/performance-tests/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/performance-tests/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java b/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java index 9a45f032a6..e781f1fca1 100644 --- a/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java +++ b/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java @@ -4,13 +4,32 @@ import com.baeldung.performancetests.dozer.DozerConverter; import com.baeldung.performancetests.jmapper.JMapperConverter; import com.baeldung.performancetests.mapstruct.MapStructConverter; import com.baeldung.performancetests.model.destination.DestinationCode; -import com.baeldung.performancetests.model.source.*; import com.baeldung.performancetests.model.destination.Order; +import com.baeldung.performancetests.model.source.AccountStatus; +import com.baeldung.performancetests.model.source.Address; +import com.baeldung.performancetests.model.source.DeliveryData; +import com.baeldung.performancetests.model.source.Discount; +import com.baeldung.performancetests.model.source.OrderStatus; +import com.baeldung.performancetests.model.source.PaymentType; +import com.baeldung.performancetests.model.source.Product; +import com.baeldung.performancetests.model.source.RefundPolicy; +import com.baeldung.performancetests.model.source.Review; +import com.baeldung.performancetests.model.source.Shop; +import com.baeldung.performancetests.model.source.SourceCode; +import com.baeldung.performancetests.model.source.SourceOrder; +import com.baeldung.performancetests.model.source.User; import com.baeldung.performancetests.modelmapper.ModelMapperConverter; import com.baeldung.performancetests.orika.OrikaConverter; -import org.junit.Assert; -import org.junit.Test; -import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Group; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.runner.RunnerException; import java.io.IOException; @@ -21,14 +40,24 @@ import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; +@Fork(value = 1, warmups = 5) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@BenchmarkMode(Mode.All) +@Measurement(iterations = 5) @State(Scope.Group) public class MappingFrameworksPerformance { - SourceOrder sourceOrder = null; - SourceCode sourceCode = null; + private SourceOrder sourceOrder = null; + private SourceCode sourceCode = null; + private static final OrikaConverter ORIKA_CONVERTER = new OrikaConverter(); + private static final JMapperConverter JMAPPER_CONVERTER = new JMapperConverter(); + private static final ModelMapperConverter MODEL_MAPPER_CONVERTER = new ModelMapperConverter(); + private static final DozerConverter DOZER_CONVERTER = new DozerConverter(); + @Setup public void setUp() { User user = new User("John", "John@doe.com", AccountStatus.ACTIVE); - RefundPolicy refundPolicy = new RefundPolicy(true, 30, Collections.singletonList("Refundable only if not used!")); + RefundPolicy refundPolicy = new RefundPolicy(true, 30, Collections + .singletonList("Refundable only if not used!")); Product product = new Product(BigDecimal.valueOf(10.99), 100, @@ -51,7 +80,7 @@ public class MappingFrameworksPerformance { List reviewList = new ArrayList<>(); reviewList.add(review); reviewList.add(negativeReview); - Shop shop = new Shop("Super Shop", shopAddress,"www.super-shop.com",reviewList); + Shop shop = new Shop("Super Shop", shopAddress, "www.super-shop.com", reviewList); sourceOrder = new SourceOrder(OrderStatus.CONFIRMED, Instant.now().toString(), @@ -68,126 +97,67 @@ public class MappingFrameworksPerformance { sourceCode = new SourceCode("This is source code!"); } - public void main(String[] args) throws IOException, RunnerException { org.openjdk.jmh.Main.main(args); } - @Benchmark @Group("realLifeTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void orikaMapperRealLifeBenchmark() { - OrikaConverter orikaConverter = new OrikaConverter(); - Order mappedOrder = orikaConverter.convert(sourceOrder); - Assert.assertEquals(mappedOrder, sourceOrder); - + public Order orikaMapperRealLifeBenchmark() { + return ORIKA_CONVERTER.convert(sourceOrder); } @Benchmark @Group("realLifeTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void jmapperRealLifeBenchmark() { - JMapperConverter jmapperConverter = new JMapperConverter(); - Order mappedOrder = jmapperConverter.convert(sourceOrder); - Assert.assertEquals(mappedOrder, sourceOrder); + public Order jmapperRealLifeBenchmark() { + return JMAPPER_CONVERTER.convert(sourceOrder); } @Benchmark @Group("realLifeTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void modelMapperRealLifeBenchmark() { - ModelMapperConverter modelMapperConverter = new ModelMapperConverter(); - Order mappedOrder = modelMapperConverter.convert(sourceOrder); - Assert.assertEquals(mappedOrder, sourceOrder); - } - - - @Benchmark - @Group("realLifeTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void dozerMapperRealLifeBenchmark() { - DozerConverter dozerConverter = new DozerConverter(); - Order mappedOrder = dozerConverter.convert(sourceOrder); - Assert.assertEquals(mappedOrder, sourceOrder); - + public Order modelMapperRealLifeBenchmark() { + return MODEL_MAPPER_CONVERTER.convert(sourceOrder); } @Benchmark @Group("realLifeTest") - @Fork(value = 1, warmups = 1) - @BenchmarkMode(Mode.All) - public void mapStructRealLifeMapperBenchmark() { - MapStructConverter converter = MapStructConverter.MAPPER; - Order mappedOrder = converter.convert(sourceOrder); - Assert.assertEquals(mappedOrder, sourceOrder); + public Order dozerMapperRealLifeBenchmark() { + return DOZER_CONVERTER.convert(sourceOrder); + } + + @Benchmark + @Group("realLifeTest") + public Order mapStructRealLifeMapperBenchmark() { + return MapStructConverter.MAPPER.convert(sourceOrder); } @Benchmark @Group("simpleTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void orikaMapperSimpleBenchmark() { - OrikaConverter orikaConverter = new OrikaConverter(); - DestinationCode mappedCode = orikaConverter.convert(sourceCode); - Assert.assertEquals(mappedCode.getCode(), sourceCode.getCode()); - + public DestinationCode orikaMapperSimpleBenchmark() { + return ORIKA_CONVERTER.convert(sourceCode); } @Benchmark @Group("simpleTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void jmapperSimpleBenchmark() { - JMapperConverter jmapperConverter = new JMapperConverter(); - DestinationCode mappedCode = jmapperConverter.convert(sourceCode); - Assert.assertEquals(mappedCode.getCode(), sourceCode.getCode()); + public DestinationCode jmapperSimpleBenchmark() { + return JMAPPER_CONVERTER.convert(sourceCode); } @Benchmark @Group("simpleTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void modelMapperBenchmark() { - ModelMapperConverter modelMapperConverter = new ModelMapperConverter(); - DestinationCode mappedCode = modelMapperConverter.convert(sourceCode); - Assert.assertEquals(mappedCode.getCode(), sourceCode.getCode()); - } - - - @Benchmark - @Group("simpleTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void dozerMapperSimpleBenchmark() { - DozerConverter dozerConverter = new DozerConverter(); - Order mappedOrder = dozerConverter.convert(sourceOrder); - Assert.assertEquals(mappedOrder, sourceOrder); - + public DestinationCode modelMapperBenchmark() { + return MODEL_MAPPER_CONVERTER.convert(sourceCode); } @Benchmark @Group("simpleTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void mapStructMapperSimpleBenchmark() { - MapStructConverter converter = MapStructConverter.MAPPER; - DestinationCode mappedCode = converter.convert(sourceCode); - Assert.assertEquals(mappedCode.getCode(), sourceCode.getCode()); + public DestinationCode dozerMapperSimpleBenchmark() { + return DOZER_CONVERTER.convert(sourceCode); } - + @Benchmark + @Group("simpleTest") + public DestinationCode mapStructMapperSimpleBenchmark() { + return MapStructConverter.MAPPER.convert(sourceCode); + } } diff --git a/persistence-modules/README.md b/persistence-modules/README.md index dde4558387..f12163bd6a 100644 --- a/persistence-modules/README.md +++ b/persistence-modules/README.md @@ -7,5 +7,5 @@ - [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search) - [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring) - [Introduction to Lettuce – the Java Redis Client](http://www.baeldung.com/java-redis-lettuce) -- [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging) - [A Guide to Jdbi](http://www.baeldung.com/jdbi) +- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking) diff --git a/persistence-modules/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml index 610d6b8f09..36ec6b5ac8 100644 --- a/persistence-modules/java-cassandra/pom.xml +++ b/persistence-modules/java-cassandra/pom.xml @@ -1,16 +1,15 @@ + 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 - cassandra-java-client + java-cassandra 1.0.0-SNAPSHOT - cassandra-java-client com.baeldung parent-java - 0.0.1-SNAPSHOT - ../../parent-java + 0.0.1-SNAPSHOT + ../../parent-java @@ -36,8 +35,6 @@ - UTF-8 - 19.0 3.1.2 3.1.1.0 diff --git a/persistence-modules/java-cassandra/src/main/resources/logback.xml b/persistence-modules/java-cassandra/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/java-cassandra/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/java-cockroachdb/pom.xml b/persistence-modules/java-cockroachdb/pom.xml index a1924b674a..870707c750 100644 --- a/persistence-modules/java-cockroachdb/pom.xml +++ b/persistence-modules/java-cockroachdb/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung java-cockroachdb diff --git a/persistence-modules/java-cockroachdb/src/main/resources/logback.xml b/persistence-modules/java-cockroachdb/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/java-cockroachdb/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/java-cockroachdb/src/test/java/com/baeldung/cockroachdb/ArticleRepositoryIntegrationTest.java b/persistence-modules/java-cockroachdb/src/test/java/com/baeldung/cockroachdb/ArticleRepositoryIntegrationTest.java deleted file mode 100644 index 9eb00b3651..0000000000 --- a/persistence-modules/java-cockroachdb/src/test/java/com/baeldung/cockroachdb/ArticleRepositoryIntegrationTest.java +++ /dev/null @@ -1,208 +0,0 @@ -package com.baeldung.cockroachdb; - -import com.baeldung.cockroachdb.domain.Article; -import com.baeldung.cockroachdb.repository.ArticleRepository; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.postgresql.util.PSQLException; - -import java.sql.*; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class ArticleRepositoryIntegrationTest { - - private static final String TABLE_NAME = "articles"; - - private Connection con; - private ArticleRepository articleRepository; - - @Before - public void connect() throws Exception { - Class.forName("org.postgresql.Driver"); - con = DriverManager.getConnection("jdbc:postgresql://localhost:26257/testdb", "user17", "qwerty"); - - articleRepository = new ArticleRepository(con); - } - - @Test - public void whenCreatingTable_thenCreatedCorrectly() throws Exception { - articleRepository.deleteTable(); - articleRepository.createTable(); - - PreparedStatement preparedStatement = con.prepareStatement("SHOW TABLES"); - ResultSet resultSet = preparedStatement.executeQuery(); - List tables = new ArrayList<>(); - while (resultSet.next()) { - tables.add(resultSet.getString("Table")); - } - - assertTrue(tables.stream().anyMatch(t -> t.equals(TABLE_NAME))); - } - - @Test - public void whenAlteringTheTable_thenColumnAddedCorrectly() throws SQLException { - articleRepository.deleteTable(); - articleRepository.createTable(); - - String columnName = "creationdate"; - articleRepository.alterTable(columnName, "DATE"); - - String query = "SHOW COLUMNS FROM " + TABLE_NAME; - PreparedStatement preparedStatement = con.prepareStatement(query); - ResultSet resultSet = preparedStatement.executeQuery(); - List columns = new ArrayList<>(); - while (resultSet.next()) { - columns.add(resultSet.getString("Field")); - } - - assertTrue(columns.stream().anyMatch(c -> c.equals(columnName))); - } - - @Test - public void whenInsertingNewArticle_thenArticleExists() throws SQLException { - articleRepository.deleteTable(); - articleRepository.createTable(); - - String title = "Guide to CockroachDB in Java"; - String author = "baeldung"; - Article article = new Article(UUID.randomUUID(), title, author); - articleRepository.insertArticle(article); - - Article savedArticle = articleRepository.selectByTitle(title); - assertEquals(article.getTitle(), savedArticle.getTitle()); - } - - @Test - public void whenSelectingAllArticles_thenAllArticlesAreReturned() throws SQLException { - articleRepository.deleteTable(); - articleRepository.createTable(); - - Article article = new Article(UUID.randomUUID(), "Guide to CockroachDB in Java", "baeldung"); - articleRepository.insertArticle(article); - - article = new Article(UUID.randomUUID(), "A Guide to MongoDB with Java", "baeldung"); - articleRepository.insertArticle(article); - - List
    savedArticles = articleRepository.selectAll(); - - assertEquals(2, savedArticles.size()); - assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("Guide to CockroachDB in Java"))); - assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("A Guide to MongoDB with Java"))); - } - - @Test - public void whenDeletingArticleByTtile_thenArticleIsDeleted() throws SQLException { - articleRepository.deleteTable(); - articleRepository.createTable(); - - Article article = new Article(UUID.randomUUID(), "Guide to CockroachDB in Java", "baeldung"); - articleRepository.insertArticle(article); - - article = new Article(UUID.randomUUID(), "A Guide to MongoDB with Java", "baeldung"); - articleRepository.insertArticle(article); - - articleRepository.deleteArticleByTitle("A Guide to MongoDB with Java"); - - List
    savedArticles = articleRepository.selectAll(); - assertEquals(1, savedArticles.size()); - assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("Guide to CockroachDB in Java"))); - assertFalse(savedArticles.stream().anyMatch(a -> a.getTitle().equals("A Guide to MongoDB with Java"))); - } - - @Test(expected = PSQLException.class) - public void whenDeletingATable_thenExceptionIfAccessed() throws SQLException { - articleRepository.createTable(); - articleRepository.deleteTable(); - - StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME); - - final String query = sb.toString(); - PreparedStatement preparedStatement = con.prepareStatement(query); - preparedStatement.executeQuery(); - } - - @Test - public void whenTruncatingATable_thenEmptyTable() throws SQLException { - articleRepository.deleteTable(); - articleRepository.createTable(); - - Article article = new Article(UUID.randomUUID(), "Guide to CockroachDB in Java", "baeldung"); - articleRepository.insertArticle(article); - - article = new Article(UUID.randomUUID(), "A Guide to MongoDB with Java", "baeldung"); - articleRepository.insertArticle(article); - - articleRepository.truncateTable(); - - List
    savedArticles = articleRepository.selectAll(); - assertEquals(0, savedArticles.size()); - } - - @Test - public void whenInsertingTwoArticlesWithSamePrimaryKeyInASingleTransaction_thenRollback() throws SQLException { - articleRepository.deleteTable(); - articleRepository.createTable(); - - try { - con.setAutoCommit(false); - - UUID articleId = UUID.randomUUID(); - - Article article = new Article(articleId, "Guide to CockroachDB in Java", "baeldung"); - articleRepository.insertArticle(article); - - article = new Article(articleId, "A Guide to MongoDB with Java", "baeldung"); - articleRepository.insertArticle(article); - - con.commit(); - } catch (Exception e) { - con.rollback(); - } finally { - con.setAutoCommit(true); - } - - List
    savedArticles = articleRepository.selectAll(); - assertEquals(0, savedArticles.size()); - } - - @Test - public void whenInsertingTwoArticlesInASingleTransaction_thenInserted() throws SQLException { - articleRepository.deleteTable(); - articleRepository.createTable(); - - try { - con.setAutoCommit(false); - - Article article = new Article(UUID.randomUUID(), "Guide to CockroachDB in Java", "baeldung"); - articleRepository.insertArticle(article); - - article = new Article(UUID.randomUUID(), "A Guide to MongoDB with Java", "baeldung"); - articleRepository.insertArticle(article); - - con.commit(); - } catch (Exception e) { - con.rollback(); - } finally { - con.setAutoCommit(true); - } - - List
    savedArticles = articleRepository.selectAll(); - assertEquals(2, savedArticles.size()); - assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("Guide to CockroachDB in Java"))); - assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("A Guide to MongoDB with Java"))); - } - - @After - public void disconnect() throws SQLException { - articleRepository = null; - con.close(); - con = null; - } -} diff --git a/persistence-modules/java-cockroachdb/src/test/java/com/baeldung/cockroachdb/ArticleRepositoryLiveTest.java b/persistence-modules/java-cockroachdb/src/test/java/com/baeldung/cockroachdb/ArticleRepositoryLiveTest.java new file mode 100644 index 0000000000..eda9ca15e4 --- /dev/null +++ b/persistence-modules/java-cockroachdb/src/test/java/com/baeldung/cockroachdb/ArticleRepositoryLiveTest.java @@ -0,0 +1,208 @@ +package com.baeldung.cockroachdb; + +import com.baeldung.cockroachdb.domain.Article; +import com.baeldung.cockroachdb.repository.ArticleRepository; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.postgresql.util.PSQLException; + +import java.sql.*; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class ArticleRepositoryLiveTest { + + private static final String TABLE_NAME = "articles"; + + private Connection con; + private ArticleRepository articleRepository; + + @Before + public void connect() throws Exception { + Class.forName("org.postgresql.Driver"); + con = DriverManager.getConnection("jdbc:postgresql://localhost:26257/testdb", "user17", "qwerty"); + + articleRepository = new ArticleRepository(con); + } + + @Test + public void whenCreatingTable_thenCreatedCorrectly() throws Exception { + articleRepository.deleteTable(); + articleRepository.createTable(); + + PreparedStatement preparedStatement = con.prepareStatement("SHOW TABLES"); + ResultSet resultSet = preparedStatement.executeQuery(); + List tables = new ArrayList<>(); + while (resultSet.next()) { + tables.add(resultSet.getString("Table")); + } + + assertTrue(tables.stream().anyMatch(t -> t.equals(TABLE_NAME))); + } + + @Test + public void whenAlteringTheTable_thenColumnAddedCorrectly() throws SQLException { + articleRepository.deleteTable(); + articleRepository.createTable(); + + String columnName = "creationdate"; + articleRepository.alterTable(columnName, "DATE"); + + String query = "SHOW COLUMNS FROM " + TABLE_NAME; + PreparedStatement preparedStatement = con.prepareStatement(query); + ResultSet resultSet = preparedStatement.executeQuery(); + List columns = new ArrayList<>(); + while (resultSet.next()) { + columns.add(resultSet.getString("Field")); + } + + assertTrue(columns.stream().anyMatch(c -> c.equals(columnName))); + } + + @Test + public void whenInsertingNewArticle_thenArticleExists() throws SQLException { + articleRepository.deleteTable(); + articleRepository.createTable(); + + String title = "Guide to CockroachDB in Java"; + String author = "baeldung"; + Article article = new Article(UUID.randomUUID(), title, author); + articleRepository.insertArticle(article); + + Article savedArticle = articleRepository.selectByTitle(title); + assertEquals(article.getTitle(), savedArticle.getTitle()); + } + + @Test + public void whenSelectingAllArticles_thenAllArticlesAreReturned() throws SQLException { + articleRepository.deleteTable(); + articleRepository.createTable(); + + Article article = new Article(UUID.randomUUID(), "Guide to CockroachDB in Java", "baeldung"); + articleRepository.insertArticle(article); + + article = new Article(UUID.randomUUID(), "A Guide to MongoDB with Java", "baeldung"); + articleRepository.insertArticle(article); + + List
    savedArticles = articleRepository.selectAll(); + + assertEquals(2, savedArticles.size()); + assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("Guide to CockroachDB in Java"))); + assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("A Guide to MongoDB with Java"))); + } + + @Test + public void whenDeletingArticleByTtile_thenArticleIsDeleted() throws SQLException { + articleRepository.deleteTable(); + articleRepository.createTable(); + + Article article = new Article(UUID.randomUUID(), "Guide to CockroachDB in Java", "baeldung"); + articleRepository.insertArticle(article); + + article = new Article(UUID.randomUUID(), "A Guide to MongoDB with Java", "baeldung"); + articleRepository.insertArticle(article); + + articleRepository.deleteArticleByTitle("A Guide to MongoDB with Java"); + + List
    savedArticles = articleRepository.selectAll(); + assertEquals(1, savedArticles.size()); + assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("Guide to CockroachDB in Java"))); + assertFalse(savedArticles.stream().anyMatch(a -> a.getTitle().equals("A Guide to MongoDB with Java"))); + } + + @Test(expected = PSQLException.class) + public void whenDeletingATable_thenExceptionIfAccessed() throws SQLException { + articleRepository.createTable(); + articleRepository.deleteTable(); + + StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME); + + final String query = sb.toString(); + PreparedStatement preparedStatement = con.prepareStatement(query); + preparedStatement.executeQuery(); + } + + @Test + public void whenTruncatingATable_thenEmptyTable() throws SQLException { + articleRepository.deleteTable(); + articleRepository.createTable(); + + Article article = new Article(UUID.randomUUID(), "Guide to CockroachDB in Java", "baeldung"); + articleRepository.insertArticle(article); + + article = new Article(UUID.randomUUID(), "A Guide to MongoDB with Java", "baeldung"); + articleRepository.insertArticle(article); + + articleRepository.truncateTable(); + + List
    savedArticles = articleRepository.selectAll(); + assertEquals(0, savedArticles.size()); + } + + @Test + public void whenInsertingTwoArticlesWithSamePrimaryKeyInASingleTransaction_thenRollback() throws SQLException { + articleRepository.deleteTable(); + articleRepository.createTable(); + + try { + con.setAutoCommit(false); + + UUID articleId = UUID.randomUUID(); + + Article article = new Article(articleId, "Guide to CockroachDB in Java", "baeldung"); + articleRepository.insertArticle(article); + + article = new Article(articleId, "A Guide to MongoDB with Java", "baeldung"); + articleRepository.insertArticle(article); + + con.commit(); + } catch (Exception e) { + con.rollback(); + } finally { + con.setAutoCommit(true); + } + + List
    savedArticles = articleRepository.selectAll(); + assertEquals(0, savedArticles.size()); + } + + @Test + public void whenInsertingTwoArticlesInASingleTransaction_thenInserted() throws SQLException { + articleRepository.deleteTable(); + articleRepository.createTable(); + + try { + con.setAutoCommit(false); + + Article article = new Article(UUID.randomUUID(), "Guide to CockroachDB in Java", "baeldung"); + articleRepository.insertArticle(article); + + article = new Article(UUID.randomUUID(), "A Guide to MongoDB with Java", "baeldung"); + articleRepository.insertArticle(article); + + con.commit(); + } catch (Exception e) { + con.rollback(); + } finally { + con.setAutoCommit(true); + } + + List
    savedArticles = articleRepository.selectAll(); + assertEquals(2, savedArticles.size()); + assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("Guide to CockroachDB in Java"))); + assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("A Guide to MongoDB with Java"))); + } + + @After + public void disconnect() throws SQLException { + articleRepository = null; + con.close(); + con = null; + } +} diff --git a/persistence-modules/java-jdbi/pom.xml b/persistence-modules/java-jdbi/pom.xml index a823141bc5..885906fcd0 100644 --- a/persistence-modules/java-jdbi/pom.xml +++ b/persistence-modules/java-jdbi/pom.xml @@ -1,7 +1,6 @@ - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 java-jdbi 1.0-SNAPSHOT diff --git a/persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiIntegrationTest.java b/persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiIntegrationTest.java new file mode 100644 index 0000000000..dbc8a396ce --- /dev/null +++ b/persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiIntegrationTest.java @@ -0,0 +1,338 @@ +package com.baeldung.persistence.jdbi; + +import org.jdbi.v3.core.Handle; +import org.jdbi.v3.core.Jdbi; +import org.jdbi.v3.core.result.ResultBearing; +import org.jdbi.v3.core.result.ResultProducer; +import org.jdbi.v3.core.statement.Query; +import org.jdbi.v3.core.statement.StatementContext; +import org.jdbi.v3.core.statement.Update; +import org.junit.Test; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.*; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import static org.junit.Assert.*; + +public class JdbiIntegrationTest { + + @Test + public void whenJdbiCreated_thenSuccess() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + + Jdbi.create("WRONG"); + } + + @Test + public void whenJdbiWithProperties_thenSuccess() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.open().close(); + Properties properties = new Properties(); + properties.setProperty("username", "sa"); + properties.setProperty("password", ""); + jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", properties); + jdbi.open().close(); + } + + @Test + public void whenHandle_thenBoh() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + final Handle[] handleRef = new Handle[1]; + boolean closed = jdbi.withHandle(handle -> { + handleRef[0] = handle; + return handle.isClosed(); + }); + + assertFalse(closed); + assertTrue(handleRef[0].isClosed()); + } + + @Test + public void whenTableCreated_thenInsertIsPossible() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + int updateCount = handle.execute("create table PROJECT_1 (id integer identity, name varchar(50), url varchar(100))"); + + assertEquals(0, updateCount); + + updateCount = handle.execute("INSERT INTO PROJECT_1 VALUES (1, 'tutorials', 'github.com/eugenp/tutorials')"); + + assertEquals(1, updateCount); + }); + } + + @Test + public void whenIdentityColumn_thenInsertReturnsNewId() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_2 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + Update update = handle.createUpdate( + "INSERT INTO PROJECT_2 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')"); + ResultBearing generatedKeys = update.executeAndReturnGeneratedKeys(); + + assertEquals(0, generatedKeys.mapToMap().findOnly().get("id")); + + update = handle.createUpdate( + "INSERT INTO PROJECT_2 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')"); + + assertEquals(1, generatedKeys.mapToMap().findOnly().get("id")); + }); + } + + @Test + public void whenSelectMapToMap_thenResultsAreMapEntries() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_3 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + handle.execute("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')"); + handle.execute("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')"); + Query query = handle.createQuery("select * from PROJECT_3 order by id"); + List> list = query.mapToMap().list(); + + assertEquals("tutorials", list.get(0).get("name")); + assertEquals("REST with Spring", list.get(1).get("name")); + }); + } + + @Test + public void whenSelectMapToString_thenResultIsString() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_4 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + handle.execute("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')"); + handle.execute("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')"); + Query query = handle.createQuery("select name, url from PROJECT_4 order by id"); + List list = query.mapTo(String.class).list(); + + assertEquals("tutorials", list.get(0)); + assertEquals("REST with Spring", list.get(1)); + }); + } + + @Test + public void whenSelectMapToString_thenStream() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + handle.execute("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')"); + handle.execute("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')"); + Query query = handle.createQuery("select name, url from PROJECT_5 order by id"); + query.mapTo(String.class).useStream((Stream stream) -> assertEquals("tutorials", stream.findFirst().get())); + }); + } + + @Test + public void whenNoResults_thenFindFirstReturnsNone() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_6 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + + assertFalse(handle.createQuery("select * from project_6").mapToMap().findFirst().isPresent()); + }); + } + + @Test + public void whenMultipleResults_thenFindFirstReturnsFirst() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_7 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + handle.execute("INSERT INTO PROJECT_7 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')"); + handle.execute("INSERT INTO PROJECT_7 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')"); + + Query query = handle.createQuery("select * from project_7 order by id"); + Optional> first = query.mapToMap().findFirst(); + + assertTrue(first.isPresent()); + assertEquals("tutorials", first.get().get("name")); + }); + } + + @Test + public void whenNoResults_thenFindOnlyThrows() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_8 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + + try { + handle.createQuery("select * from project_8").mapToMap().findOnly(); + + fail("Exception expected"); + } catch (Exception e) { + e.printStackTrace(); + } + }); + } + + @Test + public void whenMultipleResults_thenFindOnlyThrows() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_9 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + handle.execute("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')"); + handle.execute("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')"); + + try { + Query query = handle.createQuery("select * from project_9"); + Map onlyResult = query.mapToMap().findOnly(); + + fail("Exception expected"); + } catch (Exception e) { + e.printStackTrace(); + } + }); + } + + @Test + public void whenParameters_thenReplacement() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_10 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + Update update1 = handle.createUpdate("INSERT INTO PROJECT_10 (NAME, URL) VALUES (?, ?)"); + update1.bind(0, "tutorials"); + update1.bind(1, "github.com/eugenp/tutorials"); + int rows = update1.execute(); + + assertEquals(1, rows); + + Update update2 = handle.createUpdate("INSERT INTO PROJECT_10 (NAME, URL) VALUES (:name, :url)"); + update2.bind("name", "REST with Spring"); + update2.bind("url", "github.com/eugenp/REST-With-Spring"); + rows = update2.execute(); + + assertEquals(1, rows); + + List> list = + handle.select("SELECT * FROM PROJECT_10 WHERE NAME = 'tutorials'").mapToMap().list(); + + assertEquals(1, list.size()); + + list = handle.select("SELECT * FROM PROJECT_10 WHERE NAME = 'REST with Spring'").mapToMap().list(); + + assertEquals(1, list.size()); + }); + } + + @Test + public void whenMultipleParameters_thenReplacement() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_11 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + Update update = handle.createUpdate("INSERT INTO PROJECT_11 (NAME, URL) VALUES (:name, :url)"); + Map params = new HashMap<>(); + params.put("name", "REST with Spring"); + params.put("url", "github.com/eugenp/REST-With-Spring"); + update.bindMap(params); + int rows = update.execute(); + + assertEquals(1, rows); + + List> list = + handle.select("SELECT * FROM PROJECT_11").mapToMap().list(); + + assertEquals(1, list.size()); + + class Params { + private String name; + private String url; + + public Params(String name, String url) { + this.name = name; + this.url = url; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + } + + update.bindBean(new Params("tutorials", "github.com/eugenp/tutorials")); + rows = update.execute(); + + assertEquals(1, rows); + + list = handle.select("SELECT * FROM PROJECT_11").mapToMap().list(); + + assertEquals(2, list.size()); + }); + } + + @Test + public void whenTransactionRollback_thenNoDataInserted() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.useTransaction(h -> { + handle.execute("create table PROJECT_12 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + handle.execute("INSERT INTO PROJECT_12 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')"); + handle.execute("INSERT INTO PROJECT_12 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')"); + handle.rollback(); + List> list = handle.select("SELECT * FROM PROJECT_12").mapToMap().list(); + + assertEquals(0, list.size()); + }); + }); + } + + @Test + public void whenTransactionRollbackThenCommit_thenOnlyLastInserted() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.useTransaction((Handle h) -> { + assertEquals(handle, h); + + handle.execute("create table PROJECT_13 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + handle.execute("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')"); + handle.rollback(); + handle.begin(); + handle.execute("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')"); + handle.rollback(); + handle.begin(); + handle.execute("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')"); + handle.execute("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')"); + handle.commit(); + }); + List> list = handle.select("SELECT * FROM PROJECT_13").mapToMap().list(); + + assertEquals(2, list.size()); + }); + } + + + @Test + public void whenException_thenTransactionIsRolledBack() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + try { + handle.useTransaction(h -> { + h.execute("create table PROJECT_14 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + h.execute("INSERT INTO PROJECT_14 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')"); + List> list = handle.select("SELECT * FROM PROJECT_14").mapToMap().list(); + + assertTrue(h.isInTransaction()); + assertEquals(1, list.size()); + + throw new Exception("rollback"); + }); + } catch (Exception ignored) {} + List> list = handle.select("SELECT * FROM PROJECT_14").mapToMap().list(); + + assertFalse(handle.isInTransaction()); + assertEquals(0, list.size()); + }); + } + +} diff --git a/persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiTest.java b/persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiTest.java deleted file mode 100644 index 503bf90fdb..0000000000 --- a/persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiTest.java +++ /dev/null @@ -1,338 +0,0 @@ -package com.baeldung.persistence.jdbi; - -import org.jdbi.v3.core.Handle; -import org.jdbi.v3.core.Jdbi; -import org.jdbi.v3.core.result.ResultBearing; -import org.jdbi.v3.core.result.ResultProducer; -import org.jdbi.v3.core.statement.Query; -import org.jdbi.v3.core.statement.StatementContext; -import org.jdbi.v3.core.statement.Update; -import org.junit.Test; - -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.*; -import java.util.function.Supplier; -import java.util.stream.Stream; - -import static org.junit.Assert.*; - -public class JdbiTest { - - @Test - public void whenJdbiCreated_thenSuccess() { - Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); - - Jdbi.create("WRONG"); - } - - @Test - public void whenJdbiWithProperties_thenSuccess() { - Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); - jdbi.open().close(); - Properties properties = new Properties(); - properties.setProperty("username", "sa"); - properties.setProperty("password", ""); - jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", properties); - jdbi.open().close(); - } - - @Test - public void whenHandle_thenBoh() { - Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); - final Handle[] handleRef = new Handle[1]; - boolean closed = jdbi.withHandle(handle -> { - handleRef[0] = handle; - return handle.isClosed(); - }); - - assertFalse(closed); - assertTrue(handleRef[0].isClosed()); - } - - @Test - public void whenTableCreated_thenInsertIsPossible() { - Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); - jdbi.useHandle(handle -> { - int updateCount = handle.execute("create table PROJECT_1 (id integer identity, name varchar(50), url varchar(100))"); - - assertEquals(0, updateCount); - - updateCount = handle.execute("INSERT INTO PROJECT_1 VALUES (1, 'tutorials', 'github.com/eugenp/tutorials')"); - - assertEquals(1, updateCount); - }); - } - - @Test - public void whenIdentityColumn_thenInsertReturnsNewId() { - Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); - jdbi.useHandle(handle -> { - handle.execute("create table PROJECT_2 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); - Update update = handle.createUpdate( - "INSERT INTO PROJECT_2 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')"); - ResultBearing generatedKeys = update.executeAndReturnGeneratedKeys(); - - assertEquals(0, generatedKeys.mapToMap().findOnly().get("id")); - - update = handle.createUpdate( - "INSERT INTO PROJECT_2 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')"); - - assertEquals(1, generatedKeys.mapToMap().findOnly().get("id")); - }); - } - - @Test - public void whenSelectMapToMap_thenResultsAreMapEntries() { - Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); - jdbi.useHandle(handle -> { - handle.execute("create table PROJECT_3 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); - handle.execute("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')"); - handle.execute("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')"); - Query query = handle.createQuery("select * from PROJECT_3 order by id"); - List> list = query.mapToMap().list(); - - assertEquals("tutorials", list.get(0).get("name")); - assertEquals("REST with Spring", list.get(1).get("name")); - }); - } - - @Test - public void whenSelectMapToString_thenResultIsString() { - Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); - jdbi.useHandle(handle -> { - handle.execute("create table PROJECT_4 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); - handle.execute("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')"); - handle.execute("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')"); - Query query = handle.createQuery("select name, url from PROJECT_4 order by id"); - List list = query.mapTo(String.class).list(); - - assertEquals("tutorials", list.get(0)); - assertEquals("REST with Spring", list.get(1)); - }); - } - - @Test - public void whenSelectMapToString_thenStream() { - Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); - jdbi.useHandle(handle -> { - handle.execute("create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); - handle.execute("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')"); - handle.execute("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')"); - Query query = handle.createQuery("select name, url from PROJECT_5 order by id"); - query.mapTo(String.class).useStream((Stream stream) -> assertEquals("tutorials", stream.findFirst().get())); - }); - } - - @Test - public void whenNoResults_thenFindFirstReturnsNone() { - Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); - jdbi.useHandle(handle -> { - handle.execute("create table PROJECT_6 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); - - assertFalse(handle.createQuery("select * from project_6").mapToMap().findFirst().isPresent()); - }); - } - - @Test - public void whenMultipleResults_thenFindFirstReturnsFirst() { - Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); - jdbi.useHandle(handle -> { - handle.execute("create table PROJECT_7 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); - handle.execute("INSERT INTO PROJECT_7 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')"); - handle.execute("INSERT INTO PROJECT_7 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')"); - - Query query = handle.createQuery("select * from project_7 order by id"); - Optional> first = query.mapToMap().findFirst(); - - assertTrue(first.isPresent()); - assertEquals("tutorials", first.get().get("name")); - }); - } - - @Test - public void whenNoResults_thenFindOnlyThrows() { - Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); - jdbi.useHandle(handle -> { - handle.execute("create table PROJECT_8 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); - - try { - handle.createQuery("select * from project_8").mapToMap().findOnly(); - - fail("Exception expected"); - } catch (Exception e) { - e.printStackTrace(); - } - }); - } - - @Test - public void whenMultipleResults_thenFindOnlyThrows() { - Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); - jdbi.useHandle(handle -> { - handle.execute("create table PROJECT_9 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); - handle.execute("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')"); - handle.execute("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')"); - - try { - Query query = handle.createQuery("select * from project_9"); - Map onlyResult = query.mapToMap().findOnly(); - - fail("Exception expected"); - } catch (Exception e) { - e.printStackTrace(); - } - }); - } - - @Test - public void whenParameters_thenReplacement() { - Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); - jdbi.useHandle(handle -> { - handle.execute("create table PROJECT_10 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); - Update update1 = handle.createUpdate("INSERT INTO PROJECT_10 (NAME, URL) VALUES (?, ?)"); - update1.bind(0, "tutorials"); - update1.bind(1, "github.com/eugenp/tutorials"); - int rows = update1.execute(); - - assertEquals(1, rows); - - Update update2 = handle.createUpdate("INSERT INTO PROJECT_10 (NAME, URL) VALUES (:name, :url)"); - update2.bind("name", "REST with Spring"); - update2.bind("url", "github.com/eugenp/REST-With-Spring"); - rows = update2.execute(); - - assertEquals(1, rows); - - List> list = - handle.select("SELECT * FROM PROJECT_10 WHERE NAME = 'tutorials'").mapToMap().list(); - - assertEquals(1, list.size()); - - list = handle.select("SELECT * FROM PROJECT_10 WHERE NAME = 'REST with Spring'").mapToMap().list(); - - assertEquals(1, list.size()); - }); - } - - @Test - public void whenMultipleParameters_thenReplacement() { - Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); - jdbi.useHandle(handle -> { - handle.execute("create table PROJECT_11 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); - Update update = handle.createUpdate("INSERT INTO PROJECT_11 (NAME, URL) VALUES (:name, :url)"); - Map params = new HashMap<>(); - params.put("name", "REST with Spring"); - params.put("url", "github.com/eugenp/REST-With-Spring"); - update.bindMap(params); - int rows = update.execute(); - - assertEquals(1, rows); - - List> list = - handle.select("SELECT * FROM PROJECT_11").mapToMap().list(); - - assertEquals(1, list.size()); - - class Params { - private String name; - private String url; - - public Params(String name, String url) { - this.name = name; - this.url = url; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - } - - update.bindBean(new Params("tutorials", "github.com/eugenp/tutorials")); - rows = update.execute(); - - assertEquals(1, rows); - - list = handle.select("SELECT * FROM PROJECT_11").mapToMap().list(); - - assertEquals(2, list.size()); - }); - } - - @Test - public void whenTransactionRollback_thenNoDataInserted() { - Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); - jdbi.useHandle(handle -> { - handle.useTransaction(h -> { - handle.execute("create table PROJECT_12 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); - handle.execute("INSERT INTO PROJECT_12 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')"); - handle.execute("INSERT INTO PROJECT_12 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')"); - handle.rollback(); - List> list = handle.select("SELECT * FROM PROJECT_12").mapToMap().list(); - - assertEquals(0, list.size()); - }); - }); - } - - @Test - public void whenTransactionRollbackThenCommit_thenOnlyLastInserted() { - Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); - jdbi.useHandle(handle -> { - handle.useTransaction((Handle h) -> { - assertEquals(handle, h); - - handle.execute("create table PROJECT_13 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); - handle.execute("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')"); - handle.rollback(); - handle.begin(); - handle.execute("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')"); - handle.rollback(); - handle.begin(); - handle.execute("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')"); - handle.execute("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')"); - handle.commit(); - }); - List> list = handle.select("SELECT * FROM PROJECT_13").mapToMap().list(); - - assertEquals(2, list.size()); - }); - } - - - @Test - public void whenException_thenTransactionIsRolledBack() { - Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); - jdbi.useHandle(handle -> { - try { - handle.useTransaction(h -> { - h.execute("create table PROJECT_14 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); - h.execute("INSERT INTO PROJECT_14 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')"); - List> list = handle.select("SELECT * FROM PROJECT_14").mapToMap().list(); - - assertTrue(h.isInTransaction()); - assertEquals(1, list.size()); - - throw new Exception("rollback"); - }); - } catch (Exception ignored) {} - List> list = handle.select("SELECT * FROM PROJECT_14").mapToMap().list(); - - assertFalse(handle.isInTransaction()); - assertEquals(0, list.size()); - }); - } - -} diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md new file mode 100644 index 0000000000..418e0a67e2 --- /dev/null +++ b/persistence-modules/java-jpa/README.md @@ -0,0 +1,4 @@ +# Relevant Articles + +- [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping) +- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) \ No newline at end of file diff --git a/persistence-modules/java-jpa/pom.xml b/persistence-modules/java-jpa/pom.xml new file mode 100644 index 0000000000..78764f7148 --- /dev/null +++ b/persistence-modules/java-jpa/pom.xml @@ -0,0 +1,32 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + ../../pom.xml + + 4.0.0 + + java-jpa + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + com.h2database + h2 + ${h2.version} + + + + + 5.3.1.Final + 1.4.197 + + \ No newline at end of file diff --git a/jpa-storedprocedure/src/main/java/com/baeldung/jpa/model/Car.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/Car.java similarity index 100% rename from jpa-storedprocedure/src/main/java/com/baeldung/jpa/model/Car.java rename to persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/Car.java diff --git a/jpa-storedprocedure/src/main/java/com/baeldung/jpa/model/QueryParameter.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/QueryParameter.java similarity index 100% rename from jpa-storedprocedure/src/main/java/com/baeldung/jpa/model/QueryParameter.java rename to persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/QueryParameter.java diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/sqlresultsetmapping/Employee.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/sqlresultsetmapping/Employee.java new file mode 100644 index 0000000000..bec1b8845a --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/sqlresultsetmapping/Employee.java @@ -0,0 +1,43 @@ +package com.baeldung.sqlresultsetmapping; + +import javax.persistence.*; + + +@SqlResultSetMapping( + name="EmployeeResult", + entities={ + @EntityResult( + entityClass = com.baeldung.sqlresultsetmapping.Employee.class, + fields={@FieldResult(name="id",column="employeeNumber"), + @FieldResult(name="name", column="name")} + ) + } +) +@NamedNativeQuery( + name="Employees", + query="SELECT id as employeeNumber, name FROM EMPLOYEE", + resultSetMapping = "EmployeeResult" +) +@Entity +public class Employee { + + @Id + private Long id; + private String 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; + } +} diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/sqlresultsetmapping/ScheduledDay.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/sqlresultsetmapping/ScheduledDay.java new file mode 100644 index 0000000000..7e332bc67a --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/sqlresultsetmapping/ScheduledDay.java @@ -0,0 +1,58 @@ +package com.baeldung.sqlresultsetmapping; + +import javax.persistence.*; + +@SqlResultSetMappings(value = { + @SqlResultSetMapping(name = "ScheduleResult", + classes = { @ConstructorResult(targetClass = com.baeldung.sqlresultsetmapping.ScheduledDay.class, + columns = { @ColumnResult(name = "id", type = Long.class), + @ColumnResult(name = "employeeId", type = Long.class), + @ColumnResult(name = "dayOfWeek") }) }), + @SqlResultSetMapping(name = "FridayEmployeeResult", + columns = { @ColumnResult(name = "employeeId") }), + @SqlResultSetMapping(name = "EmployeeScheduleResults", + entities = { @EntityResult(entityClass = com.baeldung.sqlresultsetmapping.Employee.class), + @EntityResult(entityClass = com.baeldung.sqlresultsetmapping.ScheduledDay.class) + }) }) +@NamedNativeQuery(name = "FridayEmployees", + query = "SELECT employeeId FROM schedule_days WHERE dayOfWeek = 'FRIDAY'", + resultSetMapping = "FridayEmployeeResult") + +@NamedNativeQuery(name = "Schedules", + query = "SELECT * FROM schedule_days WHERE employeeId = 3", + resultSetMapping = "ScheduleResult") +@Entity +@Table(name = "SCHEDULE_DAYS") +public class ScheduledDay { + + @Id + @GeneratedValue + private Long id; + private Long employeeId; + private String dayOfWeek; + + public ScheduledDay() { + } + + public ScheduledDay(Long id, Long employeeId, String dayofWeek) { + this.id = id; + this.employeeId = employeeId; + this.dayOfWeek = dayofWeek; + } + + public Long getEmployeeId() { + return employeeId; + } + + public void setEmployeeId(Long employeeId) { + this.employeeId = employeeId; + } + + public String getDayOfWeek() { + return dayOfWeek; + } + + public void setDayOfWeek(String dayOfWeek) { + this.dayOfWeek = dayOfWeek; + } +} diff --git a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..3d881673b2 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,37 @@ + + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.sqlresultsetmapping.ScheduledDay + + + + + + + + + + + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.model.Car + + + + + + + + + + + \ No newline at end of file diff --git a/jpa-storedprocedure/src/main/resources/config/database/FindCarByYearProcedureMySQL.sql b/persistence-modules/java-jpa/src/main/resources/config/database/FindCarByYearProcedureMySQL.sql similarity index 100% rename from jpa-storedprocedure/src/main/resources/config/database/FindCarByYearProcedureMySQL.sql rename to persistence-modules/java-jpa/src/main/resources/config/database/FindCarByYearProcedureMySQL.sql diff --git a/jpa-storedprocedure/src/main/resources/config/database/create_table_mysql.sql b/persistence-modules/java-jpa/src/main/resources/config/database/create_table_mysql.sql similarity index 100% rename from jpa-storedprocedure/src/main/resources/config/database/create_table_mysql.sql rename to persistence-modules/java-jpa/src/main/resources/config/database/create_table_mysql.sql diff --git a/jpa-storedprocedure/src/main/resources/config/database/insert_cars.sql b/persistence-modules/java-jpa/src/main/resources/config/database/insert_cars.sql similarity index 100% rename from jpa-storedprocedure/src/main/resources/config/database/insert_cars.sql rename to persistence-modules/java-jpa/src/main/resources/config/database/insert_cars.sql diff --git a/persistence-modules/java-jpa/src/main/resources/database.sql b/persistence-modules/java-jpa/src/main/resources/database.sql new file mode 100644 index 0000000000..bd2bb68599 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/resources/database.sql @@ -0,0 +1,17 @@ +CREATE TABLE EMPLOYEE +(id BIGINT, + name VARCHAR(10)); + +INSERT INTO EMPLOYEE VALUES (1, 'JOHN'); +INSERT INTO EMPLOYEE VALUES (2, 'MARY'); +INSERT INTO EMPLOYEE VALUES (3, 'FRANK'); + +CREATE TABLE SCHEDULE_DAYS +(id IDENTITY, + employeeId BIGINT, + dayOfWeek VARCHAR(10)); + +INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (1, 'FRIDAY'); +INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (2, 'SATURDAY'); +INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (3, 'MONDAY'); +INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (3, 'FRIDAY'); diff --git a/persistence-modules/java-jpa/src/main/resources/logback.xml b/persistence-modules/java-jpa/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java new file mode 100644 index 0000000000..8bc8c854da --- /dev/null +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java @@ -0,0 +1,76 @@ +package com.baeldung.jpa.storedprocedure; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.ParameterMode; +import javax.persistence.Persistence; +import javax.persistence.StoredProcedureQuery; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.jpa.model.Car; + +public class StoredProcedureLiveTest { + + private static EntityManagerFactory factory = null; + private static EntityManager entityManager = null; + + @BeforeClass + public static void init() { + factory = Persistence.createEntityManagerFactory("jpa-db"); + entityManager = factory.createEntityManager(); + } + + @Before + public void setup() { + } + + @Test + public void createCarTest() { + final EntityTransaction transaction = entityManager.getTransaction(); + try { + transaction.begin(); + final Car car = new Car("Fiat Marea", 2015); + entityManager.persist(car); + transaction.commit(); + } catch (final Exception e) { + System.out.println(e.getCause()); + if (transaction.isActive()) { + transaction.rollback(); + } + } + } + + @Test + public void findCarsByYearNamedProcedure() { + final StoredProcedureQuery findByYearProcedure = entityManager.createNamedStoredProcedureQuery("findByYearProcedure"); + final StoredProcedureQuery storedProcedure = findByYearProcedure.setParameter("p_year", 2015); + storedProcedure.getResultList() + .forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); + } + + @Test + public void findCarsByYearNoNamed() { + final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class) + .registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN) + .setParameter(1, 2015); + storedProcedure.getResultList() + .forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); + } + + @AfterClass + public static void destroy() { + + if (entityManager != null) { + entityManager.close(); + } + if (factory != null) { + factory.close(); + } + } +} diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/sqlresultsetmapping/SqlResultSetMappingUnitTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/sqlresultsetmapping/SqlResultSetMappingUnitTest.java new file mode 100644 index 0000000000..4e01095278 --- /dev/null +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/sqlresultsetmapping/SqlResultSetMappingUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung.sqlresultsetmapping; + +import static org.junit.Assert.*; + +import org.junit.jupiter.api.*; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.persistence.Query; +import java.util.Collections; +import java.util.List; + +public class SqlResultSetMappingUnitTest { + + private static EntityManager em; + private static EntityManagerFactory emFactory; + + @BeforeAll + public static void setup() { + emFactory = Persistence.createEntityManagerFactory("java-jpa-scheduled-day"); + em = emFactory.createEntityManager(); + } + + @Test + public void whenNamedQuery_thenColumnResult() { + List employeeIds = em.createNamedQuery("FridayEmployees").getResultList(); + assertEquals(2, employeeIds.size()); + } + + @Test + public void whenNamedQuery_thenConstructorResult() { + List scheduleDays = Collections.checkedList(em.createNamedQuery("Schedules", ScheduledDay.class).getResultList(), ScheduledDay.class); + assertEquals(2, scheduleDays.size()); + assertTrue(scheduleDays.stream().allMatch(c -> c.getEmployeeId().longValue() == 3)); + } + + @Test + public void whenNamedQuery_thenSingleEntityResult() { + List employees = Collections.checkedList(em.createNamedQuery("Employees").getResultList(), Employee.class); + assertEquals(3, employees.size()); + assertTrue(employees.stream().allMatch(c -> c.getClass() == Employee.class)); + } + + @Test + public void whenNamedQuery_thenMultipleEntityResult() { + final Query query = em.createNativeQuery("SELECT e.id, e.name, d.id, d.employeeId, d.dayOfWeek " + + " FROM employee e, schedule_days d " + + " WHERE e.id = d.employeeId", "EmployeeScheduleResults"); + List results = query.getResultList(); + assertEquals(4, results.size()); + assertTrue(results.get(0).length == 2); + + Employee emp = (Employee) results.get(1)[0]; + ScheduledDay day = (ScheduledDay) results.get(1)[1]; + + assertTrue(day.getEmployeeId() == emp.getId()); + } + + @AfterAll + public static void destroy() { + + if (em != null) { + em.close(); + } + if (emFactory != null) { + emFactory.close(); + } + } +} diff --git a/persistence-modules/java-jpa/src/test/resources/employees.sql b/persistence-modules/java-jpa/src/test/resources/employees.sql new file mode 100644 index 0000000000..feace36e2c --- /dev/null +++ b/persistence-modules/java-jpa/src/test/resources/employees.sql @@ -0,0 +1,3 @@ +INSERT INTO employee (1, "JOHN"); +INSERT INTO employee (2, "MARY"); +INSERT INTO employee (3, "FRANK"); \ No newline at end of file diff --git a/jpa-storedprocedure/src/test/resources/persistence.xml b/persistence-modules/java-jpa/src/test/resources/persistence.xml similarity index 100% rename from jpa-storedprocedure/src/test/resources/persistence.xml rename to persistence-modules/java-jpa/src/test/resources/persistence.xml diff --git a/persistence-modules/java-jpa/src/test/resources/scheduledDays.sql b/persistence-modules/java-jpa/src/test/resources/scheduledDays.sql new file mode 100644 index 0000000000..df1d4ed09e --- /dev/null +++ b/persistence-modules/java-jpa/src/test/resources/scheduledDays.sql @@ -0,0 +1,10 @@ +INSERT INTO SCHEDULE_DAYS (1, 13, 21, 'FRIDAY'); +INSERT INTO SCHEDULE_DAYS (2, 8, 4, 'SATURDAY'); +INSERT INTO SCHEDULE_DAYS (3, 8, 4, 'FRIDAY'); + + +-- private Long id; +-- private Long employeeId; +-- private Time in; +-- private Time out; +-- private DayOfWeek dayOfWeek; \ No newline at end of file diff --git a/persistence-modules/java-mongodb/pom.xml b/persistence-modules/java-mongodb/pom.xml index ba8fabb9a5..bbc48f54c2 100644 --- a/persistence-modules/java-mongodb/pom.xml +++ b/persistence-modules/java-mongodb/pom.xml @@ -1,8 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 - com.baeldung java-mongodb 1.0-SNAPSHOT diff --git a/persistence-modules/java-mongodb/src/main/resources/logback.xml b/persistence-modules/java-mongodb/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/java-mongodb/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/liquibase/pom.xml b/persistence-modules/liquibase/pom.xml index a18ced0d71..cb2bee8d48 100644 --- a/persistence-modules/liquibase/pom.xml +++ b/persistence-modules/liquibase/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 liquibase @@ -20,7 +20,7 @@ - baeldung-liquibase-demo + liquibase org.liquibase diff --git a/persistence-modules/liquibase/src/main/resources/logback.xml b/persistence-modules/liquibase/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/liquibase/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/querydsl/pom.xml b/persistence-modules/querydsl/pom.xml index 4c20d673a3..d3bf1b1fb7 100644 --- a/persistence-modules/querydsl/pom.xml +++ b/persistence-modules/querydsl/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung querydsl @@ -147,8 +147,6 @@ - UTF-8 - 1.8 4.3.4.RELEASE 5.2.5.Final 1.0.0.Final diff --git a/persistence-modules/redis/pom.xml b/persistence-modules/redis/pom.xml index 7f7aeda4ad..e5a39d6eac 100644 --- a/persistence-modules/redis/pom.xml +++ b/persistence-modules/redis/pom.xml @@ -1,13 +1,10 @@ - - + 4.0.0 com.baeldung redis 0.1-SNAPSHOT - redis http://maven.apache.org @@ -24,31 +21,27 @@ jedis ${jedis.version} - com.github.kstyrc embedded-redis ${embedded-redis.version} - org.redisson redisson - 3.3.0 + ${redisson.version} - io.lettuce lettuce-core - 5.0.1.RELEASE + ${lettuce-core.version} - - UTF-8 - 2.9.0 0.6 + 3.3.0 + 5.0.1.RELEASE diff --git a/persistence-modules/redis/src/main/resources/logback.xml b/persistence-modules/redis/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/redis/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java index c1ec9bd2f8..5795e9912b 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java @@ -1,28 +1,45 @@ package com.baeldung; -import org.junit.*; -import redis.clients.jedis.*; -import redis.embedded.RedisServer; - import java.io.IOException; +import java.net.ServerSocket; import java.time.Duration; import java.util.HashMap; import java.util.Map; import java.util.Set; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; +import redis.clients.jedis.Pipeline; +import redis.clients.jedis.Response; +import redis.clients.jedis.Transaction; +import redis.embedded.RedisServer; + public class JedisIntegrationTest { - private Jedis jedis; + private static Jedis jedis; private static RedisServer redisServer; - - public JedisIntegrationTest() { - jedis = new Jedis(); - } + private static int port; @BeforeClass public static void setUp() throws IOException { - redisServer = new RedisServer(6379); + + // Take an available port + ServerSocket s = new ServerSocket(0); + port = s.getLocalPort(); + s.close(); + + redisServer = new RedisServer(port); redisServer.start(); + + // Configure JEDIS + jedis = new Jedis("localhost", port); } @AfterClass @@ -178,7 +195,7 @@ public class JedisIntegrationTest { public void givenAPoolConfiguration_thenCreateAJedisPool() { final JedisPoolConfig poolConfig = buildPoolConfig(); - try (JedisPool jedisPool = new JedisPool(poolConfig, "localhost"); Jedis jedis = jedisPool.getResource()) { + try (JedisPool jedisPool = new JedisPool(poolConfig, "localhost", port); Jedis jedis = jedisPool.getResource()) { // do simple operation to verify that the Jedis resource is working // properly diff --git a/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java index 1862d6b035..66f61ae5dd 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java @@ -1,15 +1,20 @@ package com.baeldung; +import java.io.File; +import java.io.IOException; +import java.net.ServerSocket; +import java.nio.charset.Charset; + import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.redisson.Redisson; import org.redisson.api.RedissonClient; import org.redisson.config.Config; -import redis.embedded.RedisServer; -import java.io.File; -import java.io.IOException; +import com.google.common.io.Files; + +import redis.embedded.RedisServer; /** * Created by johnson on 3/9/17. @@ -17,24 +22,33 @@ import java.io.IOException; public class RedissonConfigurationIntegrationTest { private static RedisServer redisServer; private static RedissonClient client; + private static int port; @BeforeClass public static void setUp() throws IOException { - redisServer = new RedisServer(6379); + + // Take an available port + ServerSocket s = new ServerSocket(0); + port = s.getLocalPort(); + s.close(); + + redisServer = new RedisServer(port); redisServer.start(); } @AfterClass public static void destroy() { redisServer.stop(); - client.shutdown(); + if (client != null) { + client.shutdown(); + } } @Test public void givenJavaConfig_thenRedissonConnectToRedis() { Config config = new Config(); config.useSingleServer() - .setAddress("127.0.0.1:6379"); + .setAddress(String.format("127.0.0.1:%s", port)); client = Redisson.create(config); @@ -43,10 +57,11 @@ public class RedissonConfigurationIntegrationTest { @Test public void givenJSONFileConfig_thenRedissonConnectToRedis() throws IOException { - Config config = Config.fromJSON( - new File(getClass().getClassLoader().getResource( - "singleNodeConfig.json").getFile())); - + + File configFile = new File(getClass().getClassLoader().getResource("singleNodeConfig.json").getFile()); + String configContent = Files.toString(configFile, Charset.defaultCharset()).replace("6379", String.valueOf(port)); + + Config config = Config.fromJSON(configContent); client = Redisson.create(config); assert(client != null && client.getKeys().count() >= 0); @@ -54,10 +69,11 @@ public class RedissonConfigurationIntegrationTest { @Test public void givenYAMLFileConfig_thenRedissonConnectToRedis() throws IOException { - Config config = Config.fromYAML( - new File(getClass().getClassLoader().getResource( - "singleNodeConfig.yaml").getFile())); - + + File configFile = new File(getClass().getClassLoader().getResource("singleNodeConfig.yaml").getFile()); + String configContent = Files.toString(configFile, Charset.defaultCharset()).replace("6379", String.valueOf(port)); + + Config config = Config.fromYAML(configContent); client = Redisson.create(config); assert(client != null && client.getKeys().count() >= 0); diff --git a/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java index 766963e5cf..53d77c2699 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java @@ -37,7 +37,9 @@ public class RedissonIntegrationTest { @AfterClass public static void destroy() { redisServer.stop(); - client.shutdown(); + if (client != null) { + client.shutdown(); + } } @Test diff --git a/persistence-modules/solr/pom.xml b/persistence-modules/solr/pom.xml index 34a9722af3..49f2f85856 100644 --- a/persistence-modules/solr/pom.xml +++ b/persistence-modules/solr/pom.xml @@ -1,6 +1,5 @@ - + 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 solr @@ -15,16 +14,16 @@ ../../ - - UTF-8 - - org.apache.solr solr-solrj - 6.4.1 + ${solr.version} + + 6.4.1 + + \ No newline at end of file diff --git a/persistence-modules/solr/src/main/resources/logback.xml b/persistence-modules/solr/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/solr/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-cassandra/pom.xml b/persistence-modules/spring-data-cassandra/pom.xml index 84165564ba..11953a734b 100644 --- a/persistence-modules/spring-data-cassandra/pom.xml +++ b/persistence-modules/spring-data-cassandra/pom.xml @@ -1,5 +1,5 @@ + 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-data-cassandra @@ -9,9 +9,9 @@ com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../../parent-spring + parent-spring-4 + 0.0.1-SNAPSHOT + ../../parent-spring-4 @@ -23,7 +23,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -34,7 +34,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -75,8 +75,6 @@ - UTF-8 - 4.3.4.RELEASE 1.3.2.RELEASE 2.1.5 2.1.9.2 diff --git a/persistence-modules/spring-data-dynamodb/pom.xml b/persistence-modules/spring-data-dynamodb/pom.xml index b115c0e087..4cb805131a 100644 --- a/persistence-modules/spring-data-dynamodb/pom.xml +++ b/persistence-modules/spring-data-dynamodb/pom.xml @@ -1,18 +1,18 @@ + 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-boot-dynamodb + spring-data-dynamodb 0.0.1-SNAPSHOT jar - Spring Boot Actuator - This is simple boot application for Spring boot actuator test + spring-data-dynamodb + This is simple boot application for Spring boot dynamodb test - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 @@ -154,70 +154,16 @@ org.apache.maven.plugins maven-war-plugin - - org.apache.maven.plugins - maven-dependency-plugin - 2.10 - - - copy-dependencies - test-compile - - copy-dependencies - - - test - so,dll,dylib - ${project.basedir}/native-libs - - - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - dynamodb-local DynamoDB Local Release Repository ${dynamodblocal.repository.url} - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - diff --git a/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java index 271c1e29ab..9278c0a12e 100644 --- a/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java +++ b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java @@ -1,14 +1,18 @@ package com.baeldung.spring.data.dynamodb.config; +import org.socialsignin.spring.data.dynamodb.repository.config.EnableDynamoDBRepositories; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.StringUtils; +import org.springframework.web.servlet.handler.HandlerMappingIntrospector; + import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; -import org.socialsignin.spring.data.dynamodb.repository.config.EnableDynamoDBRepositories; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.StringUtils; @Configuration @EnableDynamoDBRepositories(basePackages = "com.baeldung.spring.data.dynamodb.repositories") @@ -22,6 +26,9 @@ public class DynamoDBConfig { @Value("${amazon.aws.secretkey}") private String amazonAWSSecretKey; + + @Autowired + private ApplicationContext context; @Bean public AmazonDynamoDB amazonDynamoDB() { @@ -37,4 +44,8 @@ public class DynamoDBConfig { return new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey); } + @Bean(name = "mvcHandlerMappingIntrospector") + public HandlerMappingIntrospector mvcHandlerMappingIntrospector() { + return new HandlerMappingIntrospector(context); + } } diff --git a/persistence-modules/spring-data-eclipselink/pom.xml b/persistence-modules/spring-data-eclipselink/pom.xml index 524175fcd4..618fa83ee5 100644 --- a/persistence-modules/spring-data-eclipselink/pom.xml +++ b/persistence-modules/spring-data-eclipselink/pom.xml @@ -1,10 +1,8 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-data-eclipselink - 1.0.0-SNAPSHOT spring-data-eclipselink @@ -20,7 +18,6 @@ spring-boot-dependencies ${spring.version} pom - import org.springframework.boot @@ -68,9 +65,6 @@ - UTF-8 - UTF-8 - 1.8 1.5.9.RELEASE 2.7.0 1.4.196 diff --git a/persistence-modules/spring-data-eclipselink/src/main/resources/logback.xml b/persistence-modules/spring-data-eclipselink/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-gemfire/pom.xml b/persistence-modules/spring-data-gemfire/pom.xml index 479eb0c55f..34346c502f 100644 --- a/persistence-modules/spring-data-gemfire/pom.xml +++ b/persistence-modules/spring-data-gemfire/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-data-gemfire diff --git a/persistence-modules/spring-data-gemfire/src/main/resources/logback.xml b/persistence-modules/spring-data-gemfire/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/spring-data-gemfire/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-neo4j/pom.xml b/persistence-modules/spring-data-neo4j/pom.xml index 3405e98edb..2be4df71be 100644 --- a/persistence-modules/spring-data-neo4j/pom.xml +++ b/persistence-modules/spring-data-neo4j/pom.xml @@ -1,8 +1,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-data-neo4j 1.0 @@ -19,65 +17,44 @@ neo4j ${neo4j.version} - org.neo4j neo4j-ogm-core ${neo4j-ogm.version} - org.neo4j neo4j-ogm-embedded-driver ${neo4j-ogm.version} - org.neo4j.driver neo4j-java-driver ${neo4j-java-driver.version} - org.springframework.data spring-data-neo4j ${spring-data-neo4j.version} - - - commons-logging - commons-logging - - - - - org.springframework.data - spring-data-neo4j - ${spring-data-neo4j.version} - test-jar - - com.voodoodyne.jackson.jsog jackson-jsog ${jackson-jsog.version} compile - org.springframework.boot spring-boot-starter-test ${spring-boot.version} test - org.neo4j neo4j-kernel ${neo4j.version} test-jar - org.neo4j.app neo4j-server @@ -90,14 +67,12 @@ - org.neo4j neo4j-ogm-test ${neo4j-ogm.version} test - org.neo4j.test neo4j-harness @@ -108,25 +83,17 @@ org.springframework spring-test ${spring-test.version} - - - commons-logging - commons-logging - - - UTF-8 - UTF-8 - 1.1.1 - 3.1.0 - 4.1.6.RELEASE + 1.6.2 + 3.4.6 + 5.0.1.RELEASE 1.1 - 1.4.3.RELEASE - 4.3.5.RELEASE - 2.1.1 + 2.0.1.RELEASE + 5.0.1.RELEASE + 3.1.2 diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java index 344282d665..9bbc571aee 100644 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java @@ -1,5 +1,6 @@ package com.baeldung.spring.data.neo4j.config; +import org.neo4j.ogm.config.Configuration.Builder; import org.neo4j.ogm.session.SessionFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -8,15 +9,14 @@ import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; @ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" }) @Configuration -@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory") +@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repository") public class MovieDatabaseNeo4jConfiguration { public static final String URL = System.getenv("NEO4J_URL") != null ? System.getenv("NEO4J_URL") : "http://neo4j:movies@localhost:7474"; @Bean public org.neo4j.ogm.config.Configuration getConfiguration() { - org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration(); - config.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver").setURI(URL); + org.neo4j.ogm.config.Configuration config = new Builder().uri(URL).build(); return config; } diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java index fda478e5be..a4cbe4b809 100644 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java @@ -1,26 +1,25 @@ package com.baeldung.spring.data.neo4j.config; +import org.neo4j.ogm.config.Configuration.Builder; import org.neo4j.ogm.session.SessionFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; -import org.springframework.data.neo4j.config.Neo4jConfiguration; import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; +import org.springframework.data.neo4j.transaction.Neo4jTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement @ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" }) -@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory") +@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repository") @Profile({ "embedded", "test" }) -public class MovieDatabaseNeo4jTestConfiguration extends Neo4jConfiguration { +public class MovieDatabaseNeo4jTestConfiguration { @Bean public org.neo4j.ogm.config.Configuration getConfiguration() { - final org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration(); - config.driverConfiguration() - .setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver"); + org.neo4j.ogm.config.Configuration config = new Builder().build(); return config; } @@ -28,5 +27,10 @@ public class MovieDatabaseNeo4jTestConfiguration extends Neo4jConfiguration { public SessionFactory getSessionFactory() { return new SessionFactory(getConfiguration(), "com.baeldung.spring.data.neo4j.domain"); } + + @Bean + public Neo4jTransactionManager transactionManager() { + return new Neo4jTransactionManager(getSessionFactory()); + } } diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java index f2325a334f..455407a92b 100644 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java @@ -1,12 +1,13 @@ package com.baeldung.spring.data.neo4j.domain; -import org.neo4j.ogm.annotation.GraphId; +import org.neo4j.ogm.annotation.GeneratedValue; +import org.neo4j.ogm.annotation.Id; import org.neo4j.ogm.annotation.NodeEntity; import org.neo4j.ogm.annotation.Relationship; @NodeEntity public class Car { - @GraphId + @Id @GeneratedValue private Long id; private String make; diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java index 029754c0fc..996a661b07 100644 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java @@ -2,7 +2,9 @@ package com.baeldung.spring.data.neo4j.domain; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.voodoodyne.jackson.jsog.JSOGGenerator; -import org.neo4j.ogm.annotation.GraphId; + +import org.neo4j.ogm.annotation.GeneratedValue; +import org.neo4j.ogm.annotation.Id; import org.neo4j.ogm.annotation.NodeEntity; import org.neo4j.ogm.annotation.Relationship; @@ -13,7 +15,7 @@ import java.util.List; @NodeEntity public class Movie { - @GraphId + @Id @GeneratedValue Long id; private String title; diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java index dc5a850f29..453ca1c3f3 100644 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java @@ -2,7 +2,9 @@ package com.baeldung.spring.data.neo4j.domain; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.voodoodyne.jackson.jsog.JSOGGenerator; -import org.neo4j.ogm.annotation.GraphId; + +import org.neo4j.ogm.annotation.GeneratedValue; +import org.neo4j.ogm.annotation.Id; import org.neo4j.ogm.annotation.NodeEntity; import org.neo4j.ogm.annotation.Relationship; @@ -11,7 +13,7 @@ import java.util.List; @JsonIdentityInfo(generator = JSOGGenerator.class) @NodeEntity public class Person { - @GraphId + @Id @GeneratedValue Long id; private String name; diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java index 40dabb054b..5a18837dae 100644 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java @@ -3,7 +3,8 @@ package com.baeldung.spring.data.neo4j.domain; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.voodoodyne.jackson.jsog.JSOGGenerator; import org.neo4j.ogm.annotation.EndNode; -import org.neo4j.ogm.annotation.GraphId; +import org.neo4j.ogm.annotation.GeneratedValue; +import org.neo4j.ogm.annotation.Id; import org.neo4j.ogm.annotation.RelationshipEntity; import org.neo4j.ogm.annotation.StartNode; @@ -12,8 +13,8 @@ import java.util.Collection; @JsonIdentityInfo(generator = JSOGGenerator.class) @RelationshipEntity(type = "ACTED_IN") public class Role { - @GraphId - Long id; + @Id @GeneratedValue + Long id; private Collection roles; @StartNode private Person person; diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/MovieRepository.java similarity index 78% rename from persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/MovieRepository.java index afb82551e7..dde946ea73 100644 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/MovieRepository.java @@ -1,8 +1,8 @@ -package com.baeldung.spring.data.neo4j.repostory; +package com.baeldung.spring.data.neo4j.repository; import com.baeldung.spring.data.neo4j.domain.Movie; import org.springframework.data.neo4j.annotation.Query; -import org.springframework.data.neo4j.repository.GraphRepository; +import org.springframework.data.neo4j.repository.Neo4jRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; @@ -11,7 +11,7 @@ import java.util.List; import java.util.Map; @Repository -public interface MovieRepository extends GraphRepository { +public interface MovieRepository extends Neo4jRepository { Movie findByTitle(@Param("title") String title); diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/PersonRepository.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/PersonRepository.java new file mode 100644 index 0000000000..22094d26b6 --- /dev/null +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/PersonRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.data.neo4j.repository; + +import com.baeldung.spring.data.neo4j.domain.Person; +import org.springframework.data.neo4j.repository.Neo4jRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PersonRepository extends Neo4jRepository { +} diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java deleted file mode 100644 index 4ac40ef75b..0000000000 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.spring.data.neo4j.repostory; - -import com.baeldung.spring.data.neo4j.domain.Person; -import org.springframework.data.neo4j.repository.GraphRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface PersonRepository extends GraphRepository { -} diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java index ae1f6eb8e5..086bf48bfa 100644 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java @@ -1,10 +1,11 @@ package com.baeldung.spring.data.neo4j.services; -import com.baeldung.spring.data.neo4j.repostory.MovieRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import com.baeldung.spring.data.neo4j.repository.MovieRepository; + import java.util.*; @Service diff --git a/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java index 06b31667dd..96e5e76402 100644 --- a/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java +++ b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java @@ -12,14 +12,12 @@ import org.neo4j.ogm.session.SessionFactory; import com.baeldung.spring.data.neo4j.domain.Car; import com.baeldung.spring.data.neo4j.domain.Company; -import org.neo4j.ogm.transaction.Transaction; public class Neo4jOgmLiveTest { @Test public void testOgm() { - Configuration conf = new Configuration(); - conf.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver"); + Configuration conf = new Configuration.Builder().build(); SessionFactory factory = new SessionFactory(conf, "com.baeldung.spring.data.neo4j.domain"); Session session = factory.openSession(); diff --git a/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java index 95bc38aafc..3d9215f32f 100644 --- a/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java @@ -4,8 +4,9 @@ import com.baeldung.spring.data.neo4j.config.MovieDatabaseNeo4jTestConfiguration import com.baeldung.spring.data.neo4j.domain.Movie; import com.baeldung.spring.data.neo4j.domain.Person; import com.baeldung.spring.data.neo4j.domain.Role; -import com.baeldung.spring.data.neo4j.repostory.MovieRepository; -import com.baeldung.spring.data.neo4j.repostory.PersonRepository; +import com.baeldung.spring.data.neo4j.repository.MovieRepository; +import com.baeldung.spring.data.neo4j.repository.PersonRepository; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -50,10 +51,10 @@ public class MovieRepositoryIntegrationTest { Role charlie = new Role(); charlie.setMovie(italianJob); charlie.setPerson(mark); - Collection roleNames = new HashSet(); + Collection roleNames = new HashSet<>(); roleNames.add("Charlie Croker"); charlie.setRoles(roleNames); - List roles = new ArrayList(); + List roles = new ArrayList<>(); roles.add(charlie); italianJob.setRoles(roles); movieRepository.save(italianJob); diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index 26d5c6bddf..5981bf41e0 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -1,6 +1,5 @@ - + 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-data-redis @@ -9,9 +8,9 @@ com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../../parent-spring + parent-spring-5 + 0.0.1-SNAPSHOT + ../../parent-spring-5 @@ -70,16 +69,20 @@ spring-data-commons ${spring-data-commons.version} + + com.github.kstyrc + embedded-redis + ${embedded-redis.version} + - UTF-8 - 5.0.3.RELEASE 2.0.3.RELEASE 3.2.4 2.9.0 0.10.0 2.0.3.RELEASE + 0.6 diff --git a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java index 4ea8bb4bc0..62a7886f46 100644 --- a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java +++ b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java @@ -1,8 +1,10 @@ package com.baeldung.spring.data.redis.config; +import org.springframework.beans.factory.annotation.Value; 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.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.listener.ChannelTopic; @@ -18,6 +20,7 @@ import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber; @Configuration @ComponentScan("com.baeldung.spring.data.redis") @EnableRedisRepositories(basePackages = "com.baeldung.spring.data.redis.repo") +@PropertySource("classpath:application.properties") public class RedisConfig { @Bean diff --git a/spring-session/src/main/resources/application.properties b/persistence-modules/spring-data-redis/src/main/resources/application.properties similarity index 100% rename from spring-session/src/main/resources/application.properties rename to persistence-modules/spring-data-redis/src/main/resources/application.properties diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java index 01dbfcff4d..5bc70069c5 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java @@ -1,24 +1,44 @@ package com.baeldung.spring.data.redis; -import com.baeldung.spring.data.redis.config.RedisConfig; -import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber; -import com.baeldung.spring.data.redis.queue.RedisMessagePublisher; -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 java.util.UUID; - import static org.junit.Assert.assertTrue; +import java.io.IOException; +import java.util.UUID; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.data.redis.config.RedisConfig; +import com.baeldung.spring.data.redis.queue.RedisMessagePublisher; +import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = RedisConfig.class) +@DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class RedisMessageListenerIntegrationTest { + private static redis.embedded.RedisServer redisServer; + @Autowired private RedisMessagePublisher redisMessagePublisher; + + @BeforeClass + public static void startRedisServer() throws IOException { + redisServer = new redis.embedded.RedisServer(6379); + redisServer.start(); + } + + @AfterClass + public static void stopRedisServer() throws IOException { + redisServer.stop(); + } @Test public void testOnMessage() throws Exception { diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java index 66ef3c21b2..48832a8de9 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java @@ -3,13 +3,17 @@ package com.baeldung.spring.data.redis.repo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import java.io.IOException; import java.util.ArrayList; import java.util.List; -import java.util.Map; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -18,10 +22,24 @@ import com.baeldung.spring.data.redis.model.Student; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = RedisConfig.class) +@DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class StudentRepositoryIntegrationTest { @Autowired private StudentRepository studentRepository; + + private static redis.embedded.RedisServer redisServer; + + @BeforeClass + public static void startRedisServer() throws IOException { + redisServer = new redis.embedded.RedisServer(6379); + redisServer.start(); + } + + @AfterClass + public static void stopRedisServer() throws IOException { + redisServer.stop(); + } @Test public void whenSavingStudent_thenAvailableOnRetrieval() throws Exception { diff --git a/persistence-modules/spring-data-solr/pom.xml b/persistence-modules/spring-data-solr/pom.xml index f1c20344c1..dcba80b49a 100644 --- a/persistence-modules/spring-data-solr/pom.xml +++ b/persistence-modules/spring-data-solr/pom.xml @@ -1,6 +1,5 @@ - + 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-data-solr @@ -10,9 +9,9 @@ com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../../parent-spring + parent-spring-4 + 0.0.1-SNAPSHOT + ../../parent-spring-4 @@ -46,8 +45,6 @@ - UTF-8 - 4.3.4.RELEASE 2.0.5.RELEASE diff --git a/persistence-modules/spring-data-solr/src/main/resources/logback.xml b/persistence-modules/spring-data-solr/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/spring-data-solr/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java b/persistence-modules/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java deleted file mode 100644 index a3765a74ec..0000000000 --- a/persistence-modules/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.baeldung.spring.data.solr.repo; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.baeldung.spring.data.solr.config.SolrConfig; -import com.baeldung.spring.data.solr.model.Product; -import com.baeldung.spring.data.solr.repository.ProductRepository; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = SolrConfig.class) -public class ProductRepositoryIntegrationTest { - - @Autowired - private ProductRepository productRepository; - - @Before - public void clearSolrData() { - productRepository.deleteAll(); - } - - @Test - public void whenSavingProduct_thenAvailableOnRetrieval() throws Exception { - final Product product = new Product(); - product.setId("P000089998"); - product.setName("Desk"); - productRepository.save(product); - final Product retrievedProduct = productRepository.findOne(product.getId()); - assertEquals(product.getId(), retrievedProduct.getId()); - } - - @Test - public void whenUpdatingProduct_thenChangeAvailableOnRetrieval() throws Exception { - final Product product = new Product(); - product.setId("P0001"); - product.setName("T-Shirt"); - - productRepository.save(product); - - product.setName("Shirt"); - productRepository.save(product); - - final Product retrievedProduct = productRepository.findOne(product.getId()); - assertEquals(product.getName(), retrievedProduct.getName()); - } - - @Test - public void whenDeletingProduct_thenNotAvailableOnRetrieval() throws Exception { - final Product product = new Product(); - product.setId("P0001"); - product.setName("Desk"); - productRepository.save(product); - - productRepository.delete(product); - - Product retrievedProduct = productRepository.findOne(product.getId()); - assertNull(retrievedProduct); - - } - - @Test - public void whenFindByName_thenAvailableOnRetrieval() throws Exception { - Product phone = new Product(); - phone.setId("P0001"); - phone.setName("Phone"); - productRepository.save(phone); - - List retrievedProducts = productRepository.findByName("Phone"); - assertEquals(phone.getId(), retrievedProducts.get(0).getId()); - } - - @Test - public void whenSearchingProductsByQuery_thenAllMatchingProductsShouldAvialble() throws Exception { - final Product phone = new Product(); - phone.setId("P0001"); - phone.setName("Smart Phone"); - productRepository.save(phone); - - final Product phoneCover = new Product(); - phoneCover.setId("P0002"); - phoneCover.setName("Phone Cover"); - productRepository.save(phoneCover); - - final Product wirelessCharger = new Product(); - wirelessCharger.setId("P0003"); - wirelessCharger.setName("Phone Charging Cable"); - productRepository.save(wirelessCharger); - - Page result = productRepository.findByCustomQuery("Phone", new PageRequest(0, 10)); - assertEquals(3, result.getNumberOfElements()); - } - - @Test - public void whenSearchingProductsByNamedQuery_thenAllMatchingProductsShouldAvialble() throws Exception { - final Product phone = new Product(); - phone.setId("P0001"); - phone.setName("Smart Phone"); - productRepository.save(phone); - - final Product phoneCover = new Product(); - phoneCover.setId("P0002"); - phoneCover.setName("Phone Cover"); - productRepository.save(phoneCover); - - final Product wirelessCharger = new Product(); - wirelessCharger.setId("P0003"); - wirelessCharger.setName("Phone Charging Cable"); - productRepository.save(wirelessCharger); - - Page result = productRepository.findByNamedQuery("one", new PageRequest(0, 10)); - assertEquals(3, result.getNumberOfElements()); - } - -} diff --git a/persistence-modules/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryLiveTest.java b/persistence-modules/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryLiveTest.java new file mode 100644 index 0000000000..f86adcdc8a --- /dev/null +++ b/persistence-modules/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryLiveTest.java @@ -0,0 +1,125 @@ +package com.baeldung.spring.data.solr.repo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.data.solr.config.SolrConfig; +import com.baeldung.spring.data.solr.model.Product; +import com.baeldung.spring.data.solr.repository.ProductRepository; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = SolrConfig.class) +public class ProductRepositoryLiveTest { + + @Autowired + private ProductRepository productRepository; + + @Before + public void clearSolrData() { + productRepository.deleteAll(); + } + + @Test + public void whenSavingProduct_thenAvailableOnRetrieval() throws Exception { + final Product product = new Product(); + product.setId("P000089998"); + product.setName("Desk"); + productRepository.save(product); + final Product retrievedProduct = productRepository.findOne(product.getId()); + assertEquals(product.getId(), retrievedProduct.getId()); + } + + @Test + public void whenUpdatingProduct_thenChangeAvailableOnRetrieval() throws Exception { + final Product product = new Product(); + product.setId("P0001"); + product.setName("T-Shirt"); + + productRepository.save(product); + + product.setName("Shirt"); + productRepository.save(product); + + final Product retrievedProduct = productRepository.findOne(product.getId()); + assertEquals(product.getName(), retrievedProduct.getName()); + } + + @Test + public void whenDeletingProduct_thenNotAvailableOnRetrieval() throws Exception { + final Product product = new Product(); + product.setId("P0001"); + product.setName("Desk"); + productRepository.save(product); + + productRepository.delete(product); + + Product retrievedProduct = productRepository.findOne(product.getId()); + assertNull(retrievedProduct); + + } + + @Test + public void whenFindByName_thenAvailableOnRetrieval() throws Exception { + Product phone = new Product(); + phone.setId("P0001"); + phone.setName("Phone"); + productRepository.save(phone); + + List retrievedProducts = productRepository.findByName("Phone"); + assertEquals(phone.getId(), retrievedProducts.get(0).getId()); + } + + @Test + public void whenSearchingProductsByQuery_thenAllMatchingProductsShouldAvialble() throws Exception { + final Product phone = new Product(); + phone.setId("P0001"); + phone.setName("Smart Phone"); + productRepository.save(phone); + + final Product phoneCover = new Product(); + phoneCover.setId("P0002"); + phoneCover.setName("Phone Cover"); + productRepository.save(phoneCover); + + final Product wirelessCharger = new Product(); + wirelessCharger.setId("P0003"); + wirelessCharger.setName("Phone Charging Cable"); + productRepository.save(wirelessCharger); + + Page result = productRepository.findByCustomQuery("Phone", new PageRequest(0, 10)); + assertEquals(3, result.getNumberOfElements()); + } + + @Test + public void whenSearchingProductsByNamedQuery_thenAllMatchingProductsShouldAvialble() throws Exception { + final Product phone = new Product(); + phone.setId("P0001"); + phone.setName("Smart Phone"); + productRepository.save(phone); + + final Product phoneCover = new Product(); + phoneCover.setId("P0002"); + phoneCover.setName("Phone Cover"); + productRepository.save(phoneCover); + + final Product wirelessCharger = new Product(); + wirelessCharger.setId("P0003"); + wirelessCharger.setName("Phone Charging Cable"); + productRepository.save(wirelessCharger); + + Page result = productRepository.findByNamedQuery("one", new PageRequest(0, 10)); + assertEquals(3, result.getNumberOfElements()); + } + +} diff --git a/persistence-modules/spring-hibernate-3/pom.xml b/persistence-modules/spring-hibernate-3/pom.xml index 3233dd11fe..6c1bdace30 100644 --- a/persistence-modules/spring-hibernate-3/pom.xml +++ b/persistence-modules/spring-hibernate-3/pom.xml @@ -1,5 +1,5 @@ + 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-hibernate-3 @@ -86,24 +86,15 @@ 4.3.4.RELEASE - 4.2.0.RELEASE 3.21.0-GA 3.6.10.Final 5.1.40 8.5.8 1.4.193 - - 5.3.3.Final 19.0 3.5 - 4.4.5 - 4.5.2 - 2.9.0 - - 2.7 - 1.6.1 diff --git a/persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemoPersistenceConfig.xml b/persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemoPersistenceConfig.xml index 09314c67b1..263e902e7c 100644 --- a/persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemoPersistenceConfig.xml +++ b/persistence-modules/spring-hibernate-3/src/main/resources/exceptionDemoPersistenceConfig.xml @@ -17,7 +17,7 @@ - + diff --git a/persistence-modules/spring-hibernate-3/src/main/resources/persistenceConfig.xml b/persistence-modules/spring-hibernate-3/src/main/resources/persistenceConfig.xml index e7ef9ad765..f39817383b 100644 --- a/persistence-modules/spring-hibernate-3/src/main/resources/persistenceConfig.xml +++ b/persistence-modules/spring-hibernate-3/src/main/resources/persistenceConfig.xml @@ -5,7 +5,7 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd" > - + diff --git a/persistence-modules/spring-hibernate-5/README.md b/persistence-modules/spring-hibernate-5/README.md index d48723ac31..b4d73708c3 100644 --- a/persistence-modules/spring-hibernate-5/README.md +++ b/persistence-modules/spring-hibernate-5/README.md @@ -3,3 +3,4 @@ - [Guide to @Immutable Annotation in Hibernate](http://www.baeldung.com/hibernate-immutable) - [Hibernate Many to Many Annotation Tutorial](http://www.baeldung.com/hibernate-many-to-many) - [Programmatic Transactions in the Spring TestContext Framework](http://www.baeldung.com/spring-test-programmatic-transactions) +- [Hibernate Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries) diff --git a/persistence-modules/spring-hibernate-5/pom.xml b/persistence-modules/spring-hibernate-5/pom.xml index de66d9e6f7..832cf8dca7 100644 --- a/persistence-modules/spring-hibernate-5/pom.xml +++ b/persistence-modules/spring-hibernate-5/pom.xml @@ -93,12 +93,6 @@ ${org.springframework.version} test - - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - org.springframework.security spring-security-test @@ -106,20 +100,6 @@ test - - junit - junit-dep - 4.11 - test - - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - - org.hsqldb hsqldb @@ -155,7 +135,6 @@ 5.0.2.RELEASE 1.10.6.RELEASE 4.2.1.RELEASE - 1.10.6.RELEASE 5.2.10.Final @@ -166,31 +145,10 @@ 2.3.4 1.4.195 - - 1.7.21 - 1.1.7 - - - 5.4.0.Final - 2.2.5 - 21.0 3.5 - - 1.3 - 4.12 - 4.4.1 - 4.5 - 2.9.0 - - - 3.7.0 - 2.19.1 - 2.7 - 1.6.1 - diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/model/Item.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/model/Item.java new file mode 100644 index 0000000000..957207b7e6 --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/model/Item.java @@ -0,0 +1,81 @@ +package com.baeldung.hibernate.criteria.model; + +import java.io.Serializable; + +public class Item implements Serializable { + + private static final long serialVersionUID = 1L; + private Integer itemId; + private String itemName; + private String itemDescription; + private Integer itemPrice; + + // constructors + public Item() { + + } + + public Item(final Integer itemId, final String itemName, final String itemDescription) { + super(); + this.itemId = itemId; + this.itemName = itemName; + this.itemDescription = itemDescription; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((itemId == null) ? 0 : itemId.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Item other = (Item) obj; + if (itemId == null) { + if (other.itemId != null) + return false; + } else if (!itemId.equals(other.itemId)) + return false; + return true; + } + + public Integer getItemId() { + return itemId; + } + + public void setItemId(final Integer itemId) { + this.itemId = itemId; + } + + public String getItemName() { + return itemName; + } + + public void setItemName(final String itemName) { + this.itemName = itemName; + } + + public String getItemDescription() { + return itemDescription; + } + + public Integer getItemPrice() { + return itemPrice; + } + + public void setItemPrice(final Integer itemPrice) { + this.itemPrice = itemPrice; + } + + public void setItemDescription(final String itemDescription) { + this.itemDescription = itemDescription; + } +} diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java similarity index 100% rename from spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java new file mode 100644 index 0000000000..72d4dea377 --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java @@ -0,0 +1,335 @@ +/** + * ApplicationViewer is the class that starts the application + * First it creates the session object and then creates the + * criteria query. + * + * @author Pritam Banerjee + * @version 1.0 + * @since 07/20/2016 + */ + +package com.baeldung.hibernate.criteria.view; + +import java.util.List; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +import org.hibernate.Session; +import org.hibernate.query.Query; + +import com.baeldung.hibernate.criteria.model.Item; +import com.baeldung.hibernate.criteria.util.HibernateUtil; + +public class ApplicationView { + + // default Constructor + public ApplicationView() { + + } + + public boolean checkIfCriteriaTimeLower() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + + // calculate the time taken by criteria + final long startTimeCriteria = System.nanoTime(); + cr.select(root) + .where(cb.like(root.get("itemName"), "%item One%")); + // .add(Restrictions.like("itemName", "%item One%")); + Query query = session.createQuery(cr); + + final List results = query.getResultList(); + final long endTimeCriteria = System.nanoTime(); + final long durationCriteria = (endTimeCriteria - startTimeCriteria) / 1000; + + // calculate the time taken by HQL + final long startTimeHQL = System.nanoTime(); + session.beginTransaction(); + final List items = session.createQuery("FROM Item where itemName like '%item One%'") + .list(); + final long endTimeHQL = System.nanoTime(); + final long durationHQL = (endTimeHQL - startTimeHQL) / 1000; + + if (durationCriteria > durationHQL) { + return false; + } else { + return true; + } + } + + // To get items having price more than 1000 + public String[] greaterThanCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + cr.select(root) + .where(cb.gt(root.get("itemPrice"), 1000)); + // cr.add(Restrictions.gt("itemPrice", 1000)); + Query query = session.createQuery(cr); + final List greaterThanItemsList = query.getResultList(); + final String greaterThanItems[] = new String[greaterThanItemsList.size()]; + for (int i = 0; i < greaterThanItemsList.size(); i++) { + greaterThanItems[i] = greaterThanItemsList.get(i) + .getItemName(); + } + session.close(); + return greaterThanItems; + } + + // To get items having price less than 1000 + public String[] lessThanCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + cr.select(root) + .where(cb.lt(root.get("itemPrice"), 1000)); + // cr.add(Restrictions.lt("itemPrice", 1000)); + Query query = session.createQuery(cr); + final List lessThanItemsList = query.getResultList(); + final String lessThanItems[] = new String[lessThanItemsList.size()]; + for (int i = 0; i < lessThanItemsList.size(); i++) { + lessThanItems[i] = lessThanItemsList.get(i) + .getItemName(); + } + session.close(); + return lessThanItems; + } + + // To get items whose Name start with Chair + public String[] likeCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + cr.select(root) + .where(cb.like(root.get("itemName"), "%chair%")); + // cr.add(Restrictions.like("itemName", "%chair%")); + Query query = session.createQuery(cr); + final List likeItemsList = query.getResultList(); + final String likeItems[] = new String[likeItemsList.size()]; + for (int i = 0; i < likeItemsList.size(); i++) { + likeItems[i] = likeItemsList.get(i) + .getItemName(); + } + session.close(); + return likeItems; + } + + // Case sensitive search + public String[] likeCaseCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + cr.select(root) + .where(cb.like(cb.lower(root.get("itemName")), "%chair%")); + // cr.add(Restrictions.ilike("itemName", "%Chair%")); + Query query = session.createQuery(cr); + final List ilikeItemsList = query.getResultList(); + final String ilikeItems[] = new String[ilikeItemsList.size()]; + for (int i = 0; i < ilikeItemsList.size(); i++) { + ilikeItems[i] = ilikeItemsList.get(i) + .getItemName(); + } + session.close(); + return ilikeItems; + } + + // To get records having itemPrice in between 100 and 200 + public String[] betweenCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + cr.select(root) + .where(cb.between(root.get("itemPrice"), 100, 200)); + // cr.add(Restrictions.between("itemPrice", 100, 200)); + Query query = session.createQuery(cr); + final List betweenItemsList = query.getResultList(); + final String betweenItems[] = new String[betweenItemsList.size()]; + for (int i = 0; i < betweenItemsList.size(); i++) { + betweenItems[i] = betweenItemsList.get(i) + .getItemName(); + } + session.close(); + return betweenItems; + } + + // To check if the given property is null + public String[] nullCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + cr.select(root) + .where(cb.isNull(root.get("itemDescription"))); + // cr.add(Restrictions.isNull("itemDescription")); + Query query = session.createQuery(cr); + final List nullItemsList = query.getResultList(); + final String nullDescItems[] = new String[nullItemsList.size()]; + for (int i = 0; i < nullItemsList.size(); i++) { + nullDescItems[i] = nullItemsList.get(i) + .getItemName(); + } + session.close(); + return nullDescItems; + } + + // To check if the given property is not null + public String[] notNullCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + cr.select(root) + .where(cb.isNotNull(root.get("itemDescription"))); + // cr.add(Restrictions.isNotNull("itemDescription")); + Query query = session.createQuery(cr); + final List notNullItemsList = query.getResultList(); + final String notNullDescItems[] = new String[notNullItemsList.size()]; + for (int i = 0; i < notNullItemsList.size(); i++) { + notNullDescItems[i] = notNullItemsList.get(i) + .getItemName(); + } + session.close(); + return notNullDescItems; + } + + // Adding more than one expression in one cr + public String[] twoCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + Predicate[] predicates = new Predicate[2]; + predicates[0] = cb.isNull(root.get("itemDescription")); + predicates[1] = cb.like(root.get("itemName"), "chair%"); + cr.select(root) + .where(predicates); + // cr.add(Restrictions.isNull("itemDescription")); + // cr.add(Restrictions.like("itemName", "chair%")); + Query query = session.createQuery(cr); + final List notNullItemsList = query.getResultList(); + final String notNullDescItems[] = new String[notNullItemsList.size()]; + for (int i = 0; i < notNullItemsList.size(); i++) { + notNullDescItems[i] = notNullItemsList.get(i) + .getItemName(); + } + session.close(); + return notNullDescItems; + } + + // To get items matching with the above defined conditions joined + // with Logical AND + public String[] andLogicalCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + Predicate greaterThanPrice = cb.gt(root.get("itemPrice"), 1000); + Predicate chairItems = cb.like(root.get("itemName"), "Chair%"); + cr.select(root) + .where(cb.and(greaterThanPrice, chairItems)); + // final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); + // final Criterion chairItems = Restrictions.like("itemName", "Chair%"); + // final LogicalExpression andExample = Restrictions.and(greaterThanPrice, chairItems); + // cr.add(andExample); + Query query = session.createQuery(cr); + final List andItemsList = query.getResultList(); + final String andItems[] = new String[andItemsList.size()]; + for (int i = 0; i < andItemsList.size(); i++) { + andItems[i] = andItemsList.get(i) + .getItemName(); + } + session.close(); + return andItems; + } + + // To get items matching with the above defined conditions joined + // with Logical OR + public String[] orLogicalCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + Predicate greaterThanPrice = cb.gt(root.get("itemPrice"), 1000); + Predicate chairItems = cb.like(root.get("itemName"), "Chair%"); + cr.select(root) + .where(cb.or(greaterThanPrice, chairItems)); + Query query = session.createQuery(cr); + final List orItemsList = query.getResultList(); + final String orItems[] = new String[orItemsList.size()]; + for (int i = 0; i < orItemsList.size(); i++) { + orItems[i] = orItemsList.get(i) + .getItemName(); + } + session.close(); + return orItems; + } + + // Sorting example + public String[] sortingCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + cr.select(root); + cr.orderBy(cb.asc(root.get("itemName")), cb.desc(root.get("itemPrice"))); + // cr.addOrder(Order.asc("itemName")); + // cr.addOrder(Order.desc("itemPrice")).list(); + Query query = session.createQuery(cr); + final List sortedItemsList = query.getResultList(); + final String sortedItems[] = new String[sortedItemsList.size()]; + for (int i = 0; i < sortedItemsList.size(); i++) { + sortedItems[i] = sortedItemsList.get(i) + .getItemName(); + } + session.close(); + return sortedItems; + } + + // Set projections Row Count + public Long[] projectionRowCount() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Long.class); + final Root root = cr.from(Item.class); + cr.select(cb.count(root)); + Query query = session.createQuery(cr); + final List itemProjected = query.getResultList(); + // session.createCriteria(Item.class).setProjection(Projections.rowCount()).list(); + final Long projectedRowCount[] = new Long[itemProjected.size()]; + for (int i = 0; i < itemProjected.size(); i++) { + projectedRowCount[i] = itemProjected.get(i); + } + session.close(); + return projectedRowCount; + } + + // Set projections average of itemPrice + public Double[] projectionAverage() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Double.class); + final Root root = cr.from(Item.class); + cr.select(cb.avg(root.get("itemPrice"))); + Query query = session.createQuery(cr); + final List avgItemPriceList = query.getResultList(); + // session.createCriteria(Item.class).setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list(); + + final Double avgItemPrice[] = new Double[avgItemPriceList.size()]; + for (int i = 0; i < avgItemPriceList.size(); i++) { + avgItemPrice[i] = (Double) avgItemPriceList.get(i); + } + session.close(); + return avgItemPrice; + } + +} diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java index f1ad30b090..8157945e2c 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java @@ -3,13 +3,15 @@ package com.baeldung.hibernate.manytomany.model; import java.io.Serializable; import java.util.HashSet; import java.util.Set; + import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; -import javax.persistence.JoinTable; import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; @@ -18,7 +20,7 @@ import javax.persistence.Table; public class Employee implements Serializable { @Id @Column(name = "employee_id") - @GeneratedValue + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long employeeId; @Column(name = "first_name") diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernatesearch/HibernateSearchConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernatesearch/HibernateSearchConfig.java index 6bbd2625fc..d6445c3cb0 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernatesearch/HibernateSearchConfig.java +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernatesearch/HibernateSearchConfig.java @@ -50,6 +50,8 @@ public class HibernateSearchConfig { final BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(env.getProperty("jdbc.user")); + dataSource.setPassword(env.getProperty("jdbc.pass")); return dataSource; } diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java index 5dace1f742..44cbfadb25 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java @@ -19,7 +19,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement -@PropertySource({ "classpath:persistence-mysql.properties" }) +@PropertySource({ "classpath:persistence-h2.properties" }) @ComponentScan({ "com.baeldung.hibernate.manytomany" }) public class PersistenceConfig { @@ -61,7 +61,7 @@ public class PersistenceConfig { private final Properties hibernateProperties() { final Properties hibernateProperties = new Properties(); - //hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); hibernateProperties.setProperty("hibernate.show_sql", "true"); diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java index e64f0a4efe..74ac0a269e 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java @@ -21,7 +21,7 @@ import java.util.Properties; @Configuration @EnableTransactionManagement -@PropertySource({ "classpath:persistence-mysql.properties" }) +@PropertySource({ "classpath:persistence-h2.properties" }) @ComponentScan({ "com.baeldung.persistence" }) public class PersistenceConfig { diff --git a/persistence-modules/spring-hibernate-5/src/main/resources/import.sql b/persistence-modules/spring-hibernate-5/src/main/resources/import.sql new file mode 100644 index 0000000000..ae008f29bc --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/main/resources/import.sql @@ -0,0 +1,31 @@ +insert into item (item_id, item_name, item_desc, item_price) +values(1,'item One', 'test 1', 35.12); + +insert into item (item_id, item_name, item_desc, item_price) +values(2,'Pogo stick', 'Pogo stick', 466.12); +insert into item (item_id, item_name, item_desc, item_price) +values(3,'Raft', 'Raft', 345.12); + +insert into item (item_id, item_name, item_desc, item_price) +values(4,'Skate Board', 'Skating', 135.71); + +insert into item (item_id, item_name, item_desc, item_price) +values(5,'Umbrella', 'Umbrella for Rain', 619.25); + +insert into item (item_id, item_name, item_desc, item_price) +values(6,'Glue', 'Glue for home', 432.73); + +insert into item (item_id, item_name, item_desc, item_price) +values(7,'Paint', 'Paint for Room', 1311.40); + +insert into item (item_id, item_name, item_desc, item_price) +values(8,'Red paint', 'Red paint for room', 1135.71); + +insert into item (item_id, item_name, item_desc, item_price) +values(9,'Household Chairs', 'Chairs for house', 25.71); + +insert into item (item_id, item_name, item_desc, item_price) +values(10,'Office Chairs', 'Chairs for office', 395.98); + +insert into item (item_id, item_name, item_desc, item_price) +values(11,'Outdoor Chairs', 'Chairs for outdoor activities', 1234.36); diff --git a/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties b/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties index 0325174b67..5a137e2310 100644 --- a/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties +++ b/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties @@ -3,7 +3,7 @@ jdbc.driverClassName=org.h2.Driver jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 jdbc.eventGeneratedId=sa jdbc.user=sa -jdbc.pass=sa +jdbc.pass= # hibernate.X hibernate.dialect=org.hibernate.dialect.H2Dialect diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java similarity index 99% rename from spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java index 2275bf14f2..723b097305 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java @@ -43,7 +43,6 @@ public class HibernateCriteriaIntegrationTest { } session.close(); assertArrayEquals(expectedChairCaseItems, av.likeCaseCriteria()); - } @Test diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java similarity index 100% rename from spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java similarity index 100% rename from spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java diff --git a/spring-hibernate4/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml b/persistence-modules/spring-hibernate-5/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml similarity index 100% rename from spring-hibernate4/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml rename to persistence-modules/spring-hibernate-5/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml diff --git a/persistence-modules/spring-hibernate-5/src/test/resources/criteria.cfg.xml b/persistence-modules/spring-hibernate-5/src/test/resources/criteria.cfg.xml new file mode 100644 index 0000000000..bc4fed9680 --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/test/resources/criteria.cfg.xml @@ -0,0 +1,17 @@ + + + + + + org.h2.Driver + jdbc:h2:mem:testdb + sa + + org.hibernate.dialect.H2Dialect + create-drop + false + + + \ No newline at end of file diff --git a/persistence-modules/spring-hibernate-5/src/test/resources/import.sql b/persistence-modules/spring-hibernate-5/src/test/resources/import.sql new file mode 100644 index 0000000000..087d62d331 --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/test/resources/import.sql @@ -0,0 +1,21 @@ +insert into item (item_id, item_name, item_desc, item_price) values(1,'item One', 'test 1', 35.12); + +insert into item (item_id, item_name, item_desc, item_price) values(2,'Pogo stick', 'Pogo stick', 466.12); + +insert into item (item_id, item_name, item_desc, item_price) values(3,'Raft', 'Raft', 345.12); + +insert into item (item_id, item_name, item_desc, item_price) values(4,'Skate Board', 'Skating', 135.71); + +insert into item (item_id, item_name, item_desc, item_price) values(5,'Umbrella', 'Umbrella for Rain', 619.25); + +insert into item (item_id, item_name, item_desc, item_price) values(6,'Glue', 'Glue for home', 432.73); + +insert into item (item_id, item_name, item_desc, item_price) values(7,'Paint', 'Paint for Room', 1311.40); + +insert into item (item_id, item_name, item_desc, item_price) values(8,'Red paint', 'Red paint for room', 1135.71); + +insert into item (item_id, item_name, item_desc, item_price) values(9,'Household Chairs', 'Chairs for house', 25.71); + +insert into item (item_id, item_name, item_desc, item_price) values(10,'Office Chairs', 'Chairs for office', 395.98); + +insert into item (item_id, item_name, item_desc, item_price) values(11,'Outdoor Chairs', 'Chairs for outdoor activities', 1234.36); diff --git a/persistence-modules/spring-hibernate-5/src/test/resources/manytomany.cfg.xml b/persistence-modules/spring-hibernate-5/src/test/resources/manytomany.cfg.xml new file mode 100644 index 0000000000..a7a23ec70d --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/test/resources/manytomany.cfg.xml @@ -0,0 +1,16 @@ + + + + + org.h2.Driver + + jdbc:h2:mem:spring_hibernate_many_to_many + sa + org.hibernate.dialect.H2Dialect + thread + true + create-drop + + diff --git a/persistence-modules/spring-jpa/README.md b/persistence-modules/spring-jpa/README.md index cb71d386e2..299a5a1e51 100644 --- a/persistence-modules/spring-jpa/README.md +++ b/persistence-modules/spring-jpa/README.md @@ -9,19 +9,16 @@ - [The DAO with JPA and Spring](http://www.baeldung.com/spring-dao-jpa) - [JPA Pagination](http://www.baeldung.com/jpa-pagination) - [Sorting with JPA](http://www.baeldung.com/jpa-sort) -- [Spring JPA – Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases) - [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache) - [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource) - [Deleting Objects with Hibernate](http://www.baeldung.com/delete-with-hibernate) - [Self-Contained Testing Using an In-Memory Database](http://www.baeldung.com/spring-jpa-test-in-memory-database) -- [Spring Data JPA – Adding a Method in All Repositories](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories) - [A Guide to Spring AbstractRoutingDatasource](http://www.baeldung.com/spring-abstract-routing-data-source) -- [Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced) - [A Guide to Hibernate with Spring 4](http://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) - [Testing REST with multiple MIME types](http://www.baeldung.com/testing-rest-api-with-multiple-media-types) - [Obtaining Auto-generated Keys in Spring JDBC](http://www.baeldung.com/spring-jdbc-autogenerated-keys) - [Transactions with Spring 4 and JPA](http://www.baeldung.com/transaction-configuration-with-jpa-and-spring) -- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) +- [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/persistence-modules/spring-jpa/pom.xml b/persistence-modules/spring-jpa/pom.xml index 065b29b26b..400811b582 100644 --- a/persistence-modules/spring-jpa/pom.xml +++ b/persistence-modules/spring-jpa/pom.xml @@ -1,7 +1,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-jpa 0.1-SNAPSHOT war @@ -179,13 +178,8 @@ 21.0 3.5 3.8.0 - 4.4.5 - 4.5.2 - 2.9.0 - 2.7 - 1.6.1 2.6 diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/MyUtilityRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/MyUtilityRepository.java new file mode 100644 index 0000000000..5fe54b80d9 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/MyUtilityRepository.java @@ -0,0 +1,14 @@ +package org.baeldung.annotations; + +import java.io.Serializable; +import java.util.Optional; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.NoRepositoryBean; + +@NoRepositoryBean +public interface MyUtilityRepository extends CrudRepository { + + Optional findById(ID id); + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/Person.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/Person.java new file mode 100644 index 0000000000..309a4f43e1 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/Person.java @@ -0,0 +1,54 @@ +package org.baeldung.annotations; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.NamedStoredProcedureQueries; +import javax.persistence.NamedStoredProcedureQuery; +import javax.persistence.ParameterMode; +import javax.persistence.StoredProcedureParameter; + +import org.baeldung.persistence.multiple.model.user.User; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.Transient; + +@Entity +@NamedStoredProcedureQueries({ + @NamedStoredProcedureQuery( + name = "count_by_name", + procedureName = "person.count_by_name", + parameters = { + @StoredProcedureParameter( + mode = ParameterMode.IN, + name = "name", + type = String.class), + @StoredProcedureParameter( + mode = ParameterMode.OUT, + name = "count", + type = Long.class) + }) +}) +public class Person { + + @Id + private Long id; + + @Transient + private int age; + + @CreatedBy + private User creator; + + @LastModifiedBy + private User modifier; + + @CreatedDate + private Date createdAt; + + @LastModifiedBy + private Date modifiedAt; + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/PersonRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/PersonRepository.java new file mode 100644 index 0000000000..58558860ff --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/PersonRepository.java @@ -0,0 +1,32 @@ +package org.baeldung.annotations; + +import javax.persistence.LockModeType; + +import org.springframework.data.jpa.repository.Lock; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.jpa.repository.query.Procedure; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +@Repository +public interface PersonRepository extends MyUtilityRepository { + + @Lock(LockModeType.NONE) + @Query("SELECT COUNT(*) FROM Person p") + long getPersonCount(); + + @Query("FROM Person p WHERE p.name = :name") + Person findByName(@Param("name") String name); + + @Query(value = "SELECT AVG(p.age) FROM person p", nativeQuery = true) + int getAverageAge(); + + @Procedure(name = "count_by_name") + long getCountByName(@Param("name") String name); + + @Modifying + @Query("UPDATE Person p SET p.name = :name WHERE p.id = :id") + void changeName(@Param("id") long id, @Param("name") String name); + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java index 010eb5b8a1..78c4116c67 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java @@ -24,7 +24,7 @@ import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement -@PropertySource({ "classpath:persistence-mysql.properties" }) +@PropertySource({ "classpath:persistence-h2.properties" }) @ComponentScan({ "org.baeldung.persistence" }) @EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao") public class PersistenceJPAConfig { diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/ProductConfig.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/ProductConfig.java deleted file mode 100644 index 13f8f4b27c..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/ProductConfig.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.baeldung.config; - -import java.util.HashMap; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; - -import com.google.common.base.Preconditions; - -@Configuration -@PropertySource({ "classpath:persistence-multiple-db.properties" }) -@EnableJpaRepositories(basePackages = "org.baeldung.persistence.multiple.dao.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager") -public class ProductConfig { - @Autowired - private Environment env; - - public ProductConfig() { - super(); - } - - // - - @Bean - public LocalContainerEntityManagerFactoryBean productEntityManager() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(productDataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.persistence.multiple.model.product" }); - - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - em.setJpaVendorAdapter(vendorAdapter); - final HashMap properties = new HashMap(); - properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); - em.setJpaPropertyMap(properties); - - return em; - } - - @Bean - public DataSource productDataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); - dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("product.jdbc.url"))); - dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); - dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); - - return dataSource; - } - - @Bean - public PlatformTransactionManager productTransactionManager() { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(productEntityManager().getObject()); - return transactionManager; - } - -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJPAH2Config.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJPAH2Config.java deleted file mode 100644 index 439c6cb602..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJPAH2Config.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.baeldung.config; - -import java.util.Properties; - -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; - -import org.baeldung.extended.persistence.dao.ExtendedRepositoryImpl; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -@Configuration -@EnableJpaRepositories(basePackages = "org.baeldung.extended.persistence.dao", repositoryBaseClass = ExtendedRepositoryImpl.class) -@PropertySource("persistence-student-h2.properties") -@EnableTransactionManagement -public class StudentJPAH2Config { - - @Autowired - private Environment env; - - @Bean - public DataSource dataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); - dataSource.setUrl(env.getProperty("jdbc.url")); - dataSource.setUsername(env.getProperty("jdbc.user")); - dataSource.setPassword(env.getProperty("jdbc.pass")); - - return dataSource; - } - - @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.inmemory.persistence.model" }); - em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); - em.setJpaProperties(additionalProperties()); - return em; - } - - @Bean - JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { - JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(entityManagerFactory); - return transactionManager; - } - - final Properties additionalProperties() { - final Properties hibernateProperties = new Properties(); - - hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); - hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); - hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); - - return hibernateProperties; - } -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/UserConfig.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/UserConfig.java deleted file mode 100644 index 8e85f5d8e0..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/UserConfig.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.baeldung.config; - -import java.util.HashMap; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; - -import com.google.common.base.Preconditions; - -@Configuration -@PropertySource({ "classpath:persistence-multiple-db.properties" }) -@EnableJpaRepositories(basePackages = "org.baeldung.persistence.multiple.dao.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager") -public class UserConfig { - @Autowired - private Environment env; - - public UserConfig() { - super(); - } - - // - - @Primary - @Bean - public LocalContainerEntityManagerFactoryBean userEntityManager() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(userDataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.persistence.multiple.model.user" }); - - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - em.setJpaVendorAdapter(vendorAdapter); - final HashMap properties = new HashMap(); - properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); - em.setJpaPropertyMap(properties); - - return em; - } - - @Primary - @Bean - public DataSource userDataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); - dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("user.jdbc.url"))); - dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); - dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); - - return dataSource; - } - - @Primary - @Bean - public PlatformTransactionManager userTransactionManager() { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(userEntityManager().getObject()); - return transactionManager; - } - -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepository.java deleted file mode 100644 index 9c9c12029a..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung.extended.persistence.dao; - -import java.io.Serializable; -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.repository.NoRepositoryBean; - -@NoRepositoryBean -public interface ExtendedRepository extends JpaRepository { - public List findByAttributeContainsText(String attributeName, String text); -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedStudentRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedStudentRepository.java deleted file mode 100644 index 7e2efc72bc..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedStudentRepository.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.baeldung.extended.persistence.dao; - -import org.baeldung.inmemory.persistence.model.Student; - -public interface ExtendedStudentRepository extends ExtendedRepository { -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/dao/BookRepositoryImpl.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/dao/BookRepositoryImpl.java new file mode 100644 index 0000000000..f782d69e1e --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/dao/BookRepositoryImpl.java @@ -0,0 +1,46 @@ +package org.baeldung.persistence.criteria.dao; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +import org.baeldung.persistence.criteria.model.Book; +import org.baeldung.persistence.criteria.repository.BookRepositoryCustom; +import org.springframework.stereotype.Repository; + +@Repository +public class BookRepositoryImpl implements BookRepositoryCustom { + + private EntityManager em; + + public BookRepositoryImpl(EntityManager em) { + this.em = em; + } + + @Override + public List findBooksByAuthorNameAndTitle(String authorName, String title) { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(Book.class); + + Root book = cq.from(Book.class); + List predicates = new ArrayList<>(); + + if (authorName != null) { + predicates.add(cb.equal(book.get("author"), authorName)); + } + if (title != null) { + predicates.add(cb.like(book.get("title"), "%" + title + "%")); + } + cq.where(predicates.toArray(new Predicate[0])); + + TypedQuery query = em.createQuery(cq); + return query.getResultList(); + } + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/model/Book.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/model/Book.java new file mode 100644 index 0000000000..beb6c0190c --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/model/Book.java @@ -0,0 +1,36 @@ +package org.baeldung.persistence.criteria.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Book { + + @Id + private Long id; + + private String title; + + private String author; + + public Long getId() { + return id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookRepository.java new file mode 100644 index 0000000000..af30ae461e --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookRepository.java @@ -0,0 +1,9 @@ +package org.baeldung.persistence.criteria.repository; + +import org.baeldung.persistence.criteria.model.Book; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +public interface BookRepository extends JpaRepository, BookRepositoryCustom, JpaSpecificationExecutor { + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookRepositoryCustom.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookRepositoryCustom.java new file mode 100644 index 0000000000..35330cfa3c --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookRepositoryCustom.java @@ -0,0 +1,11 @@ +package org.baeldung.persistence.criteria.repository; + +import java.util.List; + +import org.baeldung.persistence.criteria.model.Book; + +public interface BookRepositoryCustom { + + List findBooksByAuthorNameAndTitle(String authorName, String title); + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookService.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookService.java new file mode 100644 index 0000000000..7b1aff857e --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookService.java @@ -0,0 +1,25 @@ +package org.baeldung.persistence.criteria.repository; + +import static org.baeldung.persistence.criteria.repository.BookSpecifications.hasAuthor; +import static org.baeldung.persistence.criteria.repository.BookSpecifications.titleContains; +import static org.springframework.data.jpa.domain.Specifications.where; + +import java.util.List; + +import org.baeldung.persistence.criteria.model.Book; +import org.springframework.stereotype.Service; + +@Service +public class BookService { + + private BookRepository bookRepository; + + public BookService(BookRepository bookRepository) { + this.bookRepository = bookRepository; + } + + public List query(String author, String title) { + return bookRepository.findAll(where(hasAuthor(author)).and(titleContains(title))); + } + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookSpecifications.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookSpecifications.java new file mode 100644 index 0000000000..392b750977 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/criteria/repository/BookSpecifications.java @@ -0,0 +1,16 @@ +package org.baeldung.persistence.criteria.repository; + +import org.baeldung.persistence.criteria.model.Book; +import org.springframework.data.jpa.domain.Specification; + +public class BookSpecifications { + + public static Specification hasAuthor(String author) { + return (book, cq, cb) -> cb.equal(book.get("author"), author); + } + + public static Specification titleContains(String title) { + return (book, cq, cb) -> cb.like(book.get("title"), "%" + title + "%"); + } + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/User.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/User.java deleted file mode 100644 index f84a10cf76..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/User.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.baeldung.persistence.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "users") -public class User { - - @Id - @GeneratedValue - private Integer id; - private String name; - private Integer status; - - public User() { - } - - public User(String name, Integer status) { - this.name = name; - this.status = status; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Integer getStatus() { - return status; - } - - public void setStatus(Integer status) { - this.status = status; - } -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/product/ProductRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/product/ProductRepository.java deleted file mode 100644 index bad0170a3a..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/product/ProductRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.persistence.multiple.dao.product; - -import org.baeldung.persistence.multiple.model.product.Product; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface ProductRepository extends JpaRepository { - -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java deleted file mode 100644 index 34913632d8..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.persistence.multiple.dao.user; - -import org.baeldung.persistence.multiple.model.user.Possession; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface PossessionRepository extends JpaRepository { - -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/UserRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/UserRepository.java deleted file mode 100644 index e250a291bc..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/UserRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.persistence.multiple.dao.user; - -import org.baeldung.persistence.multiple.model.user.User; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface UserRepository extends JpaRepository { - -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/product/Product.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/product/Product.java deleted file mode 100644 index 8490ed397d..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/product/Product.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.baeldung.persistence.multiple.model.product; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(schema = "spring_jpa_product") -public class Product { - - @Id - private int id; - - private String name; - - private double price; - - public Product() { - super(); - } - - public int getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public double getPrice() { - return price; - } - - public void setPrice(final double price) { - this.price = price; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Product [name=").append(name).append(", id=").append(id).append("]"); - return builder.toString(); - } -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java index 97b5803d73..7aff5f51d0 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java @@ -1,17 +1,13 @@ package org.baeldung.persistence.multiple.model.user; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +import javax.persistence.*; @Entity @Table(schema = "spring_jpa_user") public class Possession { @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String name; diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java index 1c6399dc44..6fb9de4a47 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java @@ -1,21 +1,14 @@ package org.baeldung.persistence.multiple.model.user; +import javax.persistence.*; import java.util.List; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.Table; - @Entity @Table(schema = "spring_jpa_user") public class User { @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/repository/UserRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/repository/UserRepository.java deleted file mode 100644 index eadac9a0d7..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/repository/UserRepository.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.baeldung.persistence.repository; - -import org.baeldung.persistence.model.User; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import java.util.Collection; -import java.util.List; - -@Repository("userRepository") -public interface UserRepository extends JpaRepository { - - @Query("SELECT u FROM User u WHERE u.status = 1") - Collection findAllActiveUsers(); - - @Query(value = "SELECT * FROM USERS u WHERE u.status = 1", nativeQuery = true) - Collection findAllActiveUsersNative(); - - @Query("SELECT u FROM User u WHERE u.status = ?1") - User findUserByStatus(Integer status); - - @Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true) - User findUserByStatusNative(Integer status); - - @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") - User findUserByStatusAndName(Integer status, String name); - - @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") - User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name); - - @Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) - User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name); - - @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") - User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName); - - @Query("SELECT u FROM User u WHERE u.name like ?1%") - User findUserByNameLike(String name); - - @Query("SELECT u FROM User u WHERE u.name like :name%") - User findUserByNameLikeNamedParam(@Param("name") String name); - - @Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true) - User findUserByNameLikeNative(String name); - - @Query(value = "SELECT u FROM User u") - List findAllUsers(Sort sort); - - @Query(value = "SELECT u FROM User u ORDER BY id") - Page findAllUsersWithPagination(Pageable pageable); - - @Query(value = "SELECT * FROM Users ORDER BY id \n-- #pageable\n", countQuery = "SELECT count(*) FROM Users", nativeQuery = true) - Page findAllUsersWithPaginationNative(Pageable pageable); - - @Modifying - @Query("update User u set u.status = :status where u.name = :name") - int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); - - @Modifying - @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) - int updateUserSetStatusForNameNative(Integer status, String name); - -} diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties b/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties index 2c3e18b58d..716a96fde3 100644 --- a/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties +++ b/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties @@ -2,7 +2,7 @@ jdbc.driverClassName=org.h2.Driver jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 jdbc.user=sa -# jdbc.pass= +jdbc.pass= # hibernate.X hibernate.dialect=org.hibernate.dialect.H2Dialect diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence-multiple-db.properties b/persistence-modules/spring-jpa/src/main/resources/persistence-multiple-db.properties deleted file mode 100644 index 539535528c..0000000000 --- a/persistence-modules/spring-jpa/src/main/resources/persistence-multiple-db.properties +++ /dev/null @@ -1,13 +0,0 @@ -# jdbc.X -jdbc.driverClassName=com.mysql.cj.jdbc.Driver -user.jdbc.url=jdbc:mysql://localhost:3306/spring_jpa_user?createDatabaseIfNotExist=true -product.jdbc.url=jdbc:mysql://localhost:3306/spring_jpa_product?createDatabaseIfNotExist=true -jdbc.user=tutorialuser -jdbc.pass=tutorialmy5ql - -# hibernate.X -hibernate.dialect=org.hibernate.dialect.MySQL5Dialect -hibernate.show_sql=false -hibernate.hbm2ddl.auto=create-drop -hibernate.cache.use_second_level_cache=false -hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence-student-h2.properties b/persistence-modules/spring-jpa/src/main/resources/persistence-student-h2.properties index e1d6bfa45a..405e6ff109 100644 --- a/persistence-modules/spring-jpa/src/main/resources/persistence-student-h2.properties +++ b/persistence-modules/spring-jpa/src/main/resources/persistence-student-h2.properties @@ -2,7 +2,7 @@ jdbc.driverClassName=org.h2.Driver jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 jdbc.user=sa -# jdbc.pass= +jdbc.pass= # hibernate.X hibernate.dialect=org.hibernate.dialect.H2Dialect diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence.xml b/persistence-modules/spring-jpa/src/main/resources/persistence.xml index 5afc0af94d..65bad29cdc 100644 --- a/persistence-modules/spring-jpa/src/main/resources/persistence.xml +++ b/persistence-modules/spring-jpa/src/main/resources/persistence.xml @@ -7,7 +7,7 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd" > - + diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingIntegrationTest.java index f81247e3cd..47355471b9 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingIntegrationTest.java @@ -9,11 +9,13 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @ContextConfiguration(classes = DataSourceRoutingTestConfiguration.class) +@DirtiesContext public class DataSourceRoutingIntegrationTest { @Autowired diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java index 09d118fedc..e5fb728a0a 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java @@ -10,6 +10,6 @@ public class PersistenceJPAConfigDeletion extends PersistenceJPAConfigL2Cache { @Override protected String[] getPackagesToScan() { - return new String[] { "org.baeldung.persistence.deletion.model" }; + return new String[] { "org.baeldung.persistence.deletion.model", "org.baeldung.persistence.model" }; } } \ No newline at end of file diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java index 9432420878..9a90b857e5 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java @@ -11,6 +11,7 @@ import org.baeldung.inmemory.persistence.model.SkillTag; import org.baeldung.inmemory.persistence.model.Student; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @@ -26,6 +27,7 @@ import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { StudentJpaConfig.class }, loader = AnnotationConfigContextLoader.class) @Transactional +@DirtiesContext public class AdvancedTaggingIntegrationTest { @Resource private StudentRepository studentRepository; diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java deleted file mode 100644 index 7c6ec9b6da..0000000000 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.baeldung.persistence.repository; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.List; - -import javax.annotation.Resource; - -import org.baeldung.config.StudentJPAH2Config; -import org.baeldung.extended.persistence.dao.ExtendedStudentRepository; -import org.baeldung.inmemory.persistence.model.Student; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { StudentJPAH2Config.class }) -public class ExtendedStudentRepositoryIntegrationTest { - @Resource - private ExtendedStudentRepository extendedStudentRepository; - - @Before - public void setup() { - Student student = new Student(1, "john"); - extendedStudentRepository.save(student); - Student student2 = new Student(2, "johnson"); - extendedStudentRepository.save(student2); - Student student3 = new Student(3, "tom"); - extendedStudentRepository.save(student3); - } - - @Test - public void givenStudents_whenFindByName_thenGetOk() { - List students = extendedStudentRepository.findByAttributeContainsText("name", "john"); - assertThat(students.size()).isEqualTo(2); - } -} diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java index 3d9e376e81..9ddc48460a 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java @@ -5,6 +5,7 @@ import org.baeldung.inmemory.persistence.dao.StudentRepository; import org.baeldung.inmemory.persistence.model.Student; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @@ -20,6 +21,7 @@ import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { StudentJpaConfig.class }, loader = AnnotationConfigContextLoader.class) @Transactional +@DirtiesContext public class InMemoryDBIntegrationTest { @Resource diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/UserRepositoryIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/UserRepositoryIntegrationTest.java deleted file mode 100644 index 90db9f4e74..0000000000 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/UserRepositoryIntegrationTest.java +++ /dev/null @@ -1,319 +0,0 @@ -package org.baeldung.persistence.repository; - -import org.baeldung.config.PersistenceJPAConfigL2Cache; -import org.baeldung.persistence.model.User; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Sort; -import org.springframework.data.jpa.domain.JpaSort; -import org.springframework.data.mapping.PropertyReferenceException; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; - -import java.util.Collection; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Created by adam. - */ -@RunWith(SpringRunner.class) -@ContextConfiguration(classes = PersistenceJPAConfigL2Cache.class) -public class UserRepositoryIntegrationTest { - - private final String USER_NAME_ADAM = "Adam"; - private final String USER_NAME_PETER = "Peter"; - private final Integer INACTIVE_STATUS = 0; - private final Integer ACTIVE_STATUS = 1; - - @Autowired - private UserRepository userRepository; - - @Test - public void givenUsersInDBWhenFindAllWithQueryAnnotationThenReturnCollectionWithActiveUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setStatus(ACTIVE_STATUS); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setStatus(INACTIVE_STATUS); - userRepository.save(user3); - - Collection allActiveUsers = userRepository.findAllActiveUsers(); - - assertThat(allActiveUsers.size()).isEqualTo(2); - } - - @Test - public void givenUsersInDBWhenFindAllWithQueryAnnotationNativeThenReturnCollectionWithActiveUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setStatus(ACTIVE_STATUS); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setStatus(INACTIVE_STATUS); - userRepository.save(user3); - - Collection allActiveUsers = userRepository.findAllActiveUsersNative(); - - assertThat(allActiveUsers.size()).isEqualTo(2); - } - - @Test - public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationThenReturnActiveUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationNativeThenReturnActiveUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationIndexedParamsThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParamsThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNamesThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationIndexedParamsThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLike("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNamedParamsThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNativeThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLikeNative("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindAllWithSortByNameThenReturnUsersSorted() { - userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); - - List usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); - - assertThat(usersSortByName - .get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test(expected = PropertyReferenceException.class) - public void givenUsersInDBWhenFindAllSortWithFunctionThenThrowException() { - userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); - - userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); - - List usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)")); - - assertThat(usersSortByNameLength - .get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindAllSortWithFunctionQueryAnnotationJPQLThenReturnUsersSorted() { - userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); - - userRepository.findAllUsers(new Sort("name")); - - List usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)")); - - assertThat(usersSortByNameLength - .get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationJPQLThenReturnPageOfUsers() { - userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE2", INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", INACTIVE_STATUS)); - - Page usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3)); - - assertThat(usersPage - .getContent() - .get(0) - .getName()).isEqualTo("SAMPLE1"); - } - - @Test - public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationNativeThenReturnPageOfUsers() { - userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE2", INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", INACTIVE_STATUS)); - - Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3)); - - assertThat(usersSortByNameLength - .getContent() - .get(0) - .getName()).isEqualTo("SAMPLE1"); - } - - @Test - @Transactional - public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationJPQLThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", ACTIVE_STATUS)); - - int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } - - @Test - @Transactional - public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", ACTIVE_STATUS)); - userRepository.flush(); - - int updatedUsersSize = userRepository.updateUserSetStatusForNameNative(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } - - @After - public void cleanUp() { - userRepository.deleteAll(); - } - -} diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java index f42a4e9be1..0dbb7dbfe8 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java @@ -8,6 +8,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @@ -23,6 +24,7 @@ import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceJPAConfigDeletion.class }, loader = AnnotationConfigContextLoader.class) +@DirtiesContext public class DeletionIntegrationTest { @PersistenceContext diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java index 091bec0ba0..bf49a431e1 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java @@ -16,17 +16,20 @@ import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.baeldung.config.PersistenceJPAConfig; +import org.baeldung.config.PersistenceJPAConfigL2Cache; import org.baeldung.persistence.model.Foo; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class) +@DirtiesContext public class FooPaginationPersistenceIntegrationTest { @PersistenceContext diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java index 4c57865f74..45316cf06c 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java @@ -3,6 +3,7 @@ package org.baeldung.persistence.service; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import org.baeldung.config.PersistenceJPAConfig; +import org.baeldung.config.PersistenceJPAConfigL2Cache; import org.baeldung.persistence.model.Foo; import org.junit.Assert; import org.junit.Test; @@ -11,12 +12,14 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.InvalidDataAccessApiUsageException; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class) +@DirtiesContext public class FooServicePersistenceIntegrationTest { @Autowired diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java index 3c9f509da5..61a3bfd565 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java @@ -10,17 +10,19 @@ import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; -import org.baeldung.config.PersistenceJPAConfig; +import org.baeldung.config.PersistenceJPAConfigL2Cache; import org.baeldung.persistence.model.Bar; import org.baeldung.persistence.model.Foo; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class) +@DirtiesContext @SuppressWarnings("unchecked") public class FooServiceSortingIntegrationTest { diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java index 040eee1c73..50fdf5f0f3 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java @@ -10,16 +10,19 @@ import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.baeldung.config.PersistenceJPAConfig; +import org.baeldung.config.PersistenceJPAConfigL2Cache; import org.baeldung.persistence.model.Foo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class) +@DirtiesContext public class FooServiceSortingWitNullsManualIntegrationTest { @PersistenceContext diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java deleted file mode 100644 index f20af34057..0000000000 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java +++ /dev/null @@ -1,96 +0,0 @@ -package org.baeldung.persistence.service; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.Arrays; - -import org.baeldung.config.ProductConfig; -import org.baeldung.config.UserConfig; -import org.baeldung.persistence.multiple.dao.product.ProductRepository; -import org.baeldung.persistence.multiple.dao.user.PossessionRepository; -import org.baeldung.persistence.multiple.dao.user.UserRepository; -import org.baeldung.persistence.multiple.model.product.Product; -import org.baeldung.persistence.multiple.model.user.Possession; -import org.baeldung.persistence.multiple.model.user.User; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.transaction.annotation.EnableTransactionManagement; -import org.springframework.transaction.annotation.Transactional; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { UserConfig.class, ProductConfig.class }) -@EnableTransactionManagement -public class JpaMultipleDBIntegrationTest { - - @Autowired - private UserRepository userRepository; - - @Autowired - private PossessionRepository possessionRepository; - - @Autowired - private ProductRepository productRepository; - - // tests - - @Test - @Transactional("userTransactionManager") - public void whenCreatingUser_thenCreated() { - User user = new User(); - user.setName("John"); - user.setEmail("john@test.com"); - user.setAge(20); - Possession p = new Possession("sample"); - p = possessionRepository.save(p); - user.setPossessionList(Arrays.asList(p)); - user = userRepository.save(user); - final User result = userRepository.findOne(user.getId()); - assertNotNull(result); - System.out.println(result.getPossessionList()); - assertTrue(result.getPossessionList().size() == 1); - } - - @Test - @Transactional("userTransactionManager") - public void whenCreatingUsersWithSameEmail_thenRollback() { - User user1 = new User(); - user1.setName("John"); - user1.setEmail("john@test.com"); - user1.setAge(20); - user1 = userRepository.save(user1); - assertNotNull(userRepository.findOne(user1.getId())); - - User user2 = new User(); - user2.setName("Tom"); - user2.setEmail("john@test.com"); - user2.setAge(10); - try { - user2 = userRepository.save(user2); - userRepository.flush(); - fail("DataIntegrityViolationException should be thrown!"); - } catch (final DataIntegrityViolationException e) { - // Expected - } catch (final Exception e) { - fail("DataIntegrityViolationException should be thrown, instead got: " + e); - } - } - - @Test - @Transactional("productTransactionManager") - public void whenCreatingProduct_thenCreated() { - Product product = new Product(); - product.setName("Book"); - product.setId(2); - product.setPrice(20); - product = productRepository.save(product); - - assertNotNull(productRepository.findOne(product.getId())); - } - -} diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java index aa2dfb5293..beaa51f5f9 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java @@ -8,7 +8,6 @@ import org.junit.runners.Suite; FooPaginationPersistenceIntegrationTest.class ,FooServicePersistenceIntegrationTest.class ,FooServiceSortingIntegrationTest.class - ,JpaMultipleDBIntegrationTest.class ,FooServiceSortingWitNullsManualIntegrationTest.class }) // @formatter:on public class PersistenceTestSuite { diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java index 907043b8ce..4de8d321d5 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java @@ -8,6 +8,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @@ -24,6 +25,7 @@ import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class) +@DirtiesContext public class SecondLevelCacheIntegrationTest { @PersistenceContext diff --git a/pom.xml b/pom.xml index 452c7838f7..7a7e2d7f64 100644 --- a/pom.xml +++ b/pom.xml @@ -1,454 +1,1199 @@ - - 4.0.0 - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - parent-modules - pom + + 4.0.0 - - parent-boot-5 - parent-boot-2 - parent-spring - parent-java - asm - atomix - apache-cayenne - aws - akka-streams - algorithms - annotations - apache-cxf - apache-fop - apache-poi - apache-tika - apache-thrift - apache-curator - apache-zookeeper - apache-opennlp - autovalue - axon - bootique - cdi - - core-java - core-java-collections - core-java-io - core-java-8 - - core-groovy - core-java-concurrency - couchbase - deltaspike - dozer - ethereumj - - feign - flips - - geotools - testing-modules/groovy-spock - google-cloud - gson - guava - guava-modules/guava-18 - guava-modules/guava-19 - guava-modules/guava-21 - guice - disruptor - handling-spring-static-resources - hazelcast - hbase - - httpclient - hystrix - - immutables - influxdb - jackson - - vavr - java-lite - java-rmi - java-vavr-stream - javax-servlets - javaxval - jaxb - javafx - jgroups - jee-7 - - jjwt - jpa-storedprocedure - jsf - json-path - json - jsoup - testing-modules/junit-5 - jws - - libraries-data - linkrest - logging-modules/log-mdc - logging-modules/log4j - logging-modules/log4j2 - logging-modules/logback - lombok - mapstruct - metrics - maven - mesos-marathon - testing-modules/mockito - testing-modules/mockito-2 - testing-modules/mocks - mustache - mvn-wrapper - noexception - orientdb - osgi - orika - patterns - pdf - protobuffer - persistence-modules/querydsl - reactor-core - persistence-modules/redis - testing-modules/rest-assured - testing-modules/rest-testing - resteasy - rxjava - spring-swagger-codegen - testing-modules/selenium-junit-testng - persistence-modules/solr - spark-java - spring-4 - spring-5 - spring-5-reactive - spring-5-mvc - spring-5-security - spring-activiti - spring-akka - spring-amqp - spring-all - spring-amqp-simple - spring-apache-camel - spring-batch - spring-bom - spring-boot - spring-boot-keycloak - spring-boot-bootstrap - spring-boot-admin - spring-boot-ops - spring-boot-security - spring-cloud-data-flow - spring-cloud - spring-core - spring-cucumber - spring-ejb - spring-aop - persistence-modules/spring-data-cassandra - spring-data-couchbase-2 - persistence-modules/spring-data-dynamodb - spring-data-elasticsearch - spring-data-keyvalue - spring-data-mongodb - persistence-modules/spring-data-neo4j - persistence-modules/spring-data-redis - spring-data-rest - persistence-modules/spring-data-solr - spring-dispatcher-servlet - spring-exceptions - spring-freemarker - persistence-modules/spring-hibernate-3 - spring-hibernate4 - persistence-modules/spring-hibernate-5 - persistence-modules/spring-data-eclipselink - spring-integration - spring-jenkins-pipeline - spring-jersey - - spring-jms - spring-jooq - persistence-modules/spring-jpa - spring-kafka - spring-katharsis - spring-ldap - spring-mockito - spring-mvc-email - spring-mvc-forms-jsp - spring-mvc-forms-thymeleaf - spring-mvc-java - spring-mvc-tiles - spring-mvc-velocity - spring-mvc-webflow - spring-mvc-xml - spring-mvc-simple - spring-mvc-kotlin - spring-security-openid - spring-protobuf - spring-quartz - spring-rest-angular - spring-rest-full - spring-rest-query-language - spring-rest - spring-rest-simple - spring-security-acl - spring-security-cache-control - spring-security-client/spring-security-jsp-authentication - spring-security-client/spring-security-jsp-authorize - spring-security-client/spring-security-jsp-config - spring-security-client/spring-security-mvc - spring-security-client/spring-security-thymeleaf-authentication - spring-security-client/spring-security-thymeleaf-authorize - spring-security-client/spring-security-thymeleaf-config - spring-security-core - spring-security-mvc-boot - spring-security-mvc-custom - spring-security-mvc-digest-auth - spring-security-mvc-ldap - spring-security-mvc-login - spring-security-mvc-persisted-remember-me - spring-security-mvc-session - spring-security-mvc-socket - spring-security-rest-basic-auth - spring-security-rest-custom - spring-security-rest - spring-security-sso - spring-security-x509 - spring-session - spring-sleuth - spring-social-login - spring-spel - spring-state-machine - spring-thymeleaf - spring-userservice - spring-zuul - spring-reactor - spring-vertx - spring-jinq - spring-rest-embedded-tomcat - testing-modules/testing - testing-modules/testng - video-tutorials - xml - xmlunit-2 - struts-2 - apache-velocity - apache-solrj - rabbitmq - vertx - persistence-modules/spring-data-gemfire - mybatis - spring-drools - drools - persistence-modules/liquibase - spring-boot-property-exp - testing-modules/mockserver - undertow - vertx-and-rxjava - saas - deeplearning4j - lucene - vraptor - persistence-modules/java-cockroachdb - spring-security-thymeleaf - persistence-modules/java-jdbi - jersey - java-spi - performance-tests - twilio - + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + parent-modules + pom - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - ch.qos.logback - logback-core - ${logback.version} - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + ch.qos.logback + logback-core + ${logback.version} + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + - - - junit - junit - ${junit.version} - test - - + + + junit + junit + ${junit.version} + test + + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + test + + org.junit.jupiter - junit-jupiter-engine - ${junit.jupiter.version} - test + junit-jupiter-api + ${junit-jupiter.version} + test - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-all - ${org.hamcrest.version} - test - - - org.mockito - mockito-core - ${mockito.version} - test - - + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-all + ${org.hamcrest.version} + test + + + org.mockito + mockito-core + ${mockito.version} + test + + + org.apache.maven.surefire + surefire-logger-api + ${maven-surefire-plugin.version} + + test + true + + - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - maven - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/JdbcTest.java - **/*LiveTest.java - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-pmd-plugin - 3.9.0 - - - org.baeldung.pmd - custom-pmd - 0.0.1 - - - - 5 - true - false - true - true - true - UTF-8 - 1.8 - - ${tutorialsproject.basedir}/baeldung-pmd-rules.xml - - - - - compile - - check - - - - - - org.commonjava.maven.plugins - directory-maven-plugin - 0.3.1 - - - directories - - directory-of - - validate - - tutorialsproject.basedir - - com.baeldung - parent-modules - - - - - - - org.apache.maven.plugins - maven-install-plugin - 2.5.1 - - org.baeldung.pmd - custom-pmd - 0.0.1 - jar - ${tutorialsproject.basedir}/custom-pmd-0.0.1.jar - true - - - - install-jar-lib - - install-file - - validate - - - - + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + maven + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + + + + org.junit.platform + junit-platform-surefire-provider + ${junit-platform.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + + + org.junit.vintage + junit-vintage-engine + ${junit-jupiter.version} + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + + + + org.apache.maven.plugins + maven-pmd-plugin + ${maven-pmd-plugin.version} + + + org.baeldung.pmd + custom-pmd + ${custom-pmd.version} + + + + 5 + false + true + true + true + true + UTF-8 + ${java.version} + + ${tutorialsproject.basedir}/baeldung-pmd-rules.xml + + + target/generated-sources + + + + + compile + + check + + + + + + org.commonjava.maven.plugins + directory-maven-plugin + ${directory-maven-plugin.version} + + + directories + + directory-of + + validate + + tutorialsproject.basedir + + com.baeldung + parent-modules + + + + + + + org.apache.maven.plugins + maven-install-plugin + ${maven-install-plugin.version} + + org.baeldung.pmd + custom-pmd + ${custom-pmd.version} + jar + ${tutorialsproject.basedir}/custom-pmd-${custom-pmd.version}.jar + true + + + + install-jar-lib + + install-file + + validate + + + + + maven-war-plugin + ${maven-war-plugin.version} + + + + + com.vackosar.gitflowincrementalbuilder + gitflow-incremental-builder + ${gitflow-incremental-builder.version} + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.commonjava.maven.plugins + + + directory-maven-plugin + + + [0.3.1,) + + + directory-of + + + + + + + + + + org.apache.maven.plugins + + + maven-install-plugin + + + [2.5.1,) + + + install-file + + + + + + + + + + + + + - - - com.vackosar.gitflowincrementalbuilder - gitflow-incremental-builder - 3.4 - - + - + + default + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + + + + + + + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + asm + atomix + apache-cayenne + aws + aws-lambda + akka-streams + algorithms + annotations + apache-cxf + apache-fop + apache-poi + apache-tika + apache-thrift + apache-curator + apache-zookeeper + apache-opennlp + autovalue + axon + azure + bootique + cdi + java-strings + + core-java + core-java-collections + core-java-io + core-java-8 + java-streams + core-java-persistence + core-kotlin + kotlin-libraries + core-groovy + core-java-concurrency + core-java-concurrency-collections + couchbase + deltaspike + dozer + ethereum + ejb + ejb/ejb-client + feign + flips + testing-modules/gatling + geotools + testing-modules/groovy-spock + google-cloud + google-web-toolkit + gson + guava + guava-modules/guava-18 + guava-modules/guava-19 + guava-modules/guava-21 + guice + disruptor + spring-static-resources + hazelcast + hbase + hibernate5 + httpclient + hystrix + image-processing + immutables + influxdb + jackson + persistence-modules/java-cassandra + vavr + java-lite + java-numbers + java-rmi + java-vavr-stream + javax-servlets + javaxval + jaxb + javafx + jgroups + jee-7 + jhipster/jhipster-monolithic + jjwt + jsf + json-path + json + jsoup + testing-modules/junit-5 + jws + libraries + libraries-data + libraries-server + linkrest + logging-modules/log-mdc + logging-modules/log4j + logging-modules/log4j2 + logging-modules/logback + lombok + mapstruct + metrics + maven + mesos-marathon + msf4j + testing-modules/mockito + testing-modules/mockito-2 + testing-modules/mocks + mustache + mvn-wrapper + noexception + orientdb + osgi + orika + patterns + pdf + protobuffer + persistence-modules/querydsl + reactor-core + persistence-modules/redis + testing-modules/rest-assured + testing-modules/rest-testing + resteasy + rxjava + rxjava-2 + spring-swagger-codegen + testing-modules/selenium-junit-testng + persistence-modules/solr + spark-java + spring-4 + spring-5 + spring-5-data-reactive + spring-5-reactive + spring-5-reactive-security + spring-5-reactive-client + spring-5-mvc + spring-5-security + spring-activiti + spring-akka + spring-amqp + spring-all + spring-amqp-simple + spring-apache-camel + spring-batch + spring-bom + spring-boot + spring-boot-client + spring-boot-keycloak + spring-boot-bootstrap + spring-boot-admin + spring-boot-camel + spring-boot-ops + spring-boot-persistence + spring-boot-security + spring-boot-mvc + spring-boot-vue + spring-boot-logging-log4j2 + spring-cloud-data-flow + spring-cloud + spring-core + spring-cucumber + spring-ejb + spring-ejb/spring-ejb-client + spring-aop + persistence-modules/spring-data-cassandra + spring-data-couchbase-2 + persistence-modules/spring-data-dynamodb + spring-data-elasticsearch + spring-data-jpa + spring-data-keyvalue + spring-data-mongodb + persistence-modules/spring-data-neo4j + persistence-modules/spring-data-redis + spring-data-rest + persistence-modules/spring-data-solr + spring-dispatcher-servlet + spring-exceptions + spring-freemarker + persistence-modules/spring-hibernate-3 + spring-hibernate4 + persistence-modules/spring-hibernate-5 + persistence-modules/spring-data-eclipselink + spring-integration + spring-jenkins-pipeline + spring-jersey + jmeter + spring-jms + spring-jooq + persistence-modules/spring-jpa + spring-kafka + spring-katharsis + spring-ldap + spring-mockito + spring-mvc-forms-jsp + spring-mvc-forms-thymeleaf + spring-mvc-java + spring-mvc-velocity + spring-mvc-webflow + spring-mvc-xml + spring-mvc-kotlin + spring-protobuf + spring-quartz + spring-rest-angular + spring-rest-full + spring-rest-query-language + spring-rest + spring-resttemplate + spring-rest-simple + spring-security-acl + spring-security-cache-control + spring-security-client/spring-security-jsp-authentication + spring-security-client/spring-security-jsp-authorize + spring-security-client/spring-security-jsp-config + spring-security-client/spring-security-mvc + spring-security-client/spring-security-thymeleaf-authentication + spring-security-client/spring-security-thymeleaf-authorize + spring-security-client/spring-security-thymeleaf-config + spring-security-core + spring-security-mvc-boot + spring-security-mvc-custom + spring-security-mvc-digest-auth + spring-security-mvc-ldap + spring-security-mvc-login + spring-security-mvc-persisted-remember-me + spring-security-mvc-session + spring-security-mvc-socket + spring-security-openid + + spring-security-rest-basic-auth + spring-security-rest-custom + spring-security-rest + spring-security-sso + spring-security-x509 + spring-session + spring-sleuth + spring-social-login + spring-spel + spring-state-machine + spring-thymeleaf + spring-userservice + spring-zuul + spring-remoting + spring-reactor + spring-vertx + spring-jinq + spring-rest-embedded-tomcat + testing-modules/testing + testing-modules/testng + video-tutorials + xml + xmlunit-2 + struts-2 + apache-velocity + apache-solrj + rabbitmq + vertx + persistence-modules/spring-data-gemfire + mybatis + spring-drools + drools + persistence-modules/liquibase + spring-boot-property-exp + testing-modules/mockserver + testing-modules/test-containers + undertow + vaadin + vertx-and-rxjava + saas + deeplearning4j + lucene + vraptor + persistence-modules/java-cockroachdb + spring-security-thymeleaf + persistence-modules/java-jdbi + jersey + java-spi + performance-tests + twilio + spring-boot-ctx-fluent + java-ee-8-security-api + spring-webflux-amqp + antlr + maven-archetype + optaplanner + apache-meecrowave + spring-reactive-kotlin + jnosql + spring-boot-angular-ecommerce + jta + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + + + json + + + + + + + + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + + + + + + + + + testing-modules/mockito + testing-modules/mockito-2 + testing-modules/mocks + mustache + mvn-wrapper + noexception + orientdb + osgi + orika + patterns + pdf + protobuffer + persistence-modules/querydsl + reactor-core + persistence-modules/redis + testing-modules/rest-assured + testing-modules/rest-testing + resteasy + rxjava + rxjava-2 + spring-swagger-codegen + testing-modules/selenium-junit-testng + persistence-modules/solr + spark-java + spring-4 + spring-5 + spring-5-data-reactive + spring-5-reactive + spring-5-reactive-security + spring-5-reactive-client + spring-5-mvc + spring-5-security + spring-activiti + spring-akka + spring-amqp + spring-all + spring-amqp-simple + spring-apache-camel + spring-batch + jmh + + + + + + spring-bom + spring-boot + spring-boot-client + spring-boot-keycloak + spring-boot-bootstrap + spring-boot-admin + spring-boot-camel + spring-boot-ops + spring-boot-persistence + spring-boot-security + spring-boot-mvc + spring-boot-logging-log4j2 + spring-cloud-data-flow + spring-cloud + spring-core + spring-cucumber + spring-ejb + spring-ejb/spring-ejb-client + spring-aop + persistence-modules/spring-data-cassandra + spring-data-couchbase-2 + persistence-modules/spring-data-dynamodb + spring-data-elasticsearch + spring-data-keyvalue + spring-data-mongodb + spring-data-jpa + persistence-modules/spring-data-neo4j + persistence-modules/spring-data-redis + spring-data-rest + + + + + + + persistence-modules/spring-data-solr + spring-dispatcher-servlet + spring-exceptions + spring-freemarker + persistence-modules/spring-hibernate-3 + spring-hibernate4 + persistence-modules/spring-hibernate-5 + persistence-modules/spring-data-eclipselink + spring-integration + spring-jenkins-pipeline + spring-jersey + spring-jms + spring-jooq + persistence-modules/spring-jpa + spring-kafka + spring-katharsis + spring-ldap + spring-mockito + spring-mvc-forms-jsp + spring-mvc-forms-thymeleaf + spring-mvc-java + spring-mvc-velocity + spring-mvc-webflow + spring-mvc-xml + spring-mvc-kotlin + spring-protobuf + spring-quartz + spring-rest-angular + spring-rest-full + spring-rest-query-language + spring-rest + spring-resttemplate + spring-rest-simple + spring-reactive-kotlin + + + + + + + + + + + + + + + + + + + + + integration-lite + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + + + json + + + + + + + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + asm + atomix + apache-cayenne + aws + aws-lambda + akka-streams + algorithms + annotations + apache-cxf + apache-fop + apache-poi + apache-tika + apache-thrift + apache-curator + apache-zookeeper + apache-opennlp + autovalue + axon + azure + bootique + cdi + java-strings + + core-java-collections + core-java-io + core-java-8 + java-streams + core-groovy + + couchbase + deltaspike + dozer + ethereum + feign + flips + testing-modules/groovy-spock + google-cloud + gson + guava + guava-modules/guava-18 + guava-modules/guava-19 + guava-modules/guava-21 + guice + disruptor + spring-static-resources + hazelcast + hbase + + hystrix + image-processing + immutables + influxdb + jackson + vavr + java-lite + java-numbers + java-rmi + java-vavr-stream + javax-servlets + javaxval + jaxb + javafx + jgroups + jee-7 + jjwt + jsf + json-path + json + jsoup + jta + testing-modules/junit-5 + testing-modules/junit5-migration + jws + libraries-data + linkrest + logging-modules/log-mdc + logging-modules/log4j + + logging-modules/logback + lombok + mapstruct + + maven + mesos-marathon + msf4j + testing-modules/mockito + testing-modules/mockito-2 + testing-modules/mocks + mustache + mvn-wrapper + noexception + orientdb + osgi + orika + patterns + pdf + protobuffer + persistence-modules/querydsl + reactor-core + persistence-modules/redis + testing-modules/rest-assured + testing-modules/rest-testing + resteasy + rxjava + rxjava-2 + spring-swagger-codegen + testing-modules/selenium-junit-testng + persistence-modules/solr + spark-java + spring-4 + spring-5-data-reactive + spring-5-reactive + spring-5-reactive-security + spring-5-reactive-client + spring-5-mvc + spring-5-security + spring-activiti + spring-akka + spring-amqp + spring-all + spring-amqp-simple + spring-apache-camel + spring-batch + spring-bom + spring-boot-keycloak + spring-boot-bootstrap + spring-boot-admin + spring-boot-camel + spring-boot-persistence + spring-boot-security + spring-boot-mvc + spring-boot-logging-log4j2 + spring-cloud-data-flow + spring-cloud + spring-core + spring-cucumber + spring-ejb + spring-ejb/spring-ejb-client + spring-aop + + persistence-modules/spring-data-dynamodb + spring-data-keyvalue + spring-data-mongodb + persistence-modules/spring-data-neo4j + + spring-data-rest + persistence-modules/spring-data-solr + spring-dispatcher-servlet + spring-exceptions + spring-freemarker + persistence-modules/spring-hibernate-3 + + persistence-modules/spring-hibernate-5 + persistence-modules/spring-data-eclipselink + spring-integration + spring-jenkins-pipeline + spring-jersey + + spring-jms + spring-jooq + persistence-modules/spring-jpa + spring-kafka + spring-katharsis + spring-ldap + spring-mockito + spring-mvc-forms-jsp + spring-mvc-forms-thymeleaf + spring-mvc-java + spring-mvc-velocity + spring-mvc-webflow + spring-mvc-xml + spring-mvc-kotlin + spring-protobuf + spring-quartz + spring-rest-angular + spring-rest-full + spring-rest-query-language + spring-rest + spring-resttemplate + spring-rest-simple + spring-security-acl + spring-security-cache-control + spring-security-client/spring-security-jsp-authentication + spring-security-client/spring-security-jsp-authorize + spring-security-client/spring-security-jsp-config + spring-security-client/spring-security-mvc + spring-security-client/spring-security-thymeleaf-authentication + spring-security-client/spring-security-thymeleaf-authorize + spring-security-client/spring-security-thymeleaf-config + spring-security-core + spring-security-mvc-boot + spring-security-mvc-digest-auth + spring-security-mvc-ldap + spring-security-mvc-login + spring-security-mvc-persisted-remember-me + spring-security-mvc-session + spring-security-mvc-socket + spring-security-openid + + spring-security-rest-basic-auth + spring-security-rest-custom + spring-security-rest + spring-security-sso + spring-security-x509 + spring-session + spring-sleuth + spring-social-login + spring-spel + spring-state-machine + spring-thymeleaf + spring-userservice + spring-zuul + spring-remoting + spring-reactor + spring-vertx + spring-vault + spring-jinq + spring-rest-embedded-tomcat + testing-modules/testing + testing-modules/testng + video-tutorials + + xmlunit-2 + struts-2 + apache-velocity + apache-solrj + rabbitmq + + persistence-modules/spring-data-gemfire + mybatis + spring-drools + drools + persistence-modules/liquibase + spring-boot-property-exp + testing-modules/mockserver + testing-modules/test-containers + undertow + vaadin + vertx-and-rxjava + saas + deeplearning4j + lucene + vraptor + persistence-modules/java-cockroachdb + spring-security-thymeleaf + persistence-modules/java-jdbi + jersey + jersey-client-rx + java-spi + performance-tests + twilio + spring-boot-ctx-fluent + java-ee-8-security-api + spring-webflux-amqp + antlr + maven-archetype + apache-meecrowave + + spring-hibernate4 + xml + vertx + metrics + httpclient + + + + + + + + + + + - - integration + integration-heavy + @@ -467,6 +1212,7 @@ **/*IntegrationTest.java + **/*IntTest.java @@ -479,56 +1225,92 @@ + + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + libraries + geotools + jhipster/jhipster-monolithic + testing-modules/gatling + spring-boot + spring-boot-ops + spring-5 + core-kotlin + kotlin-libraries + core-java + google-web-toolkit + spring-security-mvc-custom + hibernate5 + spring-data-elasticsearch + core-java-concurrency + core-java-concurrency-collections + + - - - - - org.apache.maven.plugins - maven-jxr-plugin - 2.3 - - - - - UTF-8 - refs/heads/master - true - false - false - - 4.12 - 1.3 - 2.8.9 - - 1.7.21 - 1.1.7 - - 2.21.0 - 3.7.0 - 1.6.0 - 1.8 - 1.2.17 - 1.1 - 2.1.0.1 - 1.19 - 1.19 - 1.3 - 1.6.0 - 2.19.1 - 2.5 - 1.4 - 2.6 - 3.1.0 - 1.2 - 2.3.1 - 1.9.13 - 1.2 - 2.5.0 - 1.3 - 5.0.2 - + + + + + org.apache.maven.plugins + maven-jxr-plugin + ${maven-jxr-plugin.version} + + + + + + UTF-8 + UTF-8 + refs/heads/master + true + false + false + + 4.12 + 1.3 + 2.21.0 + + 1.7.21 + 1.1.7 + + 2.21.0 + 3.7.0 + 1.6.0 + 1.8 + 1.2.17 + 1.1 + 2.1.0.1 + 1.19 + 1.19 + 1.3 + 1.6.0 + 2.19.1 + 2.5 + 1.4 + 3.0.0 + 3.1.0 + 1.2 + 2.3.1 + 1.9.13 + 1.2 + 2.5.0 + 1.3 + 1.2.0 + 5.2.0 + 0.3.1 + 2.5.1 + 0.0.1 + 3.4 + 2.3 + + 3.8 + diff --git a/protobuffer/pom.xml b/protobuffer/pom.xml index 919a49e67d..ff443a1615 100644 --- a/protobuffer/pom.xml +++ b/protobuffer/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 protobuffer diff --git a/protobuffer/src/main/resources/logback.xml b/protobuffer/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/protobuffer/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/rabbitmq/pom.xml b/rabbitmq/pom.xml index 391d7933ea..b620248cfc 100644 --- a/rabbitmq/pom.xml +++ b/rabbitmq/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.baeldung @@ -25,7 +24,6 @@ - UTF-8 3.6.6 diff --git a/rabbitmq/src/main/resources/logback.xml b/rabbitmq/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/rabbitmq/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/ratpack/build.gradle b/ratpack/build.gradle index aeddd5f9f9..25af3ddb51 100644 --- a/ratpack/build.gradle +++ b/ratpack/build.gradle @@ -1,35 +1,35 @@ -buildscript { - repositories { - jcenter() - } - dependencies { - classpath "io.ratpack:ratpack-gradle:1.4.5" - classpath "com.h2database:h2:1.4.193" - } -} - -if (!JavaVersion.current().java8Compatible) { - throw new IllegalStateException("Must be built with Java 8 or higher") -} - -apply plugin: "io.ratpack.ratpack-java" -apply plugin: 'java' - -repositories { - jcenter() -} - -dependencies { - compile ratpack.dependency('hikari') - compile 'com.h2database:h2:1.4.193' - testCompile 'junit:junit:4.11' - runtime "org.slf4j:slf4j-simple:1.7.21" -} - -test { - testLogging { - events 'started', 'passed' - } -} - -mainClassName = "com.baeldung.Application" +buildscript { + repositories { + jcenter() + } + dependencies { + classpath "io.ratpack:ratpack-gradle:1.5.4" + classpath "com.h2database:h2:1.4.193" + } +} + +if (!JavaVersion.current().java8Compatible) { + throw new IllegalStateException("Must be built with Java 8 or higher") +} + +apply plugin: "io.ratpack.ratpack-java" +apply plugin: 'java' + +repositories { + jcenter() +} + +dependencies { + compile ratpack.dependency('hikari') + compile 'com.h2database:h2:1.4.193' + testCompile 'junit:junit:4.11' + runtime "org.slf4j:slf4j-simple:1.7.21" +} + +test { + testLogging { + events 'started', 'passed' + } +} + +mainClassName = "com.baeldung.Application" diff --git a/ratpack/pom.xml b/ratpack/pom.xml index bf43168b02..7de11e6955 100644 --- a/ratpack/pom.xml +++ b/ratpack/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung ratpack @@ -35,6 +35,17 @@ io.ratpack ratpack-hystrix ${ratpack.version} + + + com.netflix.hystrix + hystrix-core + + + + + com.netflix.hystrix + hystrix-core + ${hystrix.version} io.ratpack @@ -74,13 +85,13 @@ - UTF-8 1.8 1.8 - 1.4.6 + 1.5.4 4.5.3 4.4.6 1.4.193 + 1.5.12 diff --git a/ratpack/src/main/java/com/baeldung/Application.java b/ratpack/src/main/java/com/baeldung/Application.java index 7f46b241ea..4a391d04a1 100644 --- a/ratpack/src/main/java/com/baeldung/Application.java +++ b/ratpack/src/main/java/com/baeldung/Application.java @@ -1,49 +1,81 @@ -package com.baeldung; - -import java.util.ArrayList; -import java.util.List; - -import com.baeldung.filter.RequestValidatorFilter; -import com.baeldung.model.Employee; - -import ratpack.guice.Guice; -import ratpack.hikari.HikariModule; -import ratpack.http.MutableHeaders; -import ratpack.jackson.Jackson; -import ratpack.http.MutableHeaders; -import ratpack.server.RatpackServer; - -public class Application { - - public static void main(String[] args) throws Exception { - - List employees = new ArrayList(); - employees.add(new Employee(1L, "Mr", "John Doe")); - employees.add(new Employee(2L, "Mr", "White Snow")); - - - RatpackServer.start( - server -> server.registry(Guice.registry(bindings -> bindings.module(HikariModule.class, config -> { - config.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource"); - config.addDataSourceProperty("URL", - "jdbc:h2:mem:baeldung;INIT=RUNSCRIPT FROM 'classpath:/DDL.sql'"); - }))).handlers(chain -> chain - .all( - // ctx -> { - // MutableHeaders headers = - // ctx.getResponse().getHeaders(); - // headers.set("Access-Control-Allow-Origin","*"); - // headers.set("Accept-Language", "en-us"); - // headers.set("Accept-Charset", "UTF-8"); - // ctx.next(); - // } - new RequestValidatorFilter()) - .get(ctx -> ctx.render("Welcome to baeldung ratpack!!!")) - .get("data/employees", ctx -> ctx.render(Jackson.json(employees))) - .get(":name", ctx -> ctx.render("Hello " + ctx.getPathTokens().get("name") + "!!!")) - .post(":amount", ctx -> ctx - .render(" Amount $" + ctx.getPathTokens().get("amount") + " added successfully !!!")))); - } - -} - +package com.baeldung; + +import com.baeldung.filter.RequestValidatorFilter; +import com.baeldung.handler.EmployeeHandler; +import com.baeldung.handler.RedirectHandler; +import com.baeldung.model.Employee; +import com.baeldung.repository.EmployeeRepository; +import com.baeldung.repository.EmployeeRepositoryImpl; +import com.zaxxer.hikari.HikariConfig; +import io.netty.buffer.PooledByteBufAllocator; +import ratpack.func.Action; +import ratpack.func.Function; +import ratpack.guice.BindingsSpec; +import ratpack.guice.Guice; +import ratpack.handling.Chain; +import ratpack.hikari.HikariModule; +import ratpack.http.client.HttpClient; +import ratpack.jackson.Jackson; +import ratpack.registry.Registry; +import ratpack.server.RatpackServer; +import ratpack.server.RatpackServerSpec; +import ratpack.server.ServerConfig; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; + +public class Application { + + public static void main(String[] args) throws Exception { + + final Action hikariConfigAction = hikariConfig -> { + hikariConfig.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource"); + hikariConfig.addDataSourceProperty("URL", "jdbc:h2:mem:baeldung;INIT=RUNSCRIPT FROM 'classpath:/DDL.sql'"); + }; + + final Action bindingsSpecAction = bindings -> bindings.module(HikariModule.class, hikariConfigAction); + final HttpClient httpClient = HttpClient.of(httpClientSpec -> { + httpClientSpec.poolSize(10) + .connectTimeout(Duration.of(60, ChronoUnit.SECONDS)) + .maxContentLength(ServerConfig.DEFAULT_MAX_CONTENT_LENGTH) + .responseMaxChunkSize(16384) + .readTimeout(Duration.of(60, ChronoUnit.SECONDS)) + .byteBufAllocator(PooledByteBufAllocator.DEFAULT); + }); + final Function registryFunction = Guice.registry(bindingsSpecAction); + + final Action chainAction = chain -> chain.all(new RequestValidatorFilter()) + .get(ctx -> ctx.render("Welcome to baeldung ratpack!!!")) + .get("data/employees", ctx -> ctx.render(Jackson.json(createEmpList()))) + .get(":name", ctx -> ctx.render("Hello " + ctx.getPathTokens() + .get("name") + "!!!")) + .post(":amount", ctx -> ctx.render(" Amount $" + ctx.getPathTokens() + .get("amount") + " added successfully !!!")); + + final Action routerChainAction = routerChain -> { + routerChain.path("redirect", new RedirectHandler()) + .prefix("employee", empChain -> { + empChain.get(":id", new EmployeeHandler()); + }); + }; + final Action ratpackServerSpecAction = serverSpec -> serverSpec.registry(registryFunction) + .registryOf(registrySpec -> { + registrySpec.add(EmployeeRepository.class, new EmployeeRepositoryImpl()); + registrySpec.add(HttpClient.class, httpClient); + }) + .handlers(chain -> chain.insert(routerChainAction) + .insert(chainAction)); + + RatpackServer.start(ratpackServerSpecAction); + } + + private static List createEmpList() { + List employees = new ArrayList<>(); + employees.add(new Employee(1L, "Mr", "John Doe")); + employees.add(new Employee(2L, "Mr", "White Snow")); + return employees; + } + +} diff --git a/ratpack/src/main/java/com/baeldung/handler/EmployeeHandler.java b/ratpack/src/main/java/com/baeldung/handler/EmployeeHandler.java new file mode 100644 index 0000000000..9a6b79259c --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/handler/EmployeeHandler.java @@ -0,0 +1,20 @@ +package com.baeldung.handler; + +import com.baeldung.repository.EmployeeRepository; +import com.baeldung.model.Employee; +import ratpack.exec.Promise; +import ratpack.handling.Context; +import ratpack.handling.Handler; + +public class EmployeeHandler implements Handler { + @Override + public void handle(Context ctx) throws Exception { + EmployeeRepository repository = ctx.get(EmployeeRepository.class); + Long id = Long.valueOf(ctx.getPathTokens() + .get("id")); + Promise employeePromise = repository.findEmployeeById(id); + employeePromise.map(employee -> employee.getName()) + .then(name -> ctx.getResponse() + .send(name)); + } +} diff --git a/ratpack/src/main/java/com/baeldung/handler/FooHandler.java b/ratpack/src/main/java/com/baeldung/handler/FooHandler.java new file mode 100644 index 0000000000..d2c4dbdce5 --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/handler/FooHandler.java @@ -0,0 +1,12 @@ +package com.baeldung.handler; + +import ratpack.handling.Context; +import ratpack.handling.Handler; + +public class FooHandler implements Handler { + @Override + public void handle(Context ctx) throws Exception { + ctx.getResponse() + .send("Hello Foo!"); + } +} diff --git a/ratpack/src/main/java/com/baeldung/handler/RedirectHandler.java b/ratpack/src/main/java/com/baeldung/handler/RedirectHandler.java new file mode 100644 index 0000000000..c95543a961 --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/handler/RedirectHandler.java @@ -0,0 +1,23 @@ +package com.baeldung.handler; + +import ratpack.exec.Promise; +import ratpack.handling.Context; +import ratpack.handling.Handler; +import ratpack.http.client.HttpClient; +import ratpack.http.client.ReceivedResponse; + +import java.net.URI; + +public class RedirectHandler implements Handler { + @Override + public void handle(Context ctx) throws Exception { + HttpClient client = ctx.get(HttpClient.class); + URI uri = URI.create("http://localhost:5050/employee/1"); + Promise responsePromise = client.get(uri); + responsePromise.map(response -> response.getBody() + .getText() + .toUpperCase()) + .then(responseText -> ctx.getResponse() + .send(responseText)); + } +} \ No newline at end of file diff --git a/ratpack/src/main/java/com/baeldung/repository/EmployeeRepository.java b/ratpack/src/main/java/com/baeldung/repository/EmployeeRepository.java new file mode 100644 index 0000000000..de04c23da5 --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/repository/EmployeeRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.repository; + +import com.baeldung.model.Employee; +import ratpack.exec.Promise; + +public interface EmployeeRepository { + + Promise findEmployeeById(Long id) throws Exception; + +} diff --git a/ratpack/src/main/java/com/baeldung/repository/EmployeeRepositoryImpl.java b/ratpack/src/main/java/com/baeldung/repository/EmployeeRepositoryImpl.java new file mode 100644 index 0000000000..6d15012ccb --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/repository/EmployeeRepositoryImpl.java @@ -0,0 +1,25 @@ +package com.baeldung.repository; + +import com.baeldung.model.Employee; +import ratpack.exec.Promise; + +import java.util.HashMap; +import java.util.Map; + +public class EmployeeRepositoryImpl implements EmployeeRepository { + + private static final Map EMPLOYEE_MAP = new HashMap<>(); + + public EmployeeRepositoryImpl() { + EMPLOYEE_MAP.put(1L, new Employee(1L, "Ms", "Jane Doe")); + EMPLOYEE_MAP.put(2L, new Employee(2L, "Mr", "NY")); + } + + @Override + public Promise findEmployeeById(Long id) throws Exception { + return Promise.async(downstream -> { + Thread.sleep(500); + downstream.success(EMPLOYEE_MAP.get(id)); + }); + } +} diff --git a/ratpack/src/main/resources/logback.xml b/ratpack/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/ratpack/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/ratpack/src/test/java/com/baeldung/AppHttpUnitTest.java b/ratpack/src/test/java/com/baeldung/AppHttpUnitTest.java new file mode 100644 index 0000000000..a97516dd74 --- /dev/null +++ b/ratpack/src/test/java/com/baeldung/AppHttpUnitTest.java @@ -0,0 +1,58 @@ +package com.baeldung; + +import com.baeldung.model.Employee; +import org.junit.Test; +import ratpack.exec.Promise; +import ratpack.func.Action; +import ratpack.handling.Chain; +import ratpack.handling.Handler; +import ratpack.registry.Registry; +import ratpack.test.embed.EmbeddedApp; +import ratpack.test.exec.ExecHarness; + +import static org.junit.Assert.assertEquals; + +public class AppHttpUnitTest { + + @Test + public void givenAnyUri_GetEmployeeFromSameRegistry() throws Exception { + Handler allHandler = ctx -> { + Long id = Long.valueOf(ctx.getPathTokens() + .get("id")); + Employee employee = new Employee(id, "Mr", "NY"); + ctx.next(Registry.single(Employee.class, employee)); + }; + Handler empNameHandler = ctx -> { + Employee employee = ctx.get(Employee.class); + ctx.getResponse() + .send("Name of employee with ID " + employee.getId() + " is " + employee.getName()); + }; + Handler empTitleHandler = ctx -> { + Employee employee = ctx.get(Employee.class); + ctx.getResponse() + .send("Title of employee with ID " + employee.getId() + " is " + employee.getTitle()); + }; + + Action chainAction = chain -> chain.prefix("employee/:id", empChain -> { + empChain.all(allHandler) + .get("name", empNameHandler) + .get("title", empTitleHandler); + }); + EmbeddedApp.fromHandlers(chainAction) + .test(testHttpClient -> { + assertEquals("Name of employee with ID 1 is NY", testHttpClient.get("employee/1/name") + .getBody() + .getText()); + assertEquals("Title of employee with ID 1 is Mr", testHttpClient.get("employee/1/title") + .getBody() + .getText()); + }); + } + + @Test + public void givenSyncDataSource_GetDataFromPromise() throws Exception { + String value = ExecHarness.yieldSingle(execution -> Promise.sync(() -> "Foo")) + .getValueOrThrow(); + assertEquals("Foo", value); + } +} diff --git a/reactor-core/pom.xml b/reactor-core/pom.xml index 41c42cac28..cf720ad6ea 100644 --- a/reactor-core/pom.xml +++ b/reactor-core/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung @@ -18,7 +18,6 @@ reactor-core ${reactor-core.version} - org.assertj assertj-core diff --git a/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersIntegrationTest.java b/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersIntegrationTest.java new file mode 100644 index 0000000000..e6108759e1 --- /dev/null +++ b/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersIntegrationTest.java @@ -0,0 +1,180 @@ +package com.baeldung.reactor.core; + +import java.time.Duration; + +import org.junit.Test; + +import reactor.core.publisher.Flux; +import reactor.test.StepVerifier; + +public class CombiningPublishersIntegrationTest { + + private static Integer min = 1; + private static Integer max = 5; + + private static Flux evenNumbers = Flux.range(min, max).filter(x -> x % 2 == 0); + private static Flux oddNumbers = Flux.range(min, max).filter(x -> x % 2 > 0); + + @Test + public void givenFluxes_whenMergeDelayErrorIsInvoked_thenMergeDelayError() { + Flux fluxOfIntegers = Flux.mergeDelayError(1, + evenNumbers.delayElements(Duration.ofMillis(2000L)), + oddNumbers.delayElements(Duration.ofMillis(1000L))); + + StepVerifier.create(fluxOfIntegers) + .expectNext(1) + .expectNext(2) + .expectNext(3) + .expectNext(5) + .expectNext(4) + .expectComplete() + .verify(); + } + + + /*@Test + public void givenFluxes_whenMergeWithDelayedElementsIsInvoked_thenMergeWithDelayedElements() { + Flux fluxOfIntegers = Flux.merge( + evenNumbers.delayElements(Duration.ofMillis(2000L)), + oddNumbers.delayElements(Duration.ofMillis(1000L))); + + StepVerifier.create(fluxOfIntegers) + .expectNext(1) + .expectNext(2) + .expectNext(3) + .expectNext(5) + .expectNext(4) + .expectComplete() + .verify(); + }*/ + + @Test + public void givenFluxes_whenConcatIsInvoked_thenConcat() { + Flux fluxOfIntegers = Flux.concat( + evenNumbers.delayElements(Duration.ofMillis(2000L)), + oddNumbers.delayElements(Duration.ofMillis(1000L))); + + StepVerifier.create(fluxOfIntegers) + .expectNext(2) + .expectNext(4) + .expectNext(1) + .expectNext(3) + .expectNext(5) + .expectComplete() + .verify(); + } + + @Test + public void givenFluxes_whenMergeIsInvoked_thenMerge() { + Flux fluxOfIntegers = Flux.merge( + evenNumbers, + oddNumbers); + + StepVerifier.create(fluxOfIntegers) + .expectNext(2) + .expectNext(4) + .expectNext(1) + .expectNext(3) + .expectNext(5) + .expectComplete() + .verify(); + } + + @Test + public void givenFluxes_whenConcatWithIsInvoked_thenConcatWith() { + Flux fluxOfIntegers = evenNumbers + .concatWith(oddNumbers); + + StepVerifier.create(fluxOfIntegers) + .expectNext(2) + .expectNext(4) + .expectNext(1) + .expectNext(3) + .expectNext(5) + .expectComplete() + .verify(); + } + + @Test + public void givenFluxes_whenCombineLatestIsInvoked_thenCombineLatest() { + Flux fluxOfIntegers = Flux.combineLatest( + evenNumbers, + oddNumbers, + (a, b) -> a + b); + + StepVerifier.create(fluxOfIntegers) + .expectNext(5) + .expectNext(7) + .expectNext(9) + .expectComplete() + .verify(); + + } + + @Test + public void givenFluxes_whenCombineLatestIsInvoked_thenCombineLatest1() { + StepVerifier.create(Flux.combineLatest(obj -> (int) obj[1], evenNumbers, oddNumbers)) + .expectNext(1) + .expectNext(3) + .expectNext(5) + .verifyComplete(); + } + + @Test + public void givenFluxes_whenMergeSequentialIsInvoked_thenMergeSequential() { + Flux fluxOfIntegers = Flux.mergeSequential( + evenNumbers, + oddNumbers); + + StepVerifier.create(fluxOfIntegers) + .expectNext(2) + .expectNext(4) + .expectNext(1) + .expectNext(3) + .expectNext(5) + .expectComplete() + .verify(); + } + + + @Test + public void givenFluxes_whenMergeWithIsInvoked_thenMergeWith() { + Flux fluxOfIntegers = evenNumbers.mergeWith(oddNumbers); + + StepVerifier.create(fluxOfIntegers) + .expectNext(2) + .expectNext(4) + .expectNext(1) + .expectNext(3) + .expectNext(5) + .expectComplete() + .verify(); + } + + @Test + public void givenFluxes_whenZipIsInvoked_thenZip() { + Flux fluxOfIntegers = Flux.zip( + evenNumbers, + oddNumbers, + (a, b) -> a + b); + + StepVerifier.create(fluxOfIntegers) + .expectNext(3) + .expectNext(7) + .expectComplete() + .verify(); + } + + @Test + public void givenFluxes_whenZipWithIsInvoked_thenZipWith() { + Flux fluxOfIntegers = evenNumbers + .zipWith(oddNumbers, + (a, b) -> a * b); + + StepVerifier.create(fluxOfIntegers) + .expectNext(2) + .expectNext(12) + .expectComplete() + .verify(); + } +} \ No newline at end of file diff --git a/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersTest.java b/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersTest.java deleted file mode 100644 index 5a0dcef5ba..0000000000 --- a/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersTest.java +++ /dev/null @@ -1,180 +0,0 @@ -package com.baeldung.reactor.core; - -import java.time.Duration; - -import org.junit.Test; - -import reactor.core.publisher.Flux; -import reactor.test.StepVerifier; - -public class CombiningPublishersTest { - - private static Integer min = 1; - private static Integer max = 5; - - private static Flux evenNumbers = Flux.range(min, max).filter(x -> x % 2 == 0); - private static Flux oddNumbers = Flux.range(min, max).filter(x -> x % 2 > 0); - - @Test - public void givenFluxes_whenMergeDelayErrorIsInvoked_thenMergeDelayError() { - Flux fluxOfIntegers = Flux.mergeDelayError(1, - evenNumbers.delayElements(Duration.ofMillis(2000L)), - oddNumbers.delayElements(Duration.ofMillis(1000L))); - - StepVerifier.create(fluxOfIntegers) - .expectNext(1) - .expectNext(2) - .expectNext(3) - .expectNext(5) - .expectNext(4) - .expectComplete() - .verify(); - } - - - /*@Test - public void givenFluxes_whenMergeWithDelayedElementsIsInvoked_thenMergeWithDelayedElements() { - Flux fluxOfIntegers = Flux.merge( - evenNumbers.delayElements(Duration.ofMillis(2000L)), - oddNumbers.delayElements(Duration.ofMillis(1000L))); - - StepVerifier.create(fluxOfIntegers) - .expectNext(1) - .expectNext(2) - .expectNext(3) - .expectNext(5) - .expectNext(4) - .expectComplete() - .verify(); - }*/ - - @Test - public void givenFluxes_whenConcatIsInvoked_thenConcat() { - Flux fluxOfIntegers = Flux.concat( - evenNumbers.delayElements(Duration.ofMillis(2000L)), - oddNumbers.delayElements(Duration.ofMillis(1000L))); - - StepVerifier.create(fluxOfIntegers) - .expectNext(2) - .expectNext(4) - .expectNext(1) - .expectNext(3) - .expectNext(5) - .expectComplete() - .verify(); - } - - @Test - public void givenFluxes_whenMergeIsInvoked_thenMerge() { - Flux fluxOfIntegers = Flux.merge( - evenNumbers, - oddNumbers); - - StepVerifier.create(fluxOfIntegers) - .expectNext(2) - .expectNext(4) - .expectNext(1) - .expectNext(3) - .expectNext(5) - .expectComplete() - .verify(); - } - - @Test - public void givenFluxes_whenConcatWithIsInvoked_thenConcatWith() { - Flux fluxOfIntegers = evenNumbers - .concatWith(oddNumbers); - - StepVerifier.create(fluxOfIntegers) - .expectNext(2) - .expectNext(4) - .expectNext(1) - .expectNext(3) - .expectNext(5) - .expectComplete() - .verify(); - } - - @Test - public void givenFluxes_whenCombineLatestIsInvoked_thenCombineLatest() { - Flux fluxOfIntegers = Flux.combineLatest( - evenNumbers, - oddNumbers, - (a, b) -> a + b); - - StepVerifier.create(fluxOfIntegers) - .expectNext(5) - .expectNext(7) - .expectNext(9) - .expectComplete() - .verify(); - - } - - @Test - public void givenFluxes_whenCombineLatestIsInvoked_thenCombineLatest1() { - StepVerifier.create(Flux.combineLatest(obj -> (int) obj[1], evenNumbers, oddNumbers)) - .expectNext(1) - .expectNext(3) - .expectNext(5) - .verifyComplete(); - } - - @Test - public void givenFluxes_whenMergeSequentialIsInvoked_thenMergeSequential() { - Flux fluxOfIntegers = Flux.mergeSequential( - evenNumbers, - oddNumbers); - - StepVerifier.create(fluxOfIntegers) - .expectNext(2) - .expectNext(4) - .expectNext(1) - .expectNext(3) - .expectNext(5) - .expectComplete() - .verify(); - } - - - @Test - public void givenFluxes_whenMergeWithIsInvoked_thenMergeWith() { - Flux fluxOfIntegers = evenNumbers.mergeWith(oddNumbers); - - StepVerifier.create(fluxOfIntegers) - .expectNext(2) - .expectNext(4) - .expectNext(1) - .expectNext(3) - .expectNext(5) - .expectComplete() - .verify(); - } - - @Test - public void givenFluxes_whenZipIsInvoked_thenZip() { - Flux fluxOfIntegers = Flux.zip( - evenNumbers, - oddNumbers, - (a, b) -> a + b); - - StepVerifier.create(fluxOfIntegers) - .expectNext(3) - .expectNext(7) - .expectComplete() - .verify(); - } - - @Test - public void givenFluxes_whenZipWithIsInvoked_thenZipWith() { - Flux fluxOfIntegers = evenNumbers - .zipWith(oddNumbers, - (a, b) -> a * b); - - StepVerifier.create(fluxOfIntegers) - .expectNext(2) - .expectNext(12) - .expectComplete() - .verify(); - } -} \ No newline at end of file diff --git a/rest-with-spark-java/pom.xml b/rest-with-spark-java/pom.xml index ffdb86ebca..a0005b7dec 100644 --- a/rest-with-spark-java/pom.xml +++ b/rest-with-spark-java/pom.xml @@ -1,6 +1,6 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 com.baeldung rest-with-spark-java @@ -15,12 +15,6 @@ - - junit - junit - ${junit.version} - test - com.sparkjava spark-core diff --git a/rest-with-spark-java/src/main/resources/logback.xml b/rest-with-spark-java/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/rest-with-spark-java/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/resteasy/pom.xml b/resteasy/pom.xml index 61c099f110..31a6ed485a 100644 --- a/resteasy/pom.xml +++ b/resteasy/pom.xml @@ -2,11 +2,11 @@ 4.0.0 - com.baeldung - resteasy-tutorial + resteasy 1.0 war + resteasy com.baeldung @@ -14,29 +14,6 @@ 1.0.0-SNAPSHOT - - RestEasyTutorial - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - 8082 - - - - - - - @@ -81,6 +58,29 @@ + + RestEasyTutorial + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + 8082 + + + + + + + live @@ -98,6 +98,7 @@ **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java @@ -140,7 +141,6 @@ - 3.0.19.Final 2.5 diff --git a/resteasy/src/main/resources/logback.xml b/resteasy/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/resteasy/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/rule-engines/easy-rules/pom.xml b/rule-engines/easy-rules/pom.xml index 8399eff8a2..5b88ce4e94 100644 --- a/rule-engines/easy-rules/pom.xml +++ b/rule-engines/easy-rules/pom.xml @@ -1,11 +1,9 @@ + 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.easyrules easy-rules 1.0 - easy-rules @@ -18,7 +16,11 @@ org.jeasy easy-rules-core - 3.0.0 + ${easy-rules.version} + + + 3.0.0 + \ No newline at end of file diff --git a/rule-engines/easy-rules/src/main/resources/logback.xml b/rule-engines/easy-rules/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/rule-engines/easy-rules/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/rule-engines/openl-tablets/pom.xml b/rule-engines/openl-tablets/pom.xml index 8e3f1965b5..3bd6055fc9 100644 --- a/rule-engines/openl-tablets/pom.xml +++ b/rule-engines/openl-tablets/pom.xml @@ -1,11 +1,9 @@ + 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.openltablets openl-tablets 1.0 - openl-tablets @@ -18,12 +16,17 @@ org.openl org.openl.core - 5.19.4 + ${openl.version} org.openl.rules org.openl.rules - 5.19.4 + ${openl.version} + + + 5.19.4 + + \ No newline at end of file diff --git a/rule-engines/openl-tablets/src/main/resources/logback.xml b/rule-engines/openl-tablets/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/rule-engines/openl-tablets/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/rule-engines/rulebook/pom.xml b/rule-engines/rulebook/pom.xml index 675776eb6f..90b5e55417 100644 --- a/rule-engines/rulebook/pom.xml +++ b/rule-engines/rulebook/pom.xml @@ -1,11 +1,9 @@ + 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.rulebook rulebook 1.0 - rulebook @@ -18,7 +16,12 @@ com.deliveredtechnologies rulebook-core - 0.6.2 + ${rulebook.version} + + + 0.6.2 + + \ No newline at end of file diff --git a/rule-engines/rulebook/src/main/resources/logback.xml b/rule-engines/rulebook/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/rule-engines/rulebook/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/rxjava-2/README.md b/rxjava-2/README.md new file mode 100644 index 0000000000..ccf575757f --- /dev/null +++ b/rxjava-2/README.md @@ -0,0 +1,6 @@ +## Relevant articles: + +- [RxJava and Error Handling](http://www.baeldung.com/rxjava-error-handling) +- [RxJava 2 – Flowable](http://www.baeldung.com/rxjava-2-flowable) +- [RxJava Maybe](http://www.baeldung.com/rxjava-maybe) +- [Introduction to RxRelay for RxJava](http://www.baeldung.com/rx-relay) \ No newline at end of file diff --git a/rxjava-2/pom.xml b/rxjava-2/pom.xml new file mode 100644 index 0000000000..4c5ea014d7 --- /dev/null +++ b/rxjava-2/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + + rxjava-2 + 1.0-SNAPSHOT + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + io.reactivex.rxjava2 + rxjava + ${rx.java2.version} + + + com.jayway.awaitility + awaitility + ${awaitility.version} + + + org.assertj + assertj-core + ${assertj.version} + + + com.jakewharton.rxrelay2 + rxrelay + ${rxrelay.version} + + + + + 3.8.0 + 2.1.3 + 1.7.0 + 2.0.0 + + + \ No newline at end of file diff --git a/rxjava/src/main/java/com/baeldung/rxjava/RandomRelay.java b/rxjava-2/src/main/java/com/baeldung/rxjava/RandomRelay.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/RandomRelay.java rename to rxjava-2/src/main/java/com/baeldung/rxjava/RandomRelay.java diff --git a/rxjava-2/src/main/resources/logback.xml b/rxjava-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/rxjava-2/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java new file mode 100644 index 0000000000..9fee2bc005 --- /dev/null +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java @@ -0,0 +1,93 @@ +package com.baeldung.rxjava; + +import io.reactivex.BackpressureStrategy; +import io.reactivex.Flowable; +import io.reactivex.FlowableOnSubscribe; +import io.reactivex.Observable; +import io.reactivex.exceptions.MissingBackpressureException; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.subscribers.TestSubscriber; + +import org.junit.Test; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class FlowableIntegrationTest { + + @Test public void whenFlowableIsCreated_thenItIsProperlyInitialized() { + Flowable integerFlowable = Flowable.just(1, 2, 3, 4); + assertNotNull(integerFlowable); + } + + @Test public void whenFlowableIsCreatedFromObservable_thenItIsProperlyInitialized() throws InterruptedException { + Observable integerObservable = Observable.just(1, 2, 3); + Flowable integerFlowable = integerObservable.toFlowable(BackpressureStrategy.BUFFER); + assertNotNull(integerFlowable); + + } + + @Test public void whenFlowableIsCreatedFromFlowableOnSubscribe_thenItIsProperlyInitialized() throws InterruptedException { + FlowableOnSubscribe flowableOnSubscribe = flowableEmitter -> flowableEmitter.onNext(1); + Flowable integerFlowable = Flowable.create(flowableOnSubscribe, BackpressureStrategy.BUFFER); + assertNotNull(integerFlowable); + } + + @Test public void thenAllValuesAreBufferedAndReceived() { + List testList = IntStream.range(0, 100000).boxed().collect(Collectors.toList()); + Observable observable = Observable.fromIterable(testList); + TestSubscriber testSubscriber = observable.toFlowable(BackpressureStrategy.BUFFER).observeOn(Schedulers.computation()).test(); + + testSubscriber.awaitTerminalEvent(); + + List receivedInts = testSubscriber.getEvents().get(0).stream().mapToInt(object -> (int) object).boxed().collect(Collectors.toList()); + + assertEquals(testList, receivedInts); + } + + @Test public void whenDropStrategyUsed_thenOnBackpressureDropped() { + List testList = IntStream.range(0, 100000).boxed().collect(Collectors.toList()); + + Observable observable = Observable.fromIterable(testList); + TestSubscriber testSubscriber = observable.toFlowable(BackpressureStrategy.DROP).observeOn(Schedulers.computation()).test(); + testSubscriber.awaitTerminalEvent(); + List receivedInts = testSubscriber.getEvents().get(0).stream().mapToInt(object -> (int) object).boxed().collect(Collectors.toList()); + + assertThat(receivedInts.size() < testList.size()); + assertThat(!receivedInts.contains(100000)); + } + + @Test public void whenMissingStrategyUsed_thenException() { + Observable observable = Observable.range(1, 100000); + TestSubscriber subscriber = observable.toFlowable(BackpressureStrategy.MISSING).observeOn(Schedulers.computation()).test(); + + subscriber.awaitTerminalEvent(); + subscriber.assertError(MissingBackpressureException.class); + } + + @Test public void whenErrorStrategyUsed_thenExceptionIsThrown() { + Observable observable = Observable.range(1, 100000); + TestSubscriber subscriber = observable.toFlowable(BackpressureStrategy.ERROR).observeOn(Schedulers.computation()).test(); + + subscriber.awaitTerminalEvent(); + subscriber.assertError(MissingBackpressureException.class); + } + + @Test public void whenLatestStrategyUsed_thenTheLastElementReceived() { + List testList = IntStream.range(0, 100000).boxed().collect(Collectors.toList()); + Observable observable = Observable.fromIterable(testList); + TestSubscriber testSubscriber = observable.toFlowable(BackpressureStrategy.LATEST).observeOn(Schedulers.computation()).test(); + + testSubscriber.awaitTerminalEvent(); + List receivedInts = testSubscriber.getEvents().get(0).stream().mapToInt(object -> (int) object).boxed().collect(Collectors.toList()); + + assertThat(receivedInts.size() < testList.size()); + assertThat(receivedInts.contains(100000)); + } + +} \ No newline at end of file diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java new file mode 100644 index 0000000000..d02fe990c0 --- /dev/null +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.rxjava; + +import org.junit.Test; + +import io.reactivex.Flowable; +import io.reactivex.Maybe; + +public class MaybeUnitTest { + @Test + public void whenEmitsSingleValue_thenItIsObserved() { + Maybe maybe = Flowable.just(1, 2, 3, 4, 5) + .firstElement(); + + maybe.map(x -> x + 7) + .filter(x -> x > 0) + .test() + .assertResult(8) + .assertComplete(); + } + + @Test + public void whenEmitsNoValue_thenSignalsCompletionAndNoValueObserved() { + Maybe maybe = Flowable.just(1, 2, 3, 4, 5) + .skip(5) + .firstElement(); + + maybe.test() + .assertComplete() + .assertNoValues(); + } + + @Test + public void whenThrowsError_thenErrorIsRaised() { + Maybe maybe = Flowable. error(new Exception("msg")) + .firstElement(); + + maybe.test() + .assertErrorMessage("msg"); + } +} diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java new file mode 100644 index 0000000000..9fc5827d86 --- /dev/null +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java @@ -0,0 +1,120 @@ +package com.baeldung.rxjava; + +import com.jakewharton.rxrelay2.BehaviorRelay; +import com.jakewharton.rxrelay2.PublishRelay; +import com.jakewharton.rxrelay2.ReplayRelay; +import io.reactivex.internal.schedulers.SingleScheduler; +import io.reactivex.observers.TestObserver; +import org.junit.Test; + +import java.util.concurrent.TimeUnit; + +public class RxRelayIntegrationTest { + + @Test + public void whenObserverSubscribedToPublishRelay_thenItReceivesEmittedEvents () { + PublishRelay publishRelay = PublishRelay.create(); + TestObserver firstObserver = TestObserver.create(); + TestObserver secondObserver = TestObserver.create(); + publishRelay.subscribe(firstObserver); + firstObserver.assertSubscribed(); + publishRelay.accept(5); + publishRelay.accept(10); + publishRelay.subscribe(secondObserver); + secondObserver.assertSubscribed(); + publishRelay.accept(15); + //First Observer will receive all events + firstObserver.assertValues(5, 10, 15); + //Second Observer will receive only last event + secondObserver.assertValue(15); + } + + @Test + public void whenObserverSubscribedToBehaviorRelayWithoutDefaultValue_thenItIsEmpty() { + BehaviorRelay behaviorRelay = BehaviorRelay.create(); + TestObserver firstObserver = new TestObserver<>(); + behaviorRelay.subscribe(firstObserver); + firstObserver.assertEmpty(); + } + + @Test + public void whenObserverSubscribedToBehaviorRelay_thenItReceivesDefaultValue() { + BehaviorRelay behaviorRelay = BehaviorRelay.createDefault(1); + TestObserver firstObserver = new TestObserver<>(); + behaviorRelay.subscribe(firstObserver); + firstObserver.assertValue(1); + } + + @Test + public void whenObserverSubscribedToBehaviorRelay_thenItReceivesEmittedEvents () { + BehaviorRelay behaviorRelay = BehaviorRelay.create(); + TestObserver firstObserver = TestObserver.create(); + TestObserver secondObserver = TestObserver.create(); + behaviorRelay.accept(5); + behaviorRelay.subscribe(firstObserver); + behaviorRelay.accept(10); + behaviorRelay.subscribe(secondObserver); + behaviorRelay.accept(15); + firstObserver.assertValues(5, 10, 15); + secondObserver.assertValues(10, 15); + } + @Test + public void whenObserverSubscribedToReplayRelay_thenItReceivesEmittedEvents () { + ReplayRelay replayRelay = ReplayRelay.create(); + TestObserver firstObserver = TestObserver.create(); + TestObserver secondObserver = TestObserver.create(); + replayRelay.subscribe(firstObserver); + replayRelay.accept(5); + replayRelay.accept(10); + replayRelay.accept(15); + replayRelay.subscribe(secondObserver); + firstObserver.assertValues(5, 10, 15); + secondObserver.assertValues(5, 10, 15); + + } + + @Test + public void whenObserverSubscribedToReplayRelayWithLimitedSize_thenItReceivesEmittedEvents () { + ReplayRelay replayRelay = ReplayRelay.createWithSize(2); + TestObserver firstObserver = TestObserver.create(); + replayRelay.accept(5); + replayRelay.accept(10); + replayRelay.accept(15); + replayRelay.accept(20); + replayRelay.subscribe(firstObserver); + + firstObserver.assertValues(15, 20); + + } + + + @Test + public void whenObserverSubscribedToReplayRelayWithMaxAge_thenItReceivesEmittedEvents () throws InterruptedException { + ReplayRelay replayRelay = ReplayRelay.createWithTime(2000, TimeUnit.MILLISECONDS, new SingleScheduler()); + TestObserver firstObserver = TestObserver.create(); + replayRelay.accept(5); + replayRelay.accept(10); + replayRelay.accept(15); + replayRelay.accept(20); + Thread.sleep(3000); + replayRelay.subscribe(firstObserver); + firstObserver.assertEmpty(); + } + + @Test + public void whenTwoObserversSubscribedToRandomRelay_thenOnlyOneReceivesEvent () { + RandomRelay randomRelay = new RandomRelay(); + TestObserver firstObserver = TestObserver.create(); + TestObserver secondObserver = TestObserver.create(); + randomRelay.subscribe(firstObserver); + randomRelay.subscribe(secondObserver); + randomRelay.accept(5); + if(firstObserver.values().isEmpty()) { + secondObserver.assertValue(5); + } else { + firstObserver.assertValue(5); + secondObserver.assertEmpty(); + } + } +} + diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java new file mode 100644 index 0000000000..304dc98274 --- /dev/null +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java @@ -0,0 +1,138 @@ +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; + +public class ExceptionHandlingIntegrationTest { + + 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-2/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java new file mode 100644 index 0000000000..746e3cfbf6 --- /dev/null +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java @@ -0,0 +1,146 @@ +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; + +public class OnErrorRetryIntegrationTest { + + 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/rxjava-2/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java new file mode 100644 index 0000000000..ade48a2cb9 --- /dev/null +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java @@ -0,0 +1,65 @@ +package com.baeldung.rxjava.operators; + +import io.reactivex.Observable; +import io.reactivex.schedulers.TestScheduler; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static org.hamcrest.CoreMatchers.hasItems; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +public class RxFlatmapAndSwitchmapUnitTest { + @Test + public void givenObservable_whenFlatmap_shouldAssertAllItemsReturned() { + //given + List actualOutput = new ArrayList<>(); + final TestScheduler scheduler = new TestScheduler(); + final List keywordToSearch = Arrays.asList("b", "bo", "boo", "book", "books"); + + //when + Observable.fromIterable(keywordToSearch) + .flatMap(s -> Observable + .just(s + " FirstResult", s + " SecondResult") + .delay(10, TimeUnit.SECONDS, scheduler)) + .toList() + .doOnSuccess(s -> actualOutput.addAll(s)) + .subscribe(); + + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + + //then + assertThat(actualOutput, hasItems("b FirstResult", "b SecondResult", + "boo FirstResult", "boo SecondResult", + "bo FirstResult", "bo SecondResult", + "book FirstResult", "book SecondResult", + "books FirstResult", "books SecondResult")); + } + + @Test + public void givenObservable_whenSwitchmap_shouldAssertLatestItemReturned() { + //given + List actualOutput = new ArrayList<>(); + final TestScheduler scheduler = new TestScheduler(); + final List keywordToSearch = Arrays.asList("b", "bo", "boo", "book", "books"); + + //when + Observable.fromIterable(keywordToSearch) + .switchMap(s -> Observable + .just(s + " FirstResult", s + " SecondResult") + .delay(10, TimeUnit.SECONDS, scheduler)) + .toList() + .doOnSuccess(s -> actualOutput.addAll(s)) + .subscribe(); + + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + + //then + assertEquals(2, actualOutput.size()); + assertThat(actualOutput, hasItems("books FirstResult", "books SecondResult")); + } +} diff --git a/rxjava/README.md b/rxjava/README.md index 3376c49426..f8a4ca1dbe 100644 --- a/rxjava/README.md +++ b/rxjava/README.md @@ -4,14 +4,12 @@ - [How to Test RxJava?](http://www.baeldung.com/rxjava-testing) - [Implementing Custom Operators in RxJava](http://www.baeldung.com/rxjava-custom-operators) - [Introduction to RxJava](http://www.baeldung.com/rx-java) -- [RxJava and Error Handling](http://www.baeldung.com/rxjava-error-handling) - [Observable Utility Operators in RxJava](http://www.baeldung.com/rxjava-observable-operators) - [Introduction to rxjava-jdbc](http://www.baeldung.com/rxjava-jdbc) - [Schedulers in RxJava](http://www.baeldung.com/rxjava-schedulers) - [Mathematical and Aggregate Operators in RxJava](http://www.baeldung.com/rxjava-math) - [Combining Observables in RxJava](http://www.baeldung.com/rxjava-combine-observables) -- [RxJava 2 – Flowable](http://www.baeldung.com/rxjava-2-flowable) - [RxJava StringObservable](http://www.baeldung.com/rxjava-string) -- [RxJava Maybe](http://www.baeldung.com/rxjava-maybe) -- [Introduction to RxRelay for RxJava](http://www.baeldung.com/rx-relay) - [Filtering Observables in RxJava](http://www.baeldung.com/rxjava-filtering) +- [RxJava One Observable, Multiple Subscribers](http://www.baeldung.com/rxjava-multiple-subscribers-observable) +- [Difference Between Flatmap and Switchmap in RxJava](https://www.baeldung.com/rxjava-flatmap-switchmap) diff --git a/rxjava/pom.xml b/rxjava/pom.xml index 72d2859330..b316001d87 100644 --- a/rxjava/pom.xml +++ b/rxjava/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 rxjava @@ -9,8 +9,8 @@ com.baeldung parent-java - 0.0.1-SNAPSHOT - ../parent-java + 0.0.1-SNAPSHOT + ../parent-java @@ -20,35 +20,22 @@ ${rx.java.version} - - io.reactivex.rxjava2 - rxjava - 2.1.3 - - io.reactivex rxjava-math - 1.0.0 + ${rx.java.math.version} io.reactivex rxjava-string - 1.1.1 - - - - junit - junit - 4.12 - test + ${rx.java.string.version} com.jayway.awaitility awaitility - 1.7.0 + ${awaitility.version} com.github.davidmoten @@ -66,19 +53,16 @@ assertj-core ${assertj.version} - - com.jakewharton.rxrelay2 - rxrelay - 2.0.0 - 3.8.0 1.2.5 0.7.11 + 1.0.0 + 1.1.1 + 1.7.0 1.4.196 - \ No newline at end of file diff --git a/rxjava/src/main/java/com/baeldung/rxjava/MultipleSubscribersColdObs.java b/rxjava/src/main/java/com/baeldung/rxjava/MultipleSubscribersColdObs.java new file mode 100644 index 0000000000..1d3e1b3f8a --- /dev/null +++ b/rxjava/src/main/java/com/baeldung/rxjava/MultipleSubscribersColdObs.java @@ -0,0 +1,59 @@ +package com.baeldung.rxjava; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import rx.Observable; +import rx.Subscription; +import rx.observables.ConnectableObservable; +import rx.subscriptions.Subscriptions; + +public class MultipleSubscribersColdObs { + private static final Logger LOGGER = LoggerFactory.getLogger(MultipleSubscribersColdObs.class); + + public static void main(String[] args) throws InterruptedException { + defaultBehaviour(); + // subscribeBeforeConnect(); + + } + + private static void defaultBehaviour() { + Observable obs = getObservable(); + + LOGGER.info("Subscribing"); + Subscription s1 = obs.subscribe(i -> LOGGER.info("subscriber#1 is printing " + i)); + Subscription s2 = obs.subscribe(i -> LOGGER.info("subscriber#2 is printing " + i)); + + s1.unsubscribe(); + s2.unsubscribe(); + } + + private static void subscribeBeforeConnect() throws InterruptedException { + ConnectableObservable obs = getObservable().publish(); + + LOGGER.info("Subscribing"); + obs.subscribe(i -> LOGGER.info("subscriber #1 is printing " + i)); + obs.subscribe(i -> LOGGER.info("subscriber #2 is printing " + i)); + Thread.sleep(1000); + LOGGER.info("Connecting"); + Subscription s = obs.connect(); + s.unsubscribe(); + + } + + private static Observable getObservable() { + return Observable.create(subscriber -> { + subscriber.onNext(gettingValue(1)); + subscriber.onNext(gettingValue(2)); + + subscriber.add(Subscriptions.create(() -> { + LOGGER.info("Clear resources"); + })); + }); + } + + private static Integer gettingValue(int i) { + LOGGER.info("Getting " + i); + return i; + } +} diff --git a/rxjava/src/main/java/com/baeldung/rxjava/MultipleSubscribersHotObs.java b/rxjava/src/main/java/com/baeldung/rxjava/MultipleSubscribersHotObs.java new file mode 100644 index 0000000000..686c230003 --- /dev/null +++ b/rxjava/src/main/java/com/baeldung/rxjava/MultipleSubscribersHotObs.java @@ -0,0 +1,152 @@ +package com.baeldung.rxjava; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.lang.reflect.InvocationTargetException; + +import javax.swing.JFrame; +import rx.Observable; +import rx.Subscription; +import rx.observables.ConnectableObservable; +import rx.subscriptions.Subscriptions; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MultipleSubscribersHotObs { + private static final Logger LOGGER = LoggerFactory.getLogger(MultipleSubscribersHotObs.class); + private static JFrame frame; + + public static void main(String[] args) throws InterruptedException, InvocationTargetException { + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + createAndShowGUI(); + } + }); + + defaultBehaviour(); + // subscribeBeforeConnect(); + // connectBeforeSubscribe(); + // autoConnectAndSubscribe(); + // refCountAndSubscribe(); + } + + private static void createAndShowGUI() { + frame = new JFrame("Hot Observable Demo"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.getContentPane().setBackground(Color.GRAY); + frame.setPreferredSize(new Dimension(500, 500)); + frame.pack(); + frame.setVisible(true); + } + + public static void defaultBehaviour() throws InterruptedException { + Observable obs = getObservable(); + + LOGGER.info("subscribing #1"); + Subscription subscription1 = obs.subscribe((i) -> LOGGER.info("subscriber#1 is printing x-coordinate " + i)); + + Thread.sleep(1000); + LOGGER.info("subscribing #2"); + Subscription subscription2 = obs.subscribe((i) -> LOGGER.info("subscriber#2 is printing x-coordinate " + i)); + Thread.sleep(1000); + LOGGER.info("unsubscribe#1"); + subscription1.unsubscribe(); + Thread.sleep(1000); + LOGGER.info("unsubscribe#2"); + subscription2.unsubscribe(); + } + + public static void subscribeBeforeConnect() throws InterruptedException { + + ConnectableObservable obs = getObservable().publish(); + + LOGGER.info("subscribing #1"); + Subscription subscription1 = obs.subscribe((i) -> LOGGER.info("subscriber#1 is printing x-coordinate " + i)); + Thread.sleep(1000); + LOGGER.info("subscribing #2"); + Subscription subscription2 = obs.subscribe((i) -> LOGGER.info("subscriber#2 is printing x-coordinate " + i)); + Thread.sleep(1000); + LOGGER.info("connecting:"); + Subscription s = obs.connect(); + Thread.sleep(1000); + LOGGER.info("unsubscribe connected"); + s.unsubscribe(); + + } + + public static void connectBeforeSubscribe() throws InterruptedException { + + ConnectableObservable obs = getObservable().doOnNext(x -> LOGGER.info("saving " + x)).publish(); + LOGGER.info("connecting:"); + Subscription s = obs.connect(); + Thread.sleep(1000); + LOGGER.info("subscribing #1"); + obs.subscribe((i) -> LOGGER.info("subscriber#1 is printing x-coordinate " + i)); + Thread.sleep(1000); + LOGGER.info("subscribing #2"); + obs.subscribe((i) -> LOGGER.info("subscriber#2 is printing x-coordinate " + i)); + Thread.sleep(1000); + s.unsubscribe(); + + } + + public static void autoConnectAndSubscribe() throws InterruptedException { + Observable obs = getObservable().doOnNext(x -> LOGGER.info("saving " + x)).publish().autoConnect(); + + LOGGER.info("autoconnect()"); + Thread.sleep(1000); + LOGGER.info("subscribing #1"); + Subscription s1 = obs.subscribe((i) -> LOGGER.info("subscriber#1 is printing x-coordinate " + i)); + Thread.sleep(1000); + LOGGER.info("subscribing #2"); + Subscription s2 = obs.subscribe((i) -> LOGGER.info("subscriber#2 is printing x-coordinate " + i)); + + Thread.sleep(1000); + LOGGER.info("unsubscribe 1"); + s1.unsubscribe(); + Thread.sleep(1000); + LOGGER.info("unsubscribe 2"); + s2.unsubscribe(); + } + + public static void refCountAndSubscribe() throws InterruptedException { + Observable obs = getObservable().doOnNext(x -> LOGGER.info("saving " + x)).publish().refCount(); + + LOGGER.info("refcount()"); + Thread.sleep(1000); + LOGGER.info("subscribing #1"); + Subscription subscription1 = obs.subscribe((i) -> LOGGER.info("subscriber#1 is printing x-coordinate " + i)); + Thread.sleep(1000); + LOGGER.info("subscribing #2"); + Subscription subscription2 = obs.subscribe((i) -> LOGGER.info("subscriber#2 is printing x-coordinate " + i)); + + Thread.sleep(1000); + LOGGER.info("unsubscribe#1"); + subscription1.unsubscribe(); + Thread.sleep(1000); + LOGGER.info("unsubscribe#2"); + subscription2.unsubscribe(); + + } + + private static Observable getObservable() { + return Observable.create(subscriber -> { + frame.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + subscriber.onNext(e.getX()); + } + }); + subscriber.add(Subscriptions.create(() -> { + LOGGER.info("Clear resources"); + for (MouseListener listener : frame.getListeners(MouseListener.class)) { + frame.removeMouseListener(listener); + } + })); + }); + } +} diff --git a/rxjava/src/main/resources/logback.xml b/rxjava/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/rxjava/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableIntegrationTest.java new file mode 100644 index 0000000000..5c28c53d11 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableIntegrationTest.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 ConnectableObservableIntegrationTest { + + @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/ConnectableObservableTest.java b/rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableTest.java deleted file mode 100644 index 031ff0c5bb..0000000000 --- a/rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableTest.java +++ /dev/null @@ -1,27 +0,0 @@ -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/FlowableTest.java b/rxjava/src/test/java/com/baeldung/rxjava/FlowableTest.java deleted file mode 100644 index b9d1d64c24..0000000000 --- a/rxjava/src/test/java/com/baeldung/rxjava/FlowableTest.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.baeldung.rxjava; - -import io.reactivex.BackpressureStrategy; -import io.reactivex.Flowable; -import io.reactivex.FlowableOnSubscribe; -import io.reactivex.Observable; -import io.reactivex.exceptions.MissingBackpressureException; -import io.reactivex.schedulers.Schedulers; -import io.reactivex.subscribers.TestSubscriber; - -import org.junit.Test; - -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class FlowableTest { - - @Test public void whenFlowableIsCreated_thenItIsProperlyInitialized() { - Flowable integerFlowable = Flowable.just(1, 2, 3, 4); - assertNotNull(integerFlowable); - } - - @Test public void whenFlowableIsCreatedFromObservable_thenItIsProperlyInitialized() throws InterruptedException { - Observable integerObservable = Observable.just(1, 2, 3); - Flowable integerFlowable = integerObservable.toFlowable(BackpressureStrategy.BUFFER); - assertNotNull(integerFlowable); - - } - - @Test public void whenFlowableIsCreatedFromFlowableOnSubscribe_thenItIsProperlyInitialized() throws InterruptedException { - FlowableOnSubscribe flowableOnSubscribe = flowableEmitter -> flowableEmitter.onNext(1); - Flowable integerFlowable = Flowable.create(flowableOnSubscribe, BackpressureStrategy.BUFFER); - assertNotNull(integerFlowable); - } - - @Test public void thenAllValuesAreBufferedAndReceived() { - List testList = IntStream.range(0, 100000).boxed().collect(Collectors.toList()); - Observable observable = Observable.fromIterable(testList); - TestSubscriber testSubscriber = observable.toFlowable(BackpressureStrategy.BUFFER).observeOn(Schedulers.computation()).test(); - - testSubscriber.awaitTerminalEvent(); - - List receivedInts = testSubscriber.getEvents().get(0).stream().mapToInt(object -> (int) object).boxed().collect(Collectors.toList()); - - assertEquals(testList, receivedInts); - } - - @Test public void whenDropStrategyUsed_thenOnBackpressureDropped() { - List testList = IntStream.range(0, 100000).boxed().collect(Collectors.toList()); - - Observable observable = Observable.fromIterable(testList); - TestSubscriber testSubscriber = observable.toFlowable(BackpressureStrategy.DROP).observeOn(Schedulers.computation()).test(); - testSubscriber.awaitTerminalEvent(); - List receivedInts = testSubscriber.getEvents().get(0).stream().mapToInt(object -> (int) object).boxed().collect(Collectors.toList()); - - assertThat(receivedInts.size() < testList.size()); - assertThat(!receivedInts.contains(100000)); - } - - @Test public void whenMissingStrategyUsed_thenException() { - Observable observable = Observable.range(1, 100000); - TestSubscriber subscriber = observable.toFlowable(BackpressureStrategy.MISSING).observeOn(Schedulers.computation()).test(); - - subscriber.awaitTerminalEvent(); - subscriber.assertError(MissingBackpressureException.class); - } - - @Test public void whenErrorStrategyUsed_thenExceptionIsThrown() { - Observable observable = Observable.range(1, 100000); - TestSubscriber subscriber = observable.toFlowable(BackpressureStrategy.ERROR).observeOn(Schedulers.computation()).test(); - - subscriber.awaitTerminalEvent(); - subscriber.assertError(MissingBackpressureException.class); - } - - @Test public void whenLatestStrategyUsed_thenTheLastElementReceived() { - List testList = IntStream.range(0, 100000).boxed().collect(Collectors.toList()); - Observable observable = Observable.fromIterable(testList); - TestSubscriber testSubscriber = observable.toFlowable(BackpressureStrategy.LATEST).observeOn(Schedulers.computation()).test(); - - testSubscriber.awaitTerminalEvent(); - List receivedInts = testSubscriber.getEvents().get(0).stream().mapToInt(object -> (int) object).boxed().collect(Collectors.toList()); - - assertThat(receivedInts.size() < testList.size()); - assertThat(receivedInts.contains(100000)); - } - -} \ No newline at end of file diff --git a/rxjava/src/test/java/com/baeldung/rxjava/MaybeTest.java b/rxjava/src/test/java/com/baeldung/rxjava/MaybeTest.java deleted file mode 100644 index 501ee1f196..0000000000 --- a/rxjava/src/test/java/com/baeldung/rxjava/MaybeTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.rxjava; - -import org.junit.Test; - -import io.reactivex.Flowable; -import io.reactivex.Maybe; - -public class MaybeTest { - @Test - public void whenEmitsSingleValue_thenItIsObserved() { - Maybe maybe = Flowable.just(1, 2, 3, 4, 5) - .firstElement(); - - maybe.map(x -> x + 7) - .filter(x -> x > 0) - .test() - .assertResult(8) - .assertComplete(); - } - - @Test - public void whenEmitsNoValue_thenSignalsCompletionAndNoValueObserved() { - Maybe maybe = Flowable.just(1, 2, 3, 4, 5) - .skip(5) - .firstElement(); - - maybe.test() - .assertComplete() - .assertNoValues(); - } - - @Test - public void whenThrowsError_thenErrorIsRaised() { - Maybe maybe = Flowable. error(new Exception("msg")) - .firstElement(); - - maybe.test() - .assertErrorMessage("msg"); - } -} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/ObservableTest.java b/rxjava/src/test/java/com/baeldung/rxjava/ObservableTest.java deleted file mode 100644 index beb2cbeed3..0000000000 --- a/rxjava/src/test/java/com/baeldung/rxjava/ObservableTest.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.baeldung.rxjava; - -import org.junit.Test; -import rx.Observable; - -import static com.baeldung.rxjava.ObservableImpl.getTitle; -import static junit.framework.Assert.assertTrue; - -public class ObservableTest { - - private 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().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/ObservableUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/ObservableUnitTest.java new file mode 100644 index 0000000000..22e52f73c4 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/ObservableUnitTest.java @@ -0,0 +1,144 @@ +package com.baeldung.rxjava; + +import org.junit.Test; +import rx.Observable; + +import static com.baeldung.rxjava.ObservableImpl.getTitle; +import static junit.framework.Assert.assertTrue; + +public class ObservableUnitTest { + + private 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().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 deleted file mode 100644 index 81be84fd0d..0000000000 --- a/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementTest.java +++ /dev/null @@ -1,30 +0,0 @@ -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( - () -> "MyResource", - r -> 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/ResourceManagementUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementUnitTest.java new file mode 100644 index 0000000000..145194d374 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.rxjava; + +import org.junit.Test; +import rx.Observable; + +import static junit.framework.Assert.assertTrue; + +public class ResourceManagementUnitTest { + + @Test + public void givenResource_whenUsingOberservable_thenCreatePrintDisposeResource() throws InterruptedException { + + String[] result = {""}; + Observable values = Observable.using( + () -> "MyResource", + r -> 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/RxRelayTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxRelayTest.java deleted file mode 100644 index 091e4df138..0000000000 --- a/rxjava/src/test/java/com/baeldung/rxjava/RxRelayTest.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.baeldung.rxjava; - -import com.jakewharton.rxrelay2.BehaviorRelay; -import com.jakewharton.rxrelay2.PublishRelay; -import com.jakewharton.rxrelay2.ReplayRelay; -import io.reactivex.internal.schedulers.SingleScheduler; -import io.reactivex.observers.TestObserver; -import org.junit.Test; - -import java.util.concurrent.TimeUnit; - -public class RxRelayTest { - - @Test - public void whenObserverSubscribedToPublishRelay_thenItReceivesEmittedEvents () { - PublishRelay publishRelay = PublishRelay.create(); - TestObserver firstObserver = TestObserver.create(); - TestObserver secondObserver = TestObserver.create(); - publishRelay.subscribe(firstObserver); - firstObserver.assertSubscribed(); - publishRelay.accept(5); - publishRelay.accept(10); - publishRelay.subscribe(secondObserver); - secondObserver.assertSubscribed(); - publishRelay.accept(15); - //First Observer will receive all events - firstObserver.assertValues(5, 10, 15); - //Second Observer will receive only last event - secondObserver.assertValue(15); - } - - @Test - public void whenObserverSubscribedToBehaviorRelayWithoutDefaultValue_thenItIsEmpty() { - BehaviorRelay behaviorRelay = BehaviorRelay.create(); - TestObserver firstObserver = new TestObserver<>(); - behaviorRelay.subscribe(firstObserver); - firstObserver.assertEmpty(); - } - - @Test - public void whenObserverSubscribedToBehaviorRelay_thenItReceivesDefaultValue() { - BehaviorRelay behaviorRelay = BehaviorRelay.createDefault(1); - TestObserver firstObserver = new TestObserver<>(); - behaviorRelay.subscribe(firstObserver); - firstObserver.assertValue(1); - } - - @Test - public void whenObserverSubscribedToBehaviorRelay_thenItReceivesEmittedEvents () { - BehaviorRelay behaviorRelay = BehaviorRelay.create(); - TestObserver firstObserver = TestObserver.create(); - TestObserver secondObserver = TestObserver.create(); - behaviorRelay.accept(5); - behaviorRelay.subscribe(firstObserver); - behaviorRelay.accept(10); - behaviorRelay.subscribe(secondObserver); - behaviorRelay.accept(15); - firstObserver.assertValues(5, 10, 15); - secondObserver.assertValues(10, 15); - } - @Test - public void whenObserverSubscribedToReplayRelay_thenItReceivesEmittedEvents () { - ReplayRelay replayRelay = ReplayRelay.create(); - TestObserver firstObserver = TestObserver.create(); - TestObserver secondObserver = TestObserver.create(); - replayRelay.subscribe(firstObserver); - replayRelay.accept(5); - replayRelay.accept(10); - replayRelay.accept(15); - replayRelay.subscribe(secondObserver); - firstObserver.assertValues(5, 10, 15); - secondObserver.assertValues(5, 10, 15); - - } - - @Test - public void whenObserverSubscribedToReplayRelayWithLimitedSize_thenItReceivesEmittedEvents () { - ReplayRelay replayRelay = ReplayRelay.createWithSize(2); - TestObserver firstObserver = TestObserver.create(); - replayRelay.accept(5); - replayRelay.accept(10); - replayRelay.accept(15); - replayRelay.accept(20); - replayRelay.subscribe(firstObserver); - - firstObserver.assertValues(15, 20); - - } - - - @Test - public void whenObserverSubscribedToReplayRelayWithMaxAge_thenItReceivesEmittedEvents () throws InterruptedException { - ReplayRelay replayRelay = ReplayRelay.createWithTime(2000, TimeUnit.MILLISECONDS, new SingleScheduler()); - TestObserver firstObserver = TestObserver.create(); - replayRelay.accept(5); - replayRelay.accept(10); - replayRelay.accept(15); - replayRelay.accept(20); - Thread.sleep(3000); - replayRelay.subscribe(firstObserver); - firstObserver.assertEmpty(); - } - - @Test - public void whenTwoObserversSubscribedToRandomRelay_thenOnlyOneReceivesEvent () { - RandomRelay randomRelay = new RandomRelay(); - TestObserver firstObserver = TestObserver.create(); - TestObserver secondObserver = TestObserver.create(); - randomRelay.subscribe(firstObserver); - randomRelay.subscribe(secondObserver); - randomRelay.accept(5); - if(firstObserver.values().isEmpty()) { - secondObserver.assertValue(5); - } else { - firstObserver.assertValue(5); - secondObserver.assertEmpty(); - } - } -} - diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SingleTest.java b/rxjava/src/test/java/com/baeldung/rxjava/SingleTest.java deleted file mode 100644 index 1352841ed9..0000000000 --- a/rxjava/src/test/java/com/baeldung/rxjava/SingleTest.java +++ /dev/null @@ -1,23 +0,0 @@ -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/SingleUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/SingleUnitTest.java new file mode 100644 index 0000000000..8c39034cb9 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/SingleUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.rxjava; + +import org.junit.Test; +import rx.Observable; +import rx.Single; + +import static junit.framework.Assert.assertTrue; + +public class SingleUnitTest { + + @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 deleted file mode 100644 index 628b1e5476..0000000000 --- a/rxjava/src/test/java/com/baeldung/rxjava/SubjectTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.rxjava; - -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/SubjectUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/SubjectUnitTest.java new file mode 100644 index 0000000000..a678d83667 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/SubjectUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.rxjava; + +import org.junit.Test; +import rx.subjects.PublishSubject; + +import static junit.framework.Assert.assertTrue; + +public class SubjectUnitTest { + + @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/UtilityOperatorsIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsIntegrationTest.java new file mode 100644 index 0000000000..a11d0ff8c3 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsIntegrationTest.java @@ -0,0 +1,270 @@ +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 rx.schedulers.Timestamped; + +import java.util.concurrent.TimeUnit; + +import static com.jayway.awaitility.Awaitility.await; +import static org.junit.Assert.assertTrue; + +public class UtilityOperatorsIntegrationTest { + + private int emittedTotal = 0; + private int receivedTotal = 0; + private 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()); + }); + + await().until(() -> { + 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()); + }); + + await().until(() -> { + 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()); + }); + + await().until(() -> { + 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 -> 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/UtilityOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java deleted file mode 100644 index 0b38f0387b..0000000000 --- a/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java +++ /dev/null @@ -1,270 +0,0 @@ -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 rx.schedulers.Timestamped; - -import java.util.concurrent.TimeUnit; - -import static com.jayway.awaitility.Awaitility.await; -import static org.junit.Assert.assertTrue; - -public class UtilityOperatorsTest { - - private int emittedTotal = 0; - private int receivedTotal = 0; - private 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()); - }); - - await().until(() -> { - 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()); - }); - - await().until(() -> { - 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()); - }); - - await().until(() -> { - 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 -> 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/filters/RxJavaFilterOperatorsIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsIntegrationTest.java new file mode 100644 index 0000000000..67f4c51cbe --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsIntegrationTest.java @@ -0,0 +1,202 @@ +package com.baeldung.rxjava.filters; + +import org.junit.Test; + +import rx.Observable; +import rx.observers.TestSubscriber; + +public class RxJavaFilterOperatorsIntegrationTest { + + @Test + public void givenRangeObservable_whenFilteringItems_thenOddItemsAreFiltered() { + + Observable sourceObservable = Observable.range(1, 10); + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = sourceObservable.filter(i -> i % 2 != 0); + + filteredObservable.subscribe(subscriber); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(5); + subscriber.assertValues(1, 3, 5, 7, 9); + } + + @Test + public void givenRangeObservable_whenFilteringWithTake_thenOnlyFirstThreeItemsAreEmitted() { + + Observable sourceObservable = Observable.range(1, 10); + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = sourceObservable.take(3); + + filteredObservable.subscribe(subscriber); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(3); + subscriber.assertValues(1, 2, 3); + } + + @Test + public void givenObservable_whenFilteringWithTakeWhile_thenItemsEmittedUntilConditionIsVerified() { + + Observable sourceObservable = Observable.just(1, 2, 3, 4, 3, 2, 1); + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = sourceObservable.takeWhile(i -> i < 4); + + filteredObservable.subscribe(subscriber); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(3); + subscriber.assertValues(1, 2, 3); + } + + @Test + public void givenRangeObservable_whenFilteringWithTakeFirst_thenOnlyFirstItemIsEmitted() { + + Observable sourceObservable = Observable.just(1, 2, 3, 4, 5, 7, 6); + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = sourceObservable.takeFirst(x -> x > 5); + + filteredObservable.subscribe(subscriber); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue(7); + } + + @Test + public void givenRangeObservable_whenFilteringWithFirst_thenOnlyFirstThreeItemsAreEmitted() { + + Observable sourceObservable = Observable.range(1, 10); + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = sourceObservable.first(); + + filteredObservable.subscribe(subscriber); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue(1); + } + + @Test + public void givenEmptyObservable_whenFilteringWithFirstOrDefault_thenDefaultValue() { + + Observable sourceObservable = Observable.empty(); + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = sourceObservable.firstOrDefault(-1); + + filteredObservable.subscribe(subscriber); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue(-1); + } + + @Test + public void givenRangeObservable_whenFilteringWithTakeLast_thenLastThreeItemAreEmitted() { + + Observable sourceObservable = Observable.range(1, 10); + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = sourceObservable.takeLast(3); + + filteredObservable.subscribe(subscriber); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(3); + subscriber.assertValues(8, 9, 10); + } + + @Test + public void givenRangeObservable_whenFilteringWithLast_thenOnlyLastItemIsEmitted() { + + Observable sourceObservable = Observable.range(1, 10); + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = sourceObservable.last(i -> i % 2 != 0); + + filteredObservable.subscribe(subscriber); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue(9); + } + + @Test + public void givenRangeObservable_whenFilteringWithLastAndDefault_thenOnlyDefaultIsEmitted() { + + Observable sourceObservable = Observable.range(1, 10); + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = sourceObservable.lastOrDefault(-1, i -> i > 10); + + filteredObservable.subscribe(subscriber); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue(-1); + } + + @Test + public void givenObservable_whenTakingElementAt_thenItemAtSpecifiedIndexIsEmitted() { + + Observable sourceObservable = Observable.just(1, 2, 3, 5, 7, 11); + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = sourceObservable.elementAt(4); + + filteredObservable.subscribe(subscriber); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue(7); + } + + @Test + public void givenObservable_whenTakingElementAtOrDefault_thenDefaultIsReturned() { + + Observable sourceObservable = Observable.just(1, 2, 3, 5, 7, 11); + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = sourceObservable.elementAtOrDefault(7, -1); + + filteredObservable.subscribe(subscriber); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue(-1); + } + + @Test + public void givenMixedTypeObservable_whenFilteringByType_thenOnlyNumbersAreEmitted() { + + Observable sourceObservable = Observable.just(1, "two", 3, "five", 7, 11); + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = sourceObservable.ofType(String.class); + + filteredObservable.subscribe(subscriber); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(2); + subscriber.assertValues("two", "five"); + + } +} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsTest.java deleted file mode 100644 index be0f390b67..0000000000 --- a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsTest.java +++ /dev/null @@ -1,202 +0,0 @@ -package com.baeldung.rxjava.filters; - -import org.junit.Test; - -import rx.Observable; -import rx.observers.TestSubscriber; - -public class RxJavaFilterOperatorsTest { - - @Test - public void givenRangeObservable_whenFilteringItems_thenOddItemsAreFiltered() { - - Observable sourceObservable = Observable.range(1, 10); - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = sourceObservable.filter(i -> i % 2 != 0); - - filteredObservable.subscribe(subscriber); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(5); - subscriber.assertValues(1, 3, 5, 7, 9); - } - - @Test - public void givenRangeObservable_whenFilteringWithTake_thenOnlyFirstThreeItemsAreEmitted() { - - Observable sourceObservable = Observable.range(1, 10); - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = sourceObservable.take(3); - - filteredObservable.subscribe(subscriber); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(3); - subscriber.assertValues(1, 2, 3); - } - - @Test - public void givenObservable_whenFilteringWithTakeWhile_thenItemsEmittedUntilConditionIsVerified() { - - Observable sourceObservable = Observable.just(1, 2, 3, 4, 3, 2, 1); - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = sourceObservable.takeWhile(i -> i < 4); - - filteredObservable.subscribe(subscriber); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(3); - subscriber.assertValues(1, 2, 3); - } - - @Test - public void givenRangeObservable_whenFilteringWithTakeFirst_thenOnlyFirstItemIsEmitted() { - - Observable sourceObservable = Observable.just(1, 2, 3, 4, 5, 7, 6); - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = sourceObservable.takeFirst(x -> x > 5); - - filteredObservable.subscribe(subscriber); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue(7); - } - - @Test - public void givenRangeObservable_whenFilteringWithFirst_thenOnlyFirstThreeItemsAreEmitted() { - - Observable sourceObservable = Observable.range(1, 10); - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = sourceObservable.first(); - - filteredObservable.subscribe(subscriber); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue(1); - } - - @Test - public void givenEmptyObservable_whenFilteringWithFirstOrDefault_thenDefaultValue() { - - Observable sourceObservable = Observable.empty(); - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = sourceObservable.firstOrDefault(-1); - - filteredObservable.subscribe(subscriber); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue(-1); - } - - @Test - public void givenRangeObservable_whenFilteringWithTakeLast_thenLastThreeItemAreEmitted() { - - Observable sourceObservable = Observable.range(1, 10); - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = sourceObservable.takeLast(3); - - filteredObservable.subscribe(subscriber); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(3); - subscriber.assertValues(8, 9, 10); - } - - @Test - public void givenRangeObservable_whenFilteringWithLast_thenOnlyLastItemIsEmitted() { - - Observable sourceObservable = Observable.range(1, 10); - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = sourceObservable.last(i -> i % 2 != 0); - - filteredObservable.subscribe(subscriber); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue(9); - } - - @Test - public void givenRangeObservable_whenFilteringWithLastAndDefault_thenOnlyDefaultIsEmitted() { - - Observable sourceObservable = Observable.range(1, 10); - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = sourceObservable.lastOrDefault(-1, i -> i > 10); - - filteredObservable.subscribe(subscriber); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue(-1); - } - - @Test - public void givenObservable_whenTakingElementAt_thenItemAtSpecifiedIndexIsEmitted() { - - Observable sourceObservable = Observable.just(1, 2, 3, 5, 7, 11); - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = sourceObservable.elementAt(4); - - filteredObservable.subscribe(subscriber); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue(7); - } - - @Test - public void givenObservable_whenTakingElementAtOrDefault_thenDefaultIsReturned() { - - Observable sourceObservable = Observable.just(1, 2, 3, 5, 7, 11); - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = sourceObservable.elementAtOrDefault(7, -1); - - filteredObservable.subscribe(subscriber); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue(-1); - } - - @Test - public void givenMixedTypeObservable_whenFilteringByType_thenOnlyNumbersAreEmitted() { - - Observable sourceObservable = Observable.just(1, "two", 3, "five", 7, 11); - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = sourceObservable.ofType(String.class); - - filteredObservable.subscribe(subscriber); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(2); - subscriber.assertValues("two", "five"); - - } -} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsIntegrationTest.java new file mode 100644 index 0000000000..eca65e728e --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsIntegrationTest.java @@ -0,0 +1,105 @@ +package com.baeldung.rxjava.filters; + +import org.junit.Test; + +import rx.Observable; +import rx.observers.TestSubscriber; + +public class RxJavaSkipOperatorsIntegrationTest { + + @Test + public void givenRangeObservable_whenSkipping_thenFirstFourItemsAreSkipped() { + + Observable sourceObservable = Observable.range(1, 10); + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = sourceObservable.skip(4); + + filteredObservable.subscribe(subscriber); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(6); + subscriber.assertValues(5, 6, 7, 8, 9, 10); + } + + @Test + public void givenObservable_whenSkippingWhile_thenFirstItemsAreSkipped() { + + Observable sourceObservable = Observable.just(1, 2, 3, 4, 5, 4, 3, 2, 1); + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = sourceObservable.skipWhile(i -> i < 4); + + filteredObservable.subscribe(subscriber); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(6); + subscriber.assertValues(4, 5, 4, 3, 2, 1); + } + + @Test + public void givenRangeObservable_whenSkippingLast_thenLastFiveItemsAreSkipped() { + + Observable sourceObservable = Observable.range(1, 10); + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = sourceObservable.skipLast(5); + + filteredObservable.subscribe(subscriber); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(5); + subscriber.assertValues(1, 2, 3, 4, 5); + } + + @Test + public void givenObservable_whenFilteringDistinct_thenOnlyDistinctValuesAreEmitted() { + + Observable sourceObservable = Observable.just(1, 1, 2, 2, 1, 3, 3, 1); + TestSubscriber subscriber = new TestSubscriber(); + + Observable distinctObservable = sourceObservable.distinct(); + + distinctObservable.subscribe(subscriber); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(3); + subscriber.assertValues(1, 2, 3); + } + + @Test + public void givenObservable_whenFilteringDistinctUntilChanged_thenOnlyDistinctConsecutiveItemsAreEmitted() { + + Observable sourceObservable = Observable.just(1, 1, 2, 2, 1, 3, 3, 1); + TestSubscriber subscriber = new TestSubscriber(); + + Observable distinctObservable = sourceObservable.distinctUntilChanged(); + + distinctObservable.subscribe(subscriber); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(5); + subscriber.assertValues(1, 2, 1, 3, 1); + } + + @Test + public void givenRangeObservable_whenIgnoringElements_thenOnlyDistinctConsecutiveItemsAreEmitted() { + + Observable sourceObservable = Observable.range(1, 10); + TestSubscriber subscriber = new TestSubscriber(); + + Observable ignoredObservable = sourceObservable.ignoreElements(); + + ignoredObservable.subscribe(subscriber); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(0); + subscriber.assertNoValues(); + } +} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsTest.java deleted file mode 100644 index eca39b17bf..0000000000 --- a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsTest.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.baeldung.rxjava.filters; - -import org.junit.Test; - -import rx.Observable; -import rx.observers.TestSubscriber; - -public class RxJavaSkipOperatorsTest { - - @Test - public void givenRangeObservable_whenSkipping_thenFirstFourItemsAreSkipped() { - - Observable sourceObservable = Observable.range(1, 10); - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = sourceObservable.skip(4); - - filteredObservable.subscribe(subscriber); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(6); - subscriber.assertValues(5, 6, 7, 8, 9, 10); - } - - @Test - public void givenObservable_whenSkippingWhile_thenFirstItemsAreSkipped() { - - Observable sourceObservable = Observable.just(1, 2, 3, 4, 5, 4, 3, 2, 1); - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = sourceObservable.skipWhile(i -> i < 4); - - filteredObservable.subscribe(subscriber); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(6); - subscriber.assertValues(4, 5, 4, 3, 2, 1); - } - - @Test - public void givenRangeObservable_whenSkippingLast_thenLastFiveItemsAreSkipped() { - - Observable sourceObservable = Observable.range(1, 10); - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = sourceObservable.skipLast(5); - - filteredObservable.subscribe(subscriber); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(5); - subscriber.assertValues(1, 2, 3, 4, 5); - } - - @Test - public void givenObservable_whenFilteringDistinct_thenOnlyDistinctValuesAreEmitted() { - - Observable sourceObservable = Observable.just(1, 1, 2, 2, 1, 3, 3, 1); - TestSubscriber subscriber = new TestSubscriber(); - - Observable distinctObservable = sourceObservable.distinct(); - - distinctObservable.subscribe(subscriber); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(3); - subscriber.assertValues(1, 2, 3); - } - - @Test - public void givenObservable_whenFilteringDistinctUntilChanged_thenOnlyDistinctConsecutiveItemsAreEmitted() { - - Observable sourceObservable = Observable.just(1, 1, 2, 2, 1, 3, 3, 1); - TestSubscriber subscriber = new TestSubscriber(); - - Observable distinctObservable = sourceObservable.distinctUntilChanged(); - - distinctObservable.subscribe(subscriber); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(5); - subscriber.assertValues(1, 2, 1, 3, 1); - } - - @Test - public void givenRangeObservable_whenIgnoringElements_thenOnlyDistinctConsecutiveItemsAreEmitted() { - - Observable sourceObservable = Observable.range(1, 10); - TestSubscriber subscriber = new TestSubscriber(); - - Observable ignoredObservable = sourceObservable.ignoreElements(); - - ignoredObservable.subscribe(subscriber); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(0); - subscriber.assertNoValues(); - } -} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsIntegrationTest.java new file mode 100644 index 0000000000..d9ec6c3798 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsIntegrationTest.java @@ -0,0 +1,221 @@ +package com.baeldung.rxjava.filters; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import org.junit.Test; + +import rx.Observable; +import rx.observers.TestSubscriber; +import rx.schedulers.TestScheduler; + +public class RxJavaTimeFilteringOperatorsIntegrationTest { + + @Test + public void givenTimedObservable_whenSampling_thenOnlySampleItemsAreEmitted() { + + TestScheduler testScheduler = new TestScheduler(); + + Observable timedObservable = + Observable.just(1, 2, 3, 4, 5, 6) + .zipWith( + Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler), + (item, time) -> item + ); + + TestSubscriber subscriber = new TestSubscriber(); + + Observable sampledObservable = + timedObservable.sample(2500L, TimeUnit.MILLISECONDS, testScheduler); + + sampledObservable.subscribe(subscriber); + + testScheduler.advanceTimeBy(7, TimeUnit.SECONDS); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValues(3, 5, 6); + } + + @Test + public void givenTimedObservable_whenThrottlingLast_thenThrottleLastItemsAreEmitted() { + + TestScheduler testScheduler = new TestScheduler(); + + Observable timedObservable = + Observable.just(1, 2, 3, 4, 5, 6) + .zipWith( + Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler), + (item, time) -> item + ); + + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = timedObservable.throttleLast(3100L, TimeUnit.MILLISECONDS, testScheduler); + + filteredObservable.subscribe(subscriber); + + testScheduler.advanceTimeBy(7, TimeUnit.SECONDS); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValues(4, 6); + } + + @Test + public void givenRangeObservable_whenThrottlingFirst_thenThrottledFirstItemsAreEmitted() { + + TestScheduler testScheduler = new TestScheduler(); + + Observable timedObservable = + Observable.just(1, 2, 3, 4, 5, 6) + .zipWith( + Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler), + (item, time) -> item + ); + + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = + timedObservable.throttleFirst(4100L, TimeUnit.MILLISECONDS, testScheduler); + + filteredObservable.subscribe(subscriber); + + testScheduler.advanceTimeBy(7, TimeUnit.SECONDS); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValues(1, 6); + } + + @Test + public void givenTimedObservable_whenThrottlingWithTimeout_thenLastItemIsEmitted() { + + TestScheduler testScheduler = new TestScheduler(); + + Observable timedObservable = + Observable.just(1, 2, 3, 4, 5, 6) + .zipWith( + Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler), + (item, time) -> item + ); + + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = timedObservable.throttleWithTimeout(2000L, TimeUnit.MILLISECONDS, testScheduler); + + filteredObservable.subscribe(subscriber); + + testScheduler.advanceTimeBy(7, TimeUnit.SECONDS); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValue(6); + } + + @Test + public void givenTimedObservable_whenDebounceOperatorIsApplied_thenLastItemIsEmitted() { + + TestScheduler testScheduler = new TestScheduler(); + + Observable timedObservable = + Observable.just(1, 2, 3, 4, 5, 6) + .zipWith( + Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler), + (item, time) -> item + ); + + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = timedObservable.debounce(2000L, TimeUnit.MILLISECONDS, testScheduler); + + filteredObservable.subscribe(subscriber); + + testScheduler.advanceTimeBy(7, TimeUnit.SECONDS); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValue(6); + } + + @Test + public void givenTimedObservable_whenUsingTimeout_thenTimeOutException() { + + TestScheduler testScheduler = new TestScheduler(); + + Observable timedObservable = + Observable.just(1, 2, 3, 4, 5, 6) + .zipWith( + Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler), + (item, time) -> item + ); + + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = timedObservable.timeout(500L, TimeUnit.MILLISECONDS, testScheduler); + + filteredObservable.subscribe(subscriber); + + testScheduler.advanceTimeBy(7, TimeUnit.SECONDS); + + subscriber.assertError(TimeoutException.class); + subscriber.assertValues(1); + } + + @Test + public void givenObservable_whenSkippingUntil_thenItemsAreSkippedUntilSecondObservableEmitsItems() { + + TestScheduler testScheduler = new TestScheduler(); + + Observable timedObservable = + Observable.just(1, 2, 3, 4, 5, 6) + .zipWith( + Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler), + (item, time) -> item + ); + + + Observable delayedObservable = Observable.just(1) + .delay(3000, TimeUnit.MILLISECONDS, testScheduler); + + TestSubscriber subscriber = new TestSubscriber(); + + Observable filteredObservable = timedObservable.skipUntil(delayedObservable); + + filteredObservable.subscribe(subscriber); + + testScheduler.advanceTimeBy(7, TimeUnit.SECONDS); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValues(4, 5, 6); + } + + @Test + public void givenObservable_whenSkippingWhile_thenItemsAreEmittedUntilSecondObservableEmitsItems() { + + TestScheduler testScheduler = new TestScheduler(); + + Observable timedObservable = + Observable.just(1, 2, 3, 4, 5, 6) + .zipWith( + Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler), + (item, time) -> item + ); + + TestSubscriber subscriber = new TestSubscriber(); + + Observable delayedObservable = Observable.just(1) + .delay(3000, TimeUnit.MILLISECONDS, testScheduler); + + Observable filteredObservable = timedObservable.takeUntil(delayedObservable); + + filteredObservable.subscribe(subscriber); + + testScheduler.advanceTimeBy(7, TimeUnit.SECONDS); + + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValues(1, 2, 3); + } +} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsTest.java deleted file mode 100644 index 63076cbc4a..0000000000 --- a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsTest.java +++ /dev/null @@ -1,221 +0,0 @@ -package com.baeldung.rxjava.filters; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import org.junit.Test; - -import rx.Observable; -import rx.observers.TestSubscriber; -import rx.schedulers.TestScheduler; - -public class RxJavaTimeFilteringOperatorsTest { - - @Test - public void givenTimedObservable_whenSampling_thenOnlySampleItemsAreEmitted() { - - TestScheduler testScheduler = new TestScheduler(); - - Observable timedObservable = - Observable.just(1, 2, 3, 4, 5, 6) - .zipWith( - Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler), - (item, time) -> item - ); - - TestSubscriber subscriber = new TestSubscriber(); - - Observable sampledObservable = - timedObservable.sample(2500L, TimeUnit.MILLISECONDS, testScheduler); - - sampledObservable.subscribe(subscriber); - - testScheduler.advanceTimeBy(7, TimeUnit.SECONDS); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValues(3, 5, 6); - } - - @Test - public void givenTimedObservable_whenThrottlingLast_thenThrottleLastItemsAreEmitted() { - - TestScheduler testScheduler = new TestScheduler(); - - Observable timedObservable = - Observable.just(1, 2, 3, 4, 5, 6) - .zipWith( - Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler), - (item, time) -> item - ); - - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = timedObservable.throttleLast(3100L, TimeUnit.MILLISECONDS, testScheduler); - - filteredObservable.subscribe(subscriber); - - testScheduler.advanceTimeBy(7, TimeUnit.SECONDS); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValues(4, 6); - } - - @Test - public void givenRangeObservable_whenThrottlingFirst_thenThrottledFirstItemsAreEmitted() { - - TestScheduler testScheduler = new TestScheduler(); - - Observable timedObservable = - Observable.just(1, 2, 3, 4, 5, 6) - .zipWith( - Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler), - (item, time) -> item - ); - - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = - timedObservable.throttleFirst(4100L, TimeUnit.MILLISECONDS, testScheduler); - - filteredObservable.subscribe(subscriber); - - testScheduler.advanceTimeBy(7, TimeUnit.SECONDS); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValues(1, 6); - } - - @Test - public void givenTimedObservable_whenThrottlingWithTimeout_thenLastItemIsEmitted() { - - TestScheduler testScheduler = new TestScheduler(); - - Observable timedObservable = - Observable.just(1, 2, 3, 4, 5, 6) - .zipWith( - Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler), - (item, time) -> item - ); - - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = timedObservable.throttleWithTimeout(2000L, TimeUnit.MILLISECONDS, testScheduler); - - filteredObservable.subscribe(subscriber); - - testScheduler.advanceTimeBy(7, TimeUnit.SECONDS); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValue(6); - } - - @Test - public void givenTimedObservable_whenDebounceOperatorIsApplied_thenLastItemIsEmitted() { - - TestScheduler testScheduler = new TestScheduler(); - - Observable timedObservable = - Observable.just(1, 2, 3, 4, 5, 6) - .zipWith( - Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler), - (item, time) -> item - ); - - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = timedObservable.debounce(2000L, TimeUnit.MILLISECONDS, testScheduler); - - filteredObservable.subscribe(subscriber); - - testScheduler.advanceTimeBy(7, TimeUnit.SECONDS); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValue(6); - } - - @Test - public void givenTimedObservable_whenUsingTimeout_thenTimeOutException() { - - TestScheduler testScheduler = new TestScheduler(); - - Observable timedObservable = - Observable.just(1, 2, 3, 4, 5, 6) - .zipWith( - Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler), - (item, time) -> item - ); - - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = timedObservable.timeout(500L, TimeUnit.MILLISECONDS, testScheduler); - - filteredObservable.subscribe(subscriber); - - testScheduler.advanceTimeBy(7, TimeUnit.SECONDS); - - subscriber.assertError(TimeoutException.class); - subscriber.assertValues(1); - } - - @Test - public void givenObservable_whenSkippingUntil_thenItemsAreSkippedUntilSecondObservableEmitsItems() { - - TestScheduler testScheduler = new TestScheduler(); - - Observable timedObservable = - Observable.just(1, 2, 3, 4, 5, 6) - .zipWith( - Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler), - (item, time) -> item - ); - - - Observable delayedObservable = Observable.just(1) - .delay(3000, TimeUnit.MILLISECONDS, testScheduler); - - TestSubscriber subscriber = new TestSubscriber(); - - Observable filteredObservable = timedObservable.skipUntil(delayedObservable); - - filteredObservable.subscribe(subscriber); - - testScheduler.advanceTimeBy(7, TimeUnit.SECONDS); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValues(4, 5, 6); - } - - @Test - public void givenObservable_whenSkippingWhile_thenItemsAreEmittedUntilSecondObservableEmitsItems() { - - TestScheduler testScheduler = new TestScheduler(); - - Observable timedObservable = - Observable.just(1, 2, 3, 4, 5, 6) - .zipWith( - Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler), - (item, time) -> item - ); - - TestSubscriber subscriber = new TestSubscriber(); - - Observable delayedObservable = Observable.just(1) - .delay(3000, TimeUnit.MILLISECONDS, testScheduler); - - Observable filteredObservable = timedObservable.takeUntil(delayedObservable); - - filteredObservable.subscribe(subscriber); - - testScheduler.advanceTimeBy(7, TimeUnit.SECONDS); - - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValues(1, 2, 3); - } -} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java index 477a2a1cb8..ec766ac7ac 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java @@ -18,26 +18,27 @@ public class AutomapInterfaceIntegrationTest { private ConnectionProvider connectionProvider = Connector.connectionProvider; private Database db = Database.from(connectionProvider); - private Observable create = null; + private Observable truncate = null; private Observable insert1, insert2 = null; @Before public void setup() { - create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))") + Observable create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))") .count(); + truncate = db.update("TRUNCATE TABLE EMPLOYEE") + .dependsOn(create) + .count(); insert1 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'Alan')") - .dependsOn(create) + .dependsOn(truncate) .count(); insert2 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(2, 'Sarah')") - .dependsOn(create) + .dependsOn(insert1) .count(); } @Test public void whenSelectFromTableAndAutomap_thenCorrect() { List employees = db.select("select id, name from EMPLOYEE") - .dependsOn(create) - .dependsOn(insert1) .dependsOn(insert2) .autoMap(Employee.class) .toList() @@ -57,7 +58,7 @@ public class AutomapInterfaceIntegrationTest { @After public void close() { db.update("DROP TABLE EMPLOYEE") - .dependsOn(create); + .dependsOn(truncate); connectionProvider.close(); } } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java index 5f445234d7..2fb3b3abd7 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java @@ -22,24 +22,24 @@ public class BasicQueryTypesIntegrationTest { @Test public void whenCreateTableAndInsertRecords_thenCorrect() { - create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))") + create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE_TABLE(id int primary key, name varchar(255))") .count(); - Observable insert1 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'John')") + Observable insert1 = db.update("INSERT INTO EMPLOYEE_TABLE(id, name) VALUES(1, 'John')") .dependsOn(create) .count(); - Observable update = db.update("UPDATE EMPLOYEE SET name = 'Alan' WHERE id = 1") + Observable update = db.update("UPDATE EMPLOYEE_TABLE SET name = 'Alan' WHERE id = 1") .dependsOn(create) .count(); - Observable insert2 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(2, 'Sarah')") + Observable insert2 = db.update("INSERT INTO EMPLOYEE_TABLE(id, name) VALUES(2, 'Sarah')") .dependsOn(create) .count(); - Observable insert3 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(3, 'Mike')") + Observable insert3 = db.update("INSERT INTO EMPLOYEE_TABLE(id, name) VALUES(3, 'Mike')") .dependsOn(create) .count(); - Observable delete = db.update("DELETE FROM EMPLOYEE WHERE id = 2") + Observable delete = db.update("DELETE FROM EMPLOYEE_TABLE WHERE id = 2") .dependsOn(create) .count(); - List names = db.select("select name from EMPLOYEE where id < ?") + List names = db.select("select name from EMPLOYEE_TABLE where id < ?") .parameter(3) .dependsOn(create) .dependsOn(insert1) @@ -57,7 +57,7 @@ public class BasicQueryTypesIntegrationTest { @After public void close() { - db.update("DROP TABLE EMPLOYEE") + db.update("DROP TABLE EMPLOYEE_TABLE") .dependsOn(create); connectionProvider.close(); } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java index 189bca4adb..284ecc4078 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java @@ -27,7 +27,7 @@ public class InsertClobIntegrationTest { @Before public void setup() throws IOException { - create = db.update("CREATE TABLE IF NOT EXISTS SERVERLOG (id int primary key, document CLOB)") + create = db.update("CREATE TABLE IF NOT EXISTS SERVERLOG_TABLE (id int primary key, document CLOB)") .count(); InputStream actualInputStream = new FileInputStream("src/test/resources/actual_clob"); @@ -35,7 +35,7 @@ public class InsertClobIntegrationTest { InputStream expectedInputStream = new FileInputStream("src/test/resources/expected_clob"); this.expectedDocument = Utils.getStringFromInputStream(expectedInputStream); - this.insert = db.update("insert into SERVERLOG(id,document) values(?,?)") + this.insert = db.update("insert into SERVERLOG_TABLE(id,document) values(?,?)") .parameter(1) .parameter(Database.toSentinelIfNull(actualDocument)) .dependsOn(create) @@ -44,7 +44,7 @@ public class InsertClobIntegrationTest { @Test public void whenSelectCLOB_thenCorrect() throws IOException { - db.select("select document from SERVERLOG where id = 1") + db.select("select document from SERVERLOG_TABLE where id = 1") .dependsOn(create) .dependsOn(insert) .getAs(String.class) @@ -56,7 +56,7 @@ public class InsertClobIntegrationTest { @After public void close() { - db.update("DROP TABLE SERVERLOG") + db.update("DROP TABLE SERVERLOG_TABLE") .dependsOn(create); connectionProvider.close(); } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java index 2018a9427c..c9e06a347f 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java @@ -22,14 +22,14 @@ public class ReturnKeysIntegrationTest { @Before public void setup() { begin = db.beginTransaction(); - createStatement = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int auto_increment primary key, name varchar(255))") + createStatement = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE_SAMPLE(id int auto_increment primary key, name varchar(255))") .dependsOn(begin) .count(); } @Test public void whenInsertAndReturnGeneratedKey_thenCorrect() { - Integer key = db.update("INSERT INTO EMPLOYEE(name) VALUES('John')") + Integer key = db.update("INSERT INTO EMPLOYEE_SAMPLE(name) VALUES('John')") .dependsOn(createStatement) .returnGeneratedKeys() .getAs(Integer.class) @@ -41,7 +41,7 @@ public class ReturnKeysIntegrationTest { @After public void close() { - db.update("DROP TABLE EMPLOYEE") + db.update("DROP TABLE EMPLOYEE_SAMPLE") .dependsOn(createStatement); connectionProvider.close(); } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java index 4e24d7f10e..d5f09be23c 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java @@ -24,8 +24,11 @@ public class TransactionIntegrationTest { .update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))") .dependsOn(begin) .count(); + Observable truncateStatement = db.update("TRUNCATE TABLE EMPLOYEE") + .dependsOn(createStatement) + .count(); Observable insertStatement = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'John')") - .dependsOn(createStatement) + .dependsOn(truncateStatement) .count(); Observable updateStatement = db.update("UPDATE EMPLOYEE SET name = 'Tom' WHERE id = 1") .dependsOn(insertStatement) diff --git a/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingTest.java b/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingTest.java deleted file mode 100644 index b1d711ab39..0000000000 --- a/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingTest.java +++ /dev/null @@ -1,138 +0,0 @@ -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; - -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 deleted file mode 100644 index 3cc72056ba..0000000000 --- a/rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryTest.java +++ /dev/null @@ -1,146 +0,0 @@ -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; - -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/rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsTest.java deleted file mode 100644 index 6733aa08c5..0000000000 --- a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsTest.java +++ /dev/null @@ -1,221 +0,0 @@ -package com.baeldung.rxjava.operators; - -import org.junit.Test; -import rx.Observable; -import rx.observers.TestSubscriber; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; - -public class RxAggregateOperatorsTest { - - @Test - public void givenTwoObservable_whenConcatenatingThem_thenSuccessfull() { - // given - List listOne = Arrays.asList(1, 2, 3, 4); - Observable observableOne = Observable.from(listOne); - - List listTwo = Arrays.asList(5, 6, 7, 8); - Observable observableTwo = Observable.from(listTwo); - - TestSubscriber subscriber = TestSubscriber.create(); - - // when - Observable concatObservable = observableOne.concatWith(observableTwo); - - concatObservable.subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(8); - subscriber.assertValues(1, 2, 3, 4, 5, 6, 7, 8); - } - - @Test - public void givenObservable_whenCounting_thenObtainingNumberOfElements() { - // given - List lettersList = Arrays.asList("A", "B", "C", "D", "E", "F", "G"); - - TestSubscriber subscriber = TestSubscriber.create(); - - // when - Observable sourceObservable = Observable.from(lettersList) - .count(); - sourceObservable.subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue(7); - } - - @Test - public void givenObservable_whenReducing_thenObtainingInvertedConcatenatedString() { - // given - List list = Arrays.asList("A", "B", "C", "D", "E", "F", "G"); - - TestSubscriber subscriber = TestSubscriber.create(); - - // when - Observable reduceObservable = Observable.from(list) - .reduce((letter1, letter2) -> letter2 + letter1); - reduceObservable.subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue("GFEDCBA"); - } - - @Test - public void givenObservable_whenCollecting_thenObtainingASet() { - // given - List list = Arrays.asList("A", "B", "C", "B", "B", "A", "D"); - - TestSubscriber subscriber = TestSubscriber.create(); - - // when - Observable> reduceListObservable = Observable.from(list) - .collect(HashSet::new, HashSet::add); - reduceListObservable.subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValues(new HashSet<>(list)); - } - - @Test - public void givenObservable_whenUsingToList_thenObtainedAList() { - // given - Observable sourceObservable = Observable.range(1, 5); - TestSubscriber subscriber = TestSubscriber.create(); - - // when - Observable> listObservable = sourceObservable.toList(); - listObservable.subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue(Arrays.asList(1, 2, 3, 4, 5)); - } - - @Test - public void givenObservable_whenUsingToSortedList_thenObtainedASortedList() { - // given - Observable sourceObservable = Observable.range(10, 5); - TestSubscriber subscriber = TestSubscriber.create(); - - // when - Observable> listObservable = sourceObservable.toSortedList(); - listObservable.subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue(Arrays.asList(10, 11, 12, 13, 14)); - } - - @Test - public void givenObservable_whenUsingToSortedListWithComparator_thenObtainedAnInverseSortedList() { - // given - Observable sourceObservable = Observable.range(10, 5); - TestSubscriber subscriber = TestSubscriber.create(); - - // when - Observable> listObservable = sourceObservable.toSortedList((int1, int2) -> int2 - int1); - listObservable.subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue(Arrays.asList(14, 13, 12, 11, 10)); - } - - @Test - public void givenObservable_whenUsingToMap_thenObtainedAMap() { - // given - Observable bookObservable = Observable - .just( - new Book("The North Water", 2016), - new Book("Origin", 2017), - new Book("Sleeping Beauties", 2017)); - TestSubscriber subscriber = TestSubscriber.create(); - - // when - Observable> mapObservable = bookObservable - .toMap(Book::getTitle, Book::getYear, HashMap::new); - - mapObservable.subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue(new HashMap() { - { - put("The North Water", 2016); - put("Origin", 2017); - put("Sleeping Beauties", 2017); - } - }); - } - - @Test - public void givenObservable_whenUsingToMultiMap_thenObtainedAMultiMap() { - // given - Observable bookObservable = Observable - .just( - new Book("The North Water", 2016), - new Book("Origin", 2017), - new Book("Sleeping Beauties", 2017)); - TestSubscriber subscriber = TestSubscriber.create(); - - // when - Observable multiMapObservable = bookObservable - .toMultimap(Book::getYear, Book::getTitle, () -> new HashMap<>(), (key) -> new ArrayList<>()); - - multiMapObservable.subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue(new HashMap() { - { - put(2016, Arrays.asList("The North Water")); - put(2017, Arrays.asList("Origin", "Sleeping Beauties")); - } - }); - } - - class Book { - private String title; - private Integer year; - - public Book(String title, Integer year) { - this.title = title; - this.year = year; - } - - public String getTitle() { - return title; - } - - public Integer getYear() { - return year; - } - } -} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsUnitTest.java new file mode 100644 index 0000000000..f0d7a9a4e4 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsUnitTest.java @@ -0,0 +1,221 @@ +package com.baeldung.rxjava.operators; + +import org.junit.Test; +import rx.Observable; +import rx.observers.TestSubscriber; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; + +public class RxAggregateOperatorsUnitTest { + + @Test + public void givenTwoObservable_whenConcatenatingThem_thenSuccessfull() { + // given + List listOne = Arrays.asList(1, 2, 3, 4); + Observable observableOne = Observable.from(listOne); + + List listTwo = Arrays.asList(5, 6, 7, 8); + Observable observableTwo = Observable.from(listTwo); + + TestSubscriber subscriber = TestSubscriber.create(); + + // when + Observable concatObservable = observableOne.concatWith(observableTwo); + + concatObservable.subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(8); + subscriber.assertValues(1, 2, 3, 4, 5, 6, 7, 8); + } + + @Test + public void givenObservable_whenCounting_thenObtainingNumberOfElements() { + // given + List lettersList = Arrays.asList("A", "B", "C", "D", "E", "F", "G"); + + TestSubscriber subscriber = TestSubscriber.create(); + + // when + Observable sourceObservable = Observable.from(lettersList) + .count(); + sourceObservable.subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue(7); + } + + @Test + public void givenObservable_whenReducing_thenObtainingInvertedConcatenatedString() { + // given + List list = Arrays.asList("A", "B", "C", "D", "E", "F", "G"); + + TestSubscriber subscriber = TestSubscriber.create(); + + // when + Observable reduceObservable = Observable.from(list) + .reduce((letter1, letter2) -> letter2 + letter1); + reduceObservable.subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue("GFEDCBA"); + } + + @Test + public void givenObservable_whenCollecting_thenObtainingASet() { + // given + List list = Arrays.asList("A", "B", "C", "B", "B", "A", "D"); + + TestSubscriber subscriber = TestSubscriber.create(); + + // when + Observable> reduceListObservable = Observable.from(list) + .collect(HashSet::new, HashSet::add); + reduceListObservable.subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValues(new HashSet<>(list)); + } + + @Test + public void givenObservable_whenUsingToList_thenObtainedAList() { + // given + Observable sourceObservable = Observable.range(1, 5); + TestSubscriber subscriber = TestSubscriber.create(); + + // when + Observable> listObservable = sourceObservable.toList(); + listObservable.subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue(Arrays.asList(1, 2, 3, 4, 5)); + } + + @Test + public void givenObservable_whenUsingToSortedList_thenObtainedASortedList() { + // given + Observable sourceObservable = Observable.range(10, 5); + TestSubscriber subscriber = TestSubscriber.create(); + + // when + Observable> listObservable = sourceObservable.toSortedList(); + listObservable.subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue(Arrays.asList(10, 11, 12, 13, 14)); + } + + @Test + public void givenObservable_whenUsingToSortedListWithComparator_thenObtainedAnInverseSortedList() { + // given + Observable sourceObservable = Observable.range(10, 5); + TestSubscriber subscriber = TestSubscriber.create(); + + // when + Observable> listObservable = sourceObservable.toSortedList((int1, int2) -> int2 - int1); + listObservable.subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue(Arrays.asList(14, 13, 12, 11, 10)); + } + + @Test + public void givenObservable_whenUsingToMap_thenObtainedAMap() { + // given + Observable bookObservable = Observable + .just( + new Book("The North Water", 2016), + new Book("Origin", 2017), + new Book("Sleeping Beauties", 2017)); + TestSubscriber subscriber = TestSubscriber.create(); + + // when + Observable> mapObservable = bookObservable + .toMap(Book::getTitle, Book::getYear, HashMap::new); + + mapObservable.subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue(new HashMap() { + { + put("The North Water", 2016); + put("Origin", 2017); + put("Sleeping Beauties", 2017); + } + }); + } + + @Test + public void givenObservable_whenUsingToMultiMap_thenObtainedAMultiMap() { + // given + Observable bookObservable = Observable + .just( + new Book("The North Water", 2016), + new Book("Origin", 2017), + new Book("Sleeping Beauties", 2017)); + TestSubscriber subscriber = TestSubscriber.create(); + + // when + Observable multiMapObservable = bookObservable + .toMultimap(Book::getYear, Book::getTitle, () -> new HashMap<>(), (key) -> new ArrayList<>()); + + multiMapObservable.subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue(new HashMap() { + { + put(2016, Arrays.asList("The North Water")); + put(2017, Arrays.asList("Origin", "Sleeping Beauties")); + } + }); + } + + class Book { + private String title; + private Integer year; + + public Book(String title, Integer year) { + this.title = title; + this.year = year; + } + + public String getTitle() { + return title; + } + + public Integer getYear() { + return year; + } + } +} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsTest.java deleted file mode 100644 index cd212a2e18..0000000000 --- a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsTest.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.baeldung.rxjava.operators; - -import org.junit.Test; -import rx.Observable; -import rx.observables.MathObservable; -import rx.observers.TestSubscriber; - -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; - -public class RxMathematicalOperatorsTest { - - @Test - public void givenRangeNumericObservable_whenCalculatingAverage_ThenSuccessfull() { - // given - Observable sourceObservable = Observable.range(1, 20); - - TestSubscriber subscriber = TestSubscriber.create(); - - // when - MathObservable.averageInteger(sourceObservable) - .subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue(10); - } - - @Test - public void givenRangeNumericObservable_whenCalculatingSum_ThenSuccessfull() { - // given - Observable sourceObservable = Observable.range(1, 20); - TestSubscriber subscriber = TestSubscriber.create(); - - // when - MathObservable.sumInteger(sourceObservable) - .subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue(210); - - } - - @Test - public void givenRangeNumericObservable_whenCalculatingMax_ThenSuccessfullObtainingMaxValue() { - // given - Observable sourceObservable = Observable.range(1, 20); - TestSubscriber subscriber = TestSubscriber.create(); - - // when - MathObservable.max(sourceObservable) - .subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue(20); - } - - @Test - public void givenRangeNumericObservable_whenCalculatingMin_ThenSuccessfullObtainingMinValue() { - // given - Observable sourceObservable = Observable.range(1, 20); - TestSubscriber subscriber = TestSubscriber.create(); - - // when - MathObservable.min(sourceObservable) - .subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue(1); - } - - @Test - public void givenItemObservable_whenCalculatingMaxWithComparator_ThenSuccessfullObtainingMaxItem() { - // given - Item five = new Item(5); - List list = Arrays.asList(new Item(1), new Item(2), new Item(3), new Item(4), five); - Observable itemObservable = Observable.from(list); - - TestSubscriber subscriber = TestSubscriber.create(); - - // when - MathObservable.from(itemObservable) - .max(Comparator.comparing(Item::getId)) - .subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue(five); - - } - - @Test - public void givenItemObservable_whenCalculatingMinWithComparator_ThenSuccessfullObtainingMinItem() { - // given - Item one = new Item(1); - List list = Arrays.asList(one, new Item(2), new Item(3), new Item(4), new Item(5)); - TestSubscriber subscriber = TestSubscriber.create(); - Observable itemObservable = Observable.from(list); - - // when - MathObservable.from(itemObservable) - .min(Comparator.comparing(Item::getId)) - .subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValue(one); - - } - - class Item { - private Integer id; - - public Item(Integer id) { - this.id = id; - } - - public Integer getId() { - return id; - } - - } -} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsUnitTest.java new file mode 100644 index 0000000000..9390792737 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsUnitTest.java @@ -0,0 +1,139 @@ +package com.baeldung.rxjava.operators; + +import org.junit.Test; +import rx.Observable; +import rx.observables.MathObservable; +import rx.observers.TestSubscriber; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; + +public class RxMathematicalOperatorsUnitTest { + + @Test + public void givenRangeNumericObservable_whenCalculatingAverage_ThenSuccessfull() { + // given + Observable sourceObservable = Observable.range(1, 20); + + TestSubscriber subscriber = TestSubscriber.create(); + + // when + MathObservable.averageInteger(sourceObservable) + .subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue(10); + } + + @Test + public void givenRangeNumericObservable_whenCalculatingSum_ThenSuccessfull() { + // given + Observable sourceObservable = Observable.range(1, 20); + TestSubscriber subscriber = TestSubscriber.create(); + + // when + MathObservable.sumInteger(sourceObservable) + .subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue(210); + + } + + @Test + public void givenRangeNumericObservable_whenCalculatingMax_ThenSuccessfullObtainingMaxValue() { + // given + Observable sourceObservable = Observable.range(1, 20); + TestSubscriber subscriber = TestSubscriber.create(); + + // when + MathObservable.max(sourceObservable) + .subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue(20); + } + + @Test + public void givenRangeNumericObservable_whenCalculatingMin_ThenSuccessfullObtainingMinValue() { + // given + Observable sourceObservable = Observable.range(1, 20); + TestSubscriber subscriber = TestSubscriber.create(); + + // when + MathObservable.min(sourceObservable) + .subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue(1); + } + + @Test + public void givenItemObservable_whenCalculatingMaxWithComparator_ThenSuccessfullObtainingMaxItem() { + // given + Item five = new Item(5); + List list = Arrays.asList(new Item(1), new Item(2), new Item(3), new Item(4), five); + Observable itemObservable = Observable.from(list); + + TestSubscriber subscriber = TestSubscriber.create(); + + // when + MathObservable.from(itemObservable) + .max(Comparator.comparing(Item::getId)) + .subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue(five); + + } + + @Test + public void givenItemObservable_whenCalculatingMinWithComparator_ThenSuccessfullObtainingMinItem() { + // given + Item one = new Item(1); + List list = Arrays.asList(one, new Item(2), new Item(3), new Item(4), new Item(5)); + TestSubscriber subscriber = TestSubscriber.create(); + Observable itemObservable = Observable.from(list); + + // when + MathObservable.from(itemObservable) + .min(Comparator.comparing(Item::getId)) + .subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValue(one); + + } + + class Item { + private Integer id; + + public Item(Integer id) { + this.id = id; + } + + public Integer getId() { + return id; + } + + } +} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsTest.java deleted file mode 100644 index 5e58b32d8b..0000000000 --- a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsTest.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.baeldung.rxjava.operators; - -import java.io.ByteArrayInputStream; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; - -import org.junit.Assert; -import org.junit.Test; - -import rx.Observable; -import rx.observables.StringObservable; -import rx.observers.TestSubscriber; - - -public class RxStringOperatorsTest -{ - - @Test - public void givenStringObservable_whenFromInputStream_ThenSuccessfull() - { - //given - ByteArrayInputStream is = new ByteArrayInputStream("Lorem ipsum loream, Lorem ipsum lore".getBytes(StandardCharsets.UTF_8)); - TestSubscriber subscriber = TestSubscriber.create(); - - // when - StringObservable.decode(StringObservable.from(is), StandardCharsets.UTF_8) - .subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValues("Lorem ipsum loream, Lorem ipsum lore"); - } - @Test - public void givenStringObservable_whenEncodingString_ThenSuccessfullObtainingByteStream() - { - //given - Observable sourceObservable = Observable.just("Lorem ipsum loream"); - TestSubscriber subscriber = TestSubscriber.create(); - - // when - StringObservable.encode(sourceObservable, StandardCharsets.UTF_8) - .subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.getOnNextEvents() - .stream() - .forEach(bytes -> Assert.assertTrue(Arrays.equals(bytes, "Lorem ipsum loream".getBytes(StandardCharsets.UTF_8)))); - } - - @Test - public void givenStringObservable_whenConcatenatingStrings_ThenSuccessfullObtainingSingleString() - { - //given - Observable sourceObservable = Observable.just("Lorem ipsum loream","Lorem ipsum lore"); - TestSubscriber subscriber = TestSubscriber.create(); - - // when - StringObservable.stringConcat(sourceObservable) - .subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValues("Lorem ipsum loreamLorem ipsum lore"); - } - - - @Test - public void givenStringObservable_whenDecodingByteArray_ThenSuccessfullObtainingStringStream() - { - //given - Observable sourceObservable = Observable.just("Lorem ipsum loream".getBytes(StandardCharsets.UTF_8)); - TestSubscriber subscriber = TestSubscriber.create(); - - // when - StringObservable.decode(sourceObservable, StandardCharsets.UTF_8) - .subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValues("Lorem ipsum loream"); - } - - @Test - public void givenStringObservable_whenStringSplitted_ThenSuccessfullObtainingStringsStream() - { - //given - Observable sourceObservable = Observable.just("Lorem ipsum loream,Lorem ipsum lore"); - TestSubscriber subscriber = TestSubscriber.create(); - - // when - StringObservable.split(sourceObservable,",") - .subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(2); - subscriber.assertValues("Lorem ipsum loream", "Lorem ipsum lore"); - } - - @Test - public void givenStringObservable_whenSplittingByLine_ThenSuccessfullObtainingStringsStream() { - //given - Observable sourceObservable = Observable.just("Lorem ipsum loream\nLorem ipsum lore"); - TestSubscriber subscriber = TestSubscriber.create(); - - // when - StringObservable.byLine(sourceObservable) - .subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(2); - subscriber.assertValues("Lorem ipsum loream", "Lorem ipsum lore"); - } - - - @Test - public void givenStringObservable_whenJoiningStrings_ThenSuccessfullObtainingSingleString() { - //given - Observable sourceObservable = Observable.just("Lorem ipsum loream","Lorem ipsum lore"); - TestSubscriber subscriber = TestSubscriber.create(); - - // when - StringObservable.join(sourceObservable,",") - .subscribe(subscriber); - - // then - subscriber.assertCompleted(); - subscriber.assertNoErrors(); - subscriber.assertValueCount(1); - subscriber.assertValues("Lorem ipsum loream,Lorem ipsum lore"); - } - -} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsUnitTest.java new file mode 100644 index 0000000000..1ffc9b3ca2 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsUnitTest.java @@ -0,0 +1,145 @@ +package com.baeldung.rxjava.operators; + +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + +import org.junit.Assert; +import org.junit.Test; + +import rx.Observable; +import rx.observables.StringObservable; +import rx.observers.TestSubscriber; + + +public class RxStringOperatorsUnitTest +{ + + @Test + public void givenStringObservable_whenFromInputStream_ThenSuccessfull() + { + //given + ByteArrayInputStream is = new ByteArrayInputStream("Lorem ipsum loream, Lorem ipsum lore".getBytes(StandardCharsets.UTF_8)); + TestSubscriber subscriber = TestSubscriber.create(); + + // when + StringObservable.decode(StringObservable.from(is), StandardCharsets.UTF_8) + .subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValues("Lorem ipsum loream, Lorem ipsum lore"); + } + @Test + public void givenStringObservable_whenEncodingString_ThenSuccessfullObtainingByteStream() + { + //given + Observable sourceObservable = Observable.just("Lorem ipsum loream"); + TestSubscriber subscriber = TestSubscriber.create(); + + // when + StringObservable.encode(sourceObservable, StandardCharsets.UTF_8) + .subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.getOnNextEvents() + .stream() + .forEach(bytes -> Assert.assertTrue(Arrays.equals(bytes, "Lorem ipsum loream".getBytes(StandardCharsets.UTF_8)))); + } + + @Test + public void givenStringObservable_whenConcatenatingStrings_ThenSuccessfullObtainingSingleString() + { + //given + Observable sourceObservable = Observable.just("Lorem ipsum loream","Lorem ipsum lore"); + TestSubscriber subscriber = TestSubscriber.create(); + + // when + StringObservable.stringConcat(sourceObservable) + .subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValues("Lorem ipsum loreamLorem ipsum lore"); + } + + + @Test + public void givenStringObservable_whenDecodingByteArray_ThenSuccessfullObtainingStringStream() + { + //given + Observable sourceObservable = Observable.just("Lorem ipsum loream".getBytes(StandardCharsets.UTF_8)); + TestSubscriber subscriber = TestSubscriber.create(); + + // when + StringObservable.decode(sourceObservable, StandardCharsets.UTF_8) + .subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValues("Lorem ipsum loream"); + } + + @Test + public void givenStringObservable_whenStringSplitted_ThenSuccessfullObtainingStringsStream() + { + //given + Observable sourceObservable = Observable.just("Lorem ipsum loream,Lorem ipsum lore"); + TestSubscriber subscriber = TestSubscriber.create(); + + // when + StringObservable.split(sourceObservable,",") + .subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(2); + subscriber.assertValues("Lorem ipsum loream", "Lorem ipsum lore"); + } + + @Test + public void givenStringObservable_whenSplittingByLine_ThenSuccessfullObtainingStringsStream() { + //given + Observable sourceObservable = Observable.just("Lorem ipsum loream\nLorem ipsum lore"); + TestSubscriber subscriber = TestSubscriber.create(); + + // when + StringObservable.byLine(sourceObservable) + .subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(2); + subscriber.assertValues("Lorem ipsum loream", "Lorem ipsum lore"); + } + + + @Test + public void givenStringObservable_whenJoiningStrings_ThenSuccessfullObtainingSingleString() { + //given + Observable sourceObservable = Observable.just("Lorem ipsum loream","Lorem ipsum lore"); + TestSubscriber subscriber = TestSubscriber.create(); + + // when + StringObservable.join(sourceObservable,",") + .subscribe(subscriber); + + // then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValues("Lorem ipsum loream,Lorem ipsum lore"); + } + +} diff --git a/saas/pom.xml b/saas/pom.xml index bb951ceda8..2abc932497 100644 --- a/saas/pom.xml +++ b/saas/pom.xml @@ -37,20 +37,10 @@ - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - - org.codehaus.mojo exec-maven-plugin - 1.6.0 + ${exec-maven-plugin.version} java com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed @@ -74,11 +64,8 @@ - - 3.7.0 4.0.0 2.6.1 - 19.0 \ No newline at end of file diff --git a/saas/src/main/resources/logback.xml b/saas/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/saas/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spark-java/pom.xml b/spark-java/pom.xml index d8243345c5..ef33f4cbe0 100644 --- a/spark-java/pom.xml +++ b/spark-java/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.baeldung spark-java @@ -30,7 +29,6 @@ - UTF-8 2.5.4 2.8.0 diff --git a/spark-java/src/main/resources/logback.xml b/spark-java/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spark-java/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-4/README.md b/spring-4/README.md index 9855a9254d..4600a603ef 100644 --- a/spring-4/README.md +++ b/spring-4/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Guide to Flips For Spring](http://www.baeldung.com/guide-to-flips-for-spring/) - [A Guide to Flips for Spring](http://www.baeldung.com/flips-spring) +- [Configuring a Hikari Connection Pool with Spring Boot](https://www.baeldung.com/spring-boot-hikari) diff --git a/spring-4/pom.xml b/spring-4/pom.xml index c81469d3eb..cf10f64aa2 100644 --- a/spring-4/pom.xml +++ b/spring-4/pom.xml @@ -1,29 +1,45 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-4 spring-4 - 0.0.1-SNAPSHOT jar spring-4 - org.springframework.boot - spring-boot-starter-parent - 1.5.10.RELEASE - + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-1 org.springframework.boot spring-boot-starter-web - ${spring-boot-starter-web.version} + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.apache.tomcat + tomcat-jdbc + + + + + com.h2database + h2 + test + + + com.zaxxer + HikariCP + org.springframework.boot spring-boot-starter-test - ${spring-boot-starter-test.version} com.github.feature-flip @@ -34,7 +50,6 @@ org.projectlombok lombok - ${lombok.version} provided @@ -57,11 +72,10 @@ UTF-8 - 1.5.10.RELEASE - 1.5.9.RELEASE 1.0.1 1.16.18 1.8 + 1.4.197 diff --git a/spring-4/src/main/resources/logback.xml b/spring-4/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-4/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-4/src/test/java/com/baeldung/connectionpool/ApplicationWithHikariConnectionPool.java b/spring-4/src/test/java/com/baeldung/connectionpool/ApplicationWithHikariConnectionPool.java new file mode 100644 index 0000000000..0bd8637681 --- /dev/null +++ b/spring-4/src/test/java/com/baeldung/connectionpool/ApplicationWithHikariConnectionPool.java @@ -0,0 +1,12 @@ +package com.baeldung.connectionpool; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationWithHikariConnectionPool { + + public static void main(String[] args) { + SpringApplication.run(ApplicationWithHikariConnectionPool.class, args); + } +} diff --git a/spring-4/src/test/java/com/baeldung/connectionpool/HikariIntegrationTest.java b/spring-4/src/test/java/com/baeldung/connectionpool/HikariIntegrationTest.java new file mode 100644 index 0000000000..0cc876d5b1 --- /dev/null +++ b/spring-4/src/test/java/com/baeldung/connectionpool/HikariIntegrationTest.java @@ -0,0 +1,28 @@ +package com.baeldung.connectionpool; + +import static org.junit.Assert.*; + +import javax.sql.DataSource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest( + // instead of setting this property, we can exclude the dependency to org.apache.tomcat:tomcat-jdbc in pom.xml + properties = "spring.datasource.type=com.zaxxer.hikari.HikariDataSource") +public class HikariIntegrationTest { + + @Autowired + private DataSource dataSource; + + @Test + public void hikariConnectionPoolIsConfigured() { + assertEquals("com.zaxxer.hikari.HikariDataSource", dataSource.getClass() + .getName()); + } + +} diff --git a/spring-4/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java b/spring-4/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java new file mode 100644 index 0000000000..9dd4ef064a --- /dev/null +++ b/spring-4/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java @@ -0,0 +1,74 @@ +package com.baeldung.flips.controller; + +import org.hamcrest.Matchers; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +@RunWith(SpringRunner.class) +@SpringBootTest(properties = { + "feature.foo.by.id=Y", + "feature.new.foo=Y", + "last.active.after=2018-03-14T00:00:00Z", + "first.active.after=2999-03-15T00:00:00Z", + "logging.level.org.flips=info" + +}, webEnvironment = SpringBootTest.WebEnvironment.MOCK) +@AutoConfigureMockMvc +@ActiveProfiles("dev") +public class FlipControllerIntegrationTest { + + @Autowired private MockMvc mvc; + + @Test + public void givenValidDayOfWeek_APIAvailable() throws Exception { + mvc.perform(MockMvcRequestBuilders.get("/foo/1")) + .andExpect(MockMvcResultMatchers.status().is(200)) + .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo1"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(1))); + } + + @Test + public void givenValidDate_APIAvailable() throws Exception { + mvc.perform(MockMvcRequestBuilders.get("/foo/last")) + .andExpect(MockMvcResultMatchers.status().is(200)) + .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo6"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(6))); + } + + @Test + public void givenInvalidDate_APINotAvailable() throws Exception { + mvc.perform(MockMvcRequestBuilders.get("/foo/first")) + .andExpect(MockMvcResultMatchers.status().is(501)); + } + + @Test + public void givenCorrectProfile_APIAvailable() throws Exception { + mvc.perform(MockMvcRequestBuilders.get("/foos")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(6))); + } + + @Test + public void givenPropertySet_APIAvailable() throws Exception { + mvc.perform(MockMvcRequestBuilders.get("/foos/1")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo1"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(1))); + } + + @Test + public void getValidExpression_FlipBean() throws Exception { + mvc.perform(MockMvcRequestBuilders.get("/foo/new")) + .andExpect(MockMvcResultMatchers.status().is(200)) + .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Shiny New Foo!"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(100))); + } +} \ No newline at end of file diff --git a/spring-4/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java b/spring-4/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java deleted file mode 100644 index 8fd9c4e340..0000000000 --- a/spring-4/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.flips.controller; - -import org.hamcrest.Matchers; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; - -@RunWith(SpringRunner.class) -@SpringBootTest(properties = { - "feature.foo.by.id=Y", - "feature.new.foo=Y", - "last.active.after=2018-03-14T00:00:00Z", - "first.active.after=2999-03-15T00:00:00Z", - "logging.level.org.flips=info" - -}, webEnvironment = SpringBootTest.WebEnvironment.MOCK) -@AutoConfigureMockMvc -@ActiveProfiles("dev") -public class FlipControllerTest { - - @Autowired private MockMvc mvc; - - @Test - public void givenValidDayOfWeek_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/1")) - .andExpect(MockMvcResultMatchers.status().is(200)) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo1"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(1))); - } - - @Test - public void givenValidDate_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/last")) - .andExpect(MockMvcResultMatchers.status().is(200)) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo6"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(6))); - } - - @Test - public void givenInvalidDate_APINotAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/first")) - .andExpect(MockMvcResultMatchers.status().is(501)); - } - - @Test - public void givenCorrectProfile_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foos")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(6))); - } - - @Test - public void givenPropertySet_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foos/1")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo1"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(1))); - } - - @Test - public void getValidExpression_FlipBean() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/new")) - .andExpect(MockMvcResultMatchers.status().is(200)) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Shiny New Foo!"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(100))); - } -} \ No newline at end of file diff --git a/spring-5-data-reactive/README.md b/spring-5-data-reactive/README.md new file mode 100644 index 0000000000..f8886ac18b --- /dev/null +++ b/spring-5-data-reactive/README.md @@ -0,0 +1,8 @@ +## Spring Data Reactive Project + +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles +- [Reactive Flow with MongoDB, Kotlin, and Spring WebFlux](http://www.baeldung.com/kotlin-mongodb-spring-webflux) +- [Spring Data Reactive Repositories with MongoDB](http://www.baeldung.com/spring-data-mongodb-reactive) diff --git a/spring-5-data-reactive/pom.xml b/spring-5-data-reactive/pom.xml new file mode 100644 index 0000000000..e4dd454635 --- /dev/null +++ b/spring-5-data-reactive/pom.xml @@ -0,0 +1,206 @@ + + + 4.0.0 + spring-5-data-reactive + jar + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-mongodb-reactive + + + org.springframework.boot + spring-boot-starter-web + + + com.fasterxml.jackson.module + jackson-module-kotlin + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + + + org.jetbrains.kotlin + kotlin-reflect + + + org.projectlombok + lombok + + + io.projectreactor + reactor-test + test + + + org.jetbrains.kotlin + kotlin-test + ${kotlin.version} + test + + + io.reactivex.rxjava2 + rxjava + + + + org.springframework + spring-test + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.junit.jupiter + junit-jupiter-api + + + org.junit.jupiter + junit-jupiter-engine + 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 + + + kotlin-maven-plugin + ${kotlin-maven-plugin.version} + + + compile + + compile + + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/main/java + + + + + test-compile + + test-compile + + + + ${project.basedir}/src/test/kotlin + ${project.basedir}/src/test/java + + + + + org.jetbrains.kotlin + + + -Xjsr305=strict + + + spring + + 1.8 + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${java.version} + ${java.version} + + + + + default-compile + none + + + + default-testCompile + none + + + java-compile + compile + + compile + + + + java-test-compile + test-compile + + testCompile + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + methods + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*LiveTest.java + + + + + + + + UTF-8 + UTF-8 + 1.8 + 1.2.40 + 1.2.40 + 1.0.0 + 5.0.2 + + + diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java b/spring-5-data-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java new file mode 100644 index 0000000000..e96767145e --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java @@ -0,0 +1,25 @@ +package com.baeldung.reactive; + +import com.mongodb.reactivestreams.client.MongoClient; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.data.mongodb.core.ReactiveMongoTemplate; + +@SpringBootApplication +public class Spring5ReactiveApplication{ + + public static void main(String[] args) { + SpringApplication.run(Spring5ReactiveApplication.class, args); + } + + @Autowired + MongoClient mongoClient; + + @Bean + public ReactiveMongoTemplate reactiveMongoTemplate() { + return new ReactiveMongoTemplate(mongoClient, "test"); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/model/Account.java b/spring-5-data-reactive/src/main/java/com/baeldung/reactive/model/Account.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/model/Account.java rename to spring-5-data-reactive/src/main/java/com/baeldung/reactive/model/Account.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java b/spring-5-data-reactive/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java rename to spring-5-data-reactive/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java b/spring-5-data-reactive/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java rename to spring-5-data-reactive/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java b/spring-5-data-reactive/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java rename to spring-5-data-reactive/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java b/spring-5-data-reactive/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java rename to spring-5-data-reactive/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java diff --git a/spring-data-5-reactive/src/main/kotlin/com/baeldung/Application.kt b/spring-5-data-reactive/src/main/kotlin/com/baeldung/Application.kt similarity index 100% rename from spring-data-5-reactive/src/main/kotlin/com/baeldung/Application.kt rename to spring-5-data-reactive/src/main/kotlin/com/baeldung/Application.kt diff --git a/spring-data-5-reactive/src/main/kotlin/com/baeldung/Event.kt b/spring-5-data-reactive/src/main/kotlin/com/baeldung/Event.kt similarity index 100% rename from spring-data-5-reactive/src/main/kotlin/com/baeldung/Event.kt rename to spring-5-data-reactive/src/main/kotlin/com/baeldung/Event.kt diff --git a/spring-data-5-reactive/src/main/kotlin/com/baeldung/EventRepository.kt b/spring-5-data-reactive/src/main/kotlin/com/baeldung/EventRepository.kt similarity index 78% rename from spring-data-5-reactive/src/main/kotlin/com/baeldung/EventRepository.kt rename to spring-5-data-reactive/src/main/kotlin/com/baeldung/EventRepository.kt index a73ef8c807..e66af71ea6 100644 --- a/spring-data-5-reactive/src/main/kotlin/com/baeldung/EventRepository.kt +++ b/spring-5-data-reactive/src/main/kotlin/com/baeldung/EventRepository.kt @@ -4,6 +4,3 @@ import org.springframework.data.mongodb.core.mapping.Document import org.springframework.data.mongodb.repository.ReactiveMongoRepository interface EventRepository : ReactiveMongoRepository - -@Document -data class Event(val id: String, val name: String) diff --git a/spring-data-5-reactive/src/main/kotlin/com/baeldung/MongoConfig.kt b/spring-5-data-reactive/src/main/kotlin/com/baeldung/MongoConfig.kt similarity index 100% rename from spring-data-5-reactive/src/main/kotlin/com/baeldung/MongoConfig.kt rename to spring-5-data-reactive/src/main/kotlin/com/baeldung/MongoConfig.kt diff --git a/spring-data-5-reactive/src/main/kotlin/com/baeldung/SendEmitter.kt b/spring-5-data-reactive/src/main/kotlin/com/baeldung/SendEmitter.kt similarity index 100% rename from spring-data-5-reactive/src/main/kotlin/com/baeldung/SendEmitter.kt rename to spring-5-data-reactive/src/main/kotlin/com/baeldung/SendEmitter.kt diff --git a/spring-5-data-reactive/src/main/resources/logback.xml b/spring-5-data-reactive/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-5-data-reactive/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-data-5-reactive/src/main/resources/static/index.html b/spring-5-data-reactive/src/main/resources/static/index.html similarity index 100% rename from spring-data-5-reactive/src/main/resources/static/index.html rename to spring-5-data-reactive/src/main/resources/static/index.html diff --git a/spring-5-data-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java new file mode 100644 index 0000000000..f425826dce --- /dev/null +++ b/spring-5-data-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java @@ -0,0 +1,70 @@ +package com.baeldung.reactive.repository; + + +import com.baeldung.reactive.Spring5ReactiveApplication; +import com.baeldung.reactive.model.Account; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Spring5ReactiveApplication.class) +public class AccountCrudRepositoryIntegrationTest { + + @Autowired + AccountCrudRepository repository; + + @Test + public void givenValue_whenFindAllByValue_thenFindAccount() { + repository.save(new Account(null, "Bill", 12.3)).block(); + Flux accountFlux = repository.findAllByValue(12.3); + + StepVerifier.create(accountFlux) + .assertNext(account -> { + assertEquals("Bill", account.getOwner()); + assertEquals(Double.valueOf(12.3) , account.getValue()); + assertNotNull(account.getId()); + }) + .expectComplete() + .verify(); + } + + @Test + public void givenOwner_whenFindFirstByOwner_thenFindAccount() { + repository.save(new Account(null, "Bill", 12.3)).block(); + Mono accountMono = repository.findFirstByOwner(Mono.just("Bill")); + + StepVerifier.create(accountMono) + .assertNext(account -> { + assertEquals("Bill", account.getOwner()); + assertEquals(Double.valueOf(12.3) , account.getValue()); + assertNotNull(account.getId()); + }) + .expectComplete() + .verify(); + + + + } + + @Test + public void givenAccount_whenSave_thenSaveAccount() { + Mono accountMono = repository.save(new Account(null, "Bill", 12.3)); + + StepVerifier + .create(accountMono) + .assertNext(account -> assertNotNull(account.getId())) + .expectComplete() + .verify(); + } + + +} \ No newline at end of file diff --git a/spring-5-data-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java new file mode 100644 index 0000000000..bfa6a789b2 --- /dev/null +++ b/spring-5-data-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java @@ -0,0 +1,67 @@ +package com.baeldung.reactive.repository; + +import com.baeldung.reactive.Spring5ReactiveApplication; +import com.baeldung.reactive.model.Account; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.domain.Example; +import org.springframework.data.domain.ExampleMatcher; +import org.springframework.test.context.junit4.SpringRunner; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.startsWith; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Spring5ReactiveApplication.class) +public class AccountMongoRepositoryIntegrationTest { + + @Autowired + AccountMongoRepository repository; + + @Test + public void givenExample_whenFindAllWithExample_thenFindAllMacthings() { + repository.save(new Account(null, "john", 12.3)).block(); + ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("owner", startsWith()); + Example example = Example.of(new Account(null, "jo", null), matcher); + Flux accountFlux = repository.findAll(example); + + StepVerifier + .create(accountFlux) + .assertNext(account -> assertEquals("john", account.getOwner())) + .expectComplete() + .verify(); + } + + @Test + public void givenAccount_whenSave_thenSave() { + Mono accountMono = repository.save(new Account(null, "john", 12.3)); + + StepVerifier + .create(accountMono) + .assertNext(account -> assertNotNull(account.getId())) + .expectComplete() + .verify(); + } + + @Test + public void givenId_whenFindById_thenFindAccount() { + Account inserted = repository.save(new Account(null, "john", 12.3)).block(); + Mono accountMono = repository.findById(inserted.getId()); + + StepVerifier + .create(accountMono) + .assertNext(account -> { + assertEquals("john", account.getOwner()); + assertEquals(Double.valueOf(12.3), account.getValue()); + assertNotNull(account.getId()); + }) + .expectComplete() + .verify(); + } +} \ No newline at end of file diff --git a/spring-5-data-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java new file mode 100644 index 0000000000..e9b3eb1c40 --- /dev/null +++ b/spring-5-data-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java @@ -0,0 +1,58 @@ +package com.baeldung.reactive.repository; + +import com.baeldung.reactive.Spring5ReactiveApplication; +import com.baeldung.reactive.model.Account; +import io.reactivex.Observable; +import io.reactivex.Single; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Spring5ReactiveApplication.class) +public class AccountRxJavaRepositoryIntegrationTest { + + @Autowired + AccountRxJavaRepository repository; + + @Test + public void givenValue_whenFindAllByValue_thenFindAccounts() throws InterruptedException { + repository.save(new Account(null, "bruno", 12.3)).blockingGet(); + Observable accountObservable = repository.findAllByValue(12.3); + + accountObservable + .test() + .await() + .assertComplete() + .assertValueAt(0, account -> { + assertEquals("bruno", account.getOwner()); + assertEquals(Double.valueOf(12.3), account.getValue()); + return true; + }); + + } + + @Test + public void givenOwner_whenFindFirstByOwner_thenFindAccount() throws InterruptedException { + repository.save(new Account(null, "bruno", 12.3)).blockingGet(); + Single accountSingle = repository.findFirstByOwner(Single.just("bruno")); + + accountSingle + .test() + .await() + .assertComplete() + .assertValueAt(0, account -> { + assertEquals("bruno", account.getOwner()); + assertEquals(Double.valueOf(12.3), account.getValue()); + assertNotNull(account.getId()); + return true; + }); + + } + +} \ No newline at end of file diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java similarity index 100% rename from spring-5-reactive/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java rename to spring-5-data-reactive/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java diff --git a/spring-5-mvc/README.md b/spring-5-mvc/README.md index c031a9d10e..7e83077f54 100644 --- a/spring-5-mvc/README.md +++ b/spring-5-mvc/README.md @@ -1,2 +1,4 @@ ### Relevant Articles: - [Spring Boot and Kotlin](http://www.baeldung.com/spring-boot-kotlin) +- [Spring MVC Streaming and SSE Request Processing](https://www.baeldung.com/spring-mvc-sse-streams) +- [Overview and Need for DelegatingFilterProxy in Spring](https://www.baeldung.com/spring-delegating-filter-proxy) diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 06ddfb82d9..f5346a0fa0 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-5-mvc @@ -10,10 +10,10 @@ spring 5 MVC sample project about new features - org.springframework.boot - spring-boot-starter-parent - 2.0.0.M7 - + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 @@ -82,15 +82,10 @@ spring-boot-starter-test test - - junit - junit - test - com.jayway.restassured rest-assured - ${rest-assured.version} + ${jayway-rest-assured.version} test @@ -111,7 +106,7 @@ spring - 1.8 + ${java.version} @@ -137,49 +132,11 @@ - - org.apache.maven.plugins - maven-surefire-plugin - - - false - - **/*IntegrationTest.java - **/*LiveTest.java - - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - + - 2.9.0 - UTF-8 - UTF-8 - 1.8 - 5.0.2.RELEASE + 2.9.0 1.1.2 - diff --git a/spring-5-mvc/src/main/java/com/baeldung/Constants.java b/spring-5-mvc/src/main/java/com/baeldung/Constants.java new file mode 100644 index 0000000000..472f3280b7 --- /dev/null +++ b/spring-5-mvc/src/main/java/com/baeldung/Constants.java @@ -0,0 +1,21 @@ +package com.baeldung; + +public class Constants { + + public static final String GENERIC_EXCEPTION = "Exception encountered!"; + + /** + * API endpoints. + */ + public static final String API_RBE = "/rbe"; + public static final String API_SSE = "/sse"; + public static final String API_SRB = "/srb"; + + /** + * API Responses. + */ + public static final String API_RBE_MSG = "I Was Sent From a Response Body Emitter!"; + public static final String API_SSE_MSG = "I Was Sent From a Sse!"; + public static final String API_SRB_MSG = "I Was Sent From a Streaming Response Body!"; + +} diff --git a/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java b/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java index 41b5c1eed1..8251467122 100644 --- a/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java +++ b/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java @@ -1,7 +1,11 @@ package com.baeldung; +import javax.servlet.Filter; + import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.web.filter.DelegatingFilterProxy; +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; @SpringBootApplication public class Spring5Application { @@ -10,4 +14,31 @@ public class Spring5Application { SpringApplication.run(Spring5Application.class, args); } + public static class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + + @Override + protected Class[] getRootConfigClasses() { + return null; + } + + @Override + protected Class[] getServletConfigClasses() { + // TODO Auto-generated method stub + return null; + } + + @Override + protected String[] getServletMappings() { + // TODO Auto-generated method stub + return null; + } + + @Override + protected javax.servlet.Filter[] getServletFilters() { + DelegatingFilterProxy delegateFilterProxy = new DelegatingFilterProxy(); + delegateFilterProxy.setTargetBeanName("loggingFilter"); + return new Filter[] { delegateFilterProxy }; + } + } + } diff --git a/spring-5-mvc/src/main/java/com/baeldung/model/Foo.java b/spring-5-mvc/src/main/java/com/baeldung/model/Foo.java index a9ffee14da..b06f50b742 100644 --- a/spring-5-mvc/src/main/java/com/baeldung/model/Foo.java +++ b/spring-5-mvc/src/main/java/com/baeldung/model/Foo.java @@ -49,8 +49,6 @@ public class Foo { this.name = name; } - // - @Override public int hashCode() { final int prime = 31; diff --git a/spring-5-mvc/src/main/java/com/baeldung/persistence/DataSetupBean.java b/spring-5-mvc/src/main/java/com/baeldung/persistence/DataSetupBean.java index cf78977961..fa07555bba 100644 --- a/spring-5-mvc/src/main/java/com/baeldung/persistence/DataSetupBean.java +++ b/spring-5-mvc/src/main/java/com/baeldung/persistence/DataSetupBean.java @@ -16,8 +16,6 @@ public class DataSetupBean implements InitializingBean { @Autowired private FooRepository repo; - // - @Override public void afterPropertiesSet() throws Exception { IntStream.range(1, 5).forEach(i -> repo.save(new Foo(randomAlphabetic(8)))); diff --git a/spring-5-mvc/src/main/java/com/baeldung/spring/filter/CustomFilter.java b/spring-5-mvc/src/main/java/com/baeldung/spring/filter/CustomFilter.java new file mode 100644 index 0000000000..4aa33cd749 --- /dev/null +++ b/spring-5-mvc/src/main/java/com/baeldung/spring/filter/CustomFilter.java @@ -0,0 +1,38 @@ +package com.baeldung.spring.filter; + +import java.io.IOException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component("loggingFilter") +public class CustomFilter implements Filter { + + private static Logger LOGGER = LoggerFactory.getLogger(CustomFilter.class); + + @Override + public void init(FilterConfig config) throws ServletException { + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletRequest req = (HttpServletRequest) request; + LOGGER.info("Request Info : " + req); + chain.doFilter(request, response); + } + + @Override + public void destroy() { + // cleanup code, if necessary + } +} diff --git a/spring-5-mvc/src/main/java/com/baeldung/web/ResponseBodyEmitterController.java b/spring-5-mvc/src/main/java/com/baeldung/web/ResponseBodyEmitterController.java new file mode 100644 index 0000000000..c5f63486fe --- /dev/null +++ b/spring-5-mvc/src/main/java/com/baeldung/web/ResponseBodyEmitterController.java @@ -0,0 +1,35 @@ +package com.baeldung.web; + +import com.baeldung.Constants; +import java.util.Date; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter; + +@Controller +public class ResponseBodyEmitterController { + private ExecutorService nonBlockingService = Executors.newCachedThreadPool(); + + @GetMapping(Constants.API_RBE) + public ResponseEntity handleRbe() { + ResponseBodyEmitter emitter = new ResponseBodyEmitter(); + + nonBlockingService.execute(() -> { + try { + emitter.send(Constants.API_RBE_MSG + " @ " + new Date(), MediaType.TEXT_PLAIN); + emitter.complete(); + } catch (Exception ex) { + System.out.println(Constants.GENERIC_EXCEPTION); + emitter.completeWithError(ex); + } + }); + + return new ResponseEntity(emitter, HttpStatus.OK); + } + +} diff --git a/spring-5-mvc/src/main/java/com/baeldung/web/SseEmitterController.java b/spring-5-mvc/src/main/java/com/baeldung/web/SseEmitterController.java new file mode 100644 index 0000000000..00113c5ff7 --- /dev/null +++ b/spring-5-mvc/src/main/java/com/baeldung/web/SseEmitterController.java @@ -0,0 +1,59 @@ +package com.baeldung.web; + +import java.time.LocalTime; +import java.util.Date; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter.SseEventBuilder; + +import com.baeldung.Constants; + +@Controller +public class SseEmitterController { + private ExecutorService nonBlockingService = Executors.newCachedThreadPool(); + + @GetMapping(Constants.API_SSE) + public SseEmitter handleSse() { + SseEmitter emitter = new SseEmitter(); + + nonBlockingService.execute(() -> { + try { + emitter.send(Constants.API_SSE_MSG + " @ " + new Date()); + emitter.complete(); + } catch (Exception ex) { + System.out.println(Constants.GENERIC_EXCEPTION); + emitter.completeWithError(ex); + } + }); + + return emitter; + } + + @GetMapping("/stream-sse-mvc") + public SseEmitter streamSseMvc() { + SseEmitter emitter = new SseEmitter(); + ExecutorService sseMvcExecutor = Executors.newSingleThreadExecutor(); + + sseMvcExecutor.execute(() -> { + try { + for (int i = 0; true; i++) { + SseEventBuilder event = SseEmitter.event() + .data("SSE MVC - " + LocalTime.now() + .toString()) + .id(String.valueOf(i)) + .name("sse event - mvc"); + emitter.send(event); + Thread.sleep(1000); + } + } catch (Exception ex) { + emitter.completeWithError(ex); + } + }); + return emitter; + } + +} diff --git a/spring-5-mvc/src/main/java/com/baeldung/web/StreamingResponseBodyController.java b/spring-5-mvc/src/main/java/com/baeldung/web/StreamingResponseBodyController.java new file mode 100644 index 0000000000..1722ad85cd --- /dev/null +++ b/spring-5-mvc/src/main/java/com/baeldung/web/StreamingResponseBodyController.java @@ -0,0 +1,23 @@ +package com.baeldung.web; + +import com.baeldung.Constants; +import java.util.Date; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; + +@Controller +public class StreamingResponseBodyController { + + @GetMapping(Constants.API_SRB) + public ResponseEntity handleRbe() { + StreamingResponseBody stream = out -> { + String msg = Constants.API_SRB_MSG + " @ " + new Date(); + out.write(msg.getBytes()); + }; + return new ResponseEntity(stream, HttpStatus.OK); + } + +} diff --git a/spring-5-mvc/src/main/resources/logback.xml b/spring-5-mvc/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-5-mvc/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-5-mvc/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-5-mvc/src/main/webapp/WEB-INF/jsp/index.jsp new file mode 100644 index 0000000000..df5baf7adb --- /dev/null +++ b/spring-5-mvc/src/main/webapp/WEB-INF/jsp/index.jsp @@ -0,0 +1,86 @@ +<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %> +<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %> + + + + + + + Spring MVC Async + " rel="stylesheet"> + + +
    +

    Spring MVC Async

    +
    +
    +
    +
    + + + diff --git a/spring-5-mvc/src/main/webapp/WEB-INF/web.xml b/spring-5-mvc/src/main/webapp/WEB-INF/web.xml index bfcf43dad2..43c7143e5b 100644 --- a/spring-5-mvc/src/main/webapp/WEB-INF/web.xml +++ b/spring-5-mvc/src/main/webapp/WEB-INF/web.xml @@ -16,6 +16,14 @@ functional / + + loggingFilter + org.springframework.web.filter.DelegatingFilterProxy + + + loggingFilter + /* + \ No newline at end of file diff --git a/spring-5-reactive-client/README.md b/spring-5-reactive-client/README.md index 400e343263..f94bd0b0c1 100644 --- a/spring-5-reactive-client/README.md +++ b/spring-5-reactive-client/README.md @@ -4,12 +4,3 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles - -- [Concurrent Test Execution in Spring 5](http://www.baeldung.com/spring-5-concurrent-tests) -- [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) -- [The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5](http://www.baeldung.com/spring-5-junit-config) -- [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) -- [Spring 5 Testing with @EnabledIf Annotation](https://github.com/eugenp/tutorials/tree/master/spring-5) diff --git a/spring-5-reactive-client/pom.xml b/spring-5-reactive-client/pom.xml index e9e7c7c3e3..6e39743ed0 100644 --- a/spring-5-reactive-client/pom.xml +++ b/spring-5-reactive-client/pom.xml @@ -1,19 +1,18 @@ - + 4.0.0 - com.baeldung spring-5-reactive-client - 0.0.1-SNAPSHOT jar spring-5-reactive-client spring 5 sample project about new features - org.springframework.boot - spring-boot-starter-parent - 2.0.0.M7 - + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 @@ -42,20 +41,6 @@ javax.json.bind javax.json.bind-api - - - - - - - - - - - - - - org.apache.geronimo.specs geronimo-json_1.1_spec @@ -101,37 +86,10 @@ test - - org.junit.jupiter - junit-jupiter-api - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - test - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - - org.projectlombok lombok - - org.apache.commons - commons-lang3 - - @@ -144,53 +102,10 @@ JAR - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - methods - true - - **/*IntegrationTest.java - **/*LiveTest.java - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - UTF-8 - UTF-8 - 1.8 - 1.0.0 - 5.0.0 - 2.20 - 5.0.2.RELEASE 1.0.1.RELEASE 1.1.3 1.0 diff --git a/spring-5-reactive-client/src/main/resources/logback.xml b/spring-5-reactive-client/src/main/resources/logback.xml index 8bbe8c1d67..7072369b8d 100644 --- a/spring-5-reactive-client/src/main/resources/logback.xml +++ b/spring-5-reactive-client/src/main/resources/logback.xml @@ -3,7 +3,7 @@ # Pattern of log message for console appender - %d{yyyy-MM-dd HH:mm:ss} %-5p %m%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-5-reactive-client/src/test/resources/logback-test.xml b/spring-5-reactive-client/src/test/resources/logback-test.xml index 8bbe8c1d67..7072369b8d 100644 --- a/spring-5-reactive-client/src/test/resources/logback-test.xml +++ b/spring-5-reactive-client/src/test/resources/logback-test.xml @@ -3,7 +3,7 @@ # Pattern of log message for console appender - %d{yyyy-MM-dd HH:mm:ss} %-5p %m%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-5-reactive-functional/src/main/resources/logback.xml b/spring-5-reactive-functional/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-5-reactive-functional/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/jsonb/.gitignore b/spring-5-reactive-security/.gitignore similarity index 100% rename from jsonb/.gitignore rename to spring-5-reactive-security/.gitignore diff --git a/spring-5-reactive-security/README.md b/spring-5-reactive-security/README.md new file mode 100644 index 0000000000..3395cf5562 --- /dev/null +++ b/spring-5-reactive-security/README.md @@ -0,0 +1,11 @@ +## Spring 5 Reactive Security Examples + +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles + +- [Spring Boot Actuator](http://www.baeldung.com/spring-boot-actuators) +- [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) +- [Guide to Spring 5 WebFlux](http://www.baeldung.com/spring-webflux) + diff --git a/spring-5-reactive-security/pom.xml b/spring-5-reactive-security/pom.xml new file mode 100644 index 0000000000..3b64b9b3ac --- /dev/null +++ b/spring-5-reactive-security/pom.xml @@ -0,0 +1,135 @@ + + + 4.0.0 + + com.baeldung + spring-5-reactive-security + 0.0.1-SNAPSHOT + jar + spring-5-reactive-security + spring 5 security sample project about new features + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-tomcat + + + org.springframework.boot + spring-boot-starter-webflux + + + org.projectreactor + reactor-spring + ${reactor-spring.version} + + + javax.json.bind + javax.json.bind-api + + + org.springframework.boot + spring-boot-starter-actuator + + + org.projectlombok + lombok + compile + + + org.apache.geronimo.specs + geronimo-json_1.1_spec + ${geronimo-json_1.1_spec.version} + + + org.apache.johnzon + johnzon-jsonb + + + + org.apache.commons + commons-lang3 + + + + + + org.springframework.boot + spring-boot-devtools + runtime + + + org.springframework + spring-test + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + test + + + + io.reactivex.rxjava2 + rxjava + ${rxjava-version} + + + io.projectreactor + reactor-test + ${project-reactor-test} + test + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.security + spring-security-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.webflux.EmployeeSpringApplication + JAR + + + + + + + 1.0.1.RELEASE + 2.1.12 + 1.1.3 + 1.0 + 1.0 + 4.1 + 3.1.6.RELEASE + + + diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/FeaturesEndpoint.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/FeaturesEndpoint.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/FeaturesEndpoint.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/FeaturesEndpoint.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/InfoWebEndpointExtension.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/InfoWebEndpointExtension.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/InfoWebEndpointExtension.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/InfoWebEndpointExtension.java diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java new file mode 100644 index 0000000000..f07ddfb0f7 --- /dev/null +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.reactive.actuator; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +public class Spring5ReactiveApplication{ + + public static void main(String[] args) { + SpringApplication.run(Spring5ReactiveApplication.class, args); + } + +} diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java new file mode 100644 index 0000000000..07f805fea4 --- /dev/null +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java @@ -0,0 +1,28 @@ +package com.baeldung.reactive.actuator; + +import org.springframework.boot.actuate.autoconfigure.security.reactive.EndpointRequest; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; + +@Configuration +@EnableWebFluxSecurity +public class WebSecurityConfig { + + + @Bean + public SecurityWebFilterChain securitygWebFilterChain( + ServerHttpSecurity http) { + return http + + .authorizeExchange() + .matchers(EndpointRequest.to( + FeaturesEndpoint.class + )).permitAll().anyExchange().permitAll().and().csrf().disable().build(); + } + +} diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeFunctionalConfig.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeFunctionalConfig.java new file mode 100644 index 0000000000..8d7860ccdc --- /dev/null +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeFunctionalConfig.java @@ -0,0 +1,75 @@ +package com.baeldung.reactive.functional; + +import static org.springframework.web.reactive.function.BodyExtractors.toMono; +import static org.springframework.web.reactive.function.server.RequestPredicates.GET; +import static org.springframework.web.reactive.function.server.RequestPredicates.POST; +import static org.springframework.web.reactive.function.server.RouterFunctions.route; +import static org.springframework.web.reactive.function.server.ServerResponse.ok; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.webflux.Employee; +import com.baeldung.webflux.EmployeeRepository; + +@Configuration +public class EmployeeFunctionalConfig { + + @Bean + EmployeeRepository employeeRepository() { + return new EmployeeRepository(); + } + + @Bean + RouterFunction getAllEmployeesRoute() { + return route(GET("/employees"), + req -> ok().body( + employeeRepository().findAllEmployees(), Employee.class)); + } + + @Bean + RouterFunction getEmployeeByIdRoute() { + return route(GET("/employees/{id}"), + req -> ok().body( + employeeRepository().findEmployeeById(req.pathVariable("id")), Employee.class)); + } + + @Bean + RouterFunction updateEmployee() { + return route(POST("/employees/update"), + req -> req.body(toMono(Employee.class)) + .doOnNext(employeeRepository()::updateEmployee) + .then(ok().build())); + } + + @Bean + RouterFunction composedRoutes() { + return + route(GET("/employees"), + req -> ok().body( + employeeRepository().findAllEmployees(), Employee.class)) + + .and(route(GET("/employees/{id}"), + req -> ok().body( + employeeRepository().findEmployeeById(req.pathVariable("id")), Employee.class))) + + .and(route(POST("/employees/update"), + req -> req.body(toMono(Employee.class)) + .doOnNext(employeeRepository()::updateEmployee) + .then(ok().build()))); + } + + @Bean + public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http.csrf() + .disable() + .authorizeExchange() + .anyExchange() + .permitAll(); + return http.build(); + } +} diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalApplication.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalApplication.java new file mode 100644 index 0000000000..1f2bd871fc --- /dev/null +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.reactive.functional; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class EmployeeSpringFunctionalApplication { + + public static void main(String[] args) { + SpringApplication.run(EmployeeSpringFunctionalApplication.class, args); + } + +} diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/GreetController.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/GreetController.java new file mode 100644 index 0000000000..99b79d88ea --- /dev/null +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/GreetController.java @@ -0,0 +1,37 @@ +package com.baeldung.reactive.security; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Mono; + +import java.security.Principal; + +@RestController +public class GreetController { + + private GreetService greetService; + + public GreetController(GreetService greetService) { + this.greetService = greetService; + } + + @GetMapping("/") + public Mono greet(Mono principal) { + return principal + .map(Principal::getName) + .map(name -> String.format("Hello, %s", name)); + } + + @GetMapping("/admin") + public Mono greetAdmin(Mono principal) { + return principal + .map(Principal::getName) + .map(name -> String.format("Admin access: %s", name)); + } + + @GetMapping("/greetService") + public Mono greetService() { + return greetService.greet(); + } + +} diff --git a/spring-5/src/main/java/com/baeldung/security/GreetService.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/GreetService.java similarity index 88% rename from spring-5/src/main/java/com/baeldung/security/GreetService.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/GreetService.java index 7622b360be..93df64bced 100644 --- a/spring-5/src/main/java/com/baeldung/security/GreetService.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/GreetService.java @@ -1,4 +1,4 @@ -package com.baeldung.security; +package com.baeldung.reactive.security; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SecurityConfig.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SecurityConfig.java new file mode 100644 index 0000000000..225f78b3f7 --- /dev/null +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SecurityConfig.java @@ -0,0 +1,60 @@ +package com.baeldung.reactive.security; + +import org.springframework.boot.actuate.autoconfigure.security.reactive.EndpointRequest; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity; +import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.server.SecurityWebFilterChain; + +import com.baeldung.reactive.actuator.FeaturesEndpoint; + +@EnableWebFluxSecurity +@EnableReactiveMethodSecurity +public class SecurityConfig { + + @Bean + public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) { + return http.authorizeExchange() + .pathMatchers("/", "/admin") + .hasAuthority("ROLE_ADMIN") + .matchers(EndpointRequest.to(FeaturesEndpoint.class)) + .permitAll() + .anyExchange() + .permitAll() + .and() + .formLogin() + .and() + .csrf() + .disable() + .build(); + } + + @Bean + public MapReactiveUserDetailsService userDetailsService() { + UserDetails user = User + .withUsername("user") + .password(passwordEncoder().encode("password")) + .roles("USER") + .build(); + + UserDetails admin = User + .withUsername("admin") + .password(passwordEncoder().encode("password")) + .roles("ADMIN") + .build(); + + return new MapReactiveUserDetailsService(user, admin); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + +} diff --git a/spring-5/src/main/java/com/baeldung/SpringSecurity5Application.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java similarity index 92% rename from spring-5/src/main/java/com/baeldung/SpringSecurity5Application.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java index 02c91a1879..f2963c4fa5 100644 --- a/spring-5/src/main/java/com/baeldung/SpringSecurity5Application.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.reactive.security; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -11,7 +11,7 @@ import org.springframework.web.server.adapter.WebHttpHandlerBuilder; import reactor.ipc.netty.NettyContext; import reactor.ipc.netty.http.server.HttpServer; -@ComponentScan(basePackages = {"com.baeldung.security"}) +@ComponentScan(basePackages = {"com.baeldung.reactive.security"}) @EnableWebFlux public class SpringSecurity5Application { diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/webflux/Employee.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/Employee.java new file mode 100644 index 0000000000..bbdf85d293 --- /dev/null +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/Employee.java @@ -0,0 +1,17 @@ +package com.baeldung.webflux; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class Employee { + + private String id; + private String name; + + // standard getters and setters + +} diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeConfig.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeConfig.java new file mode 100644 index 0000000000..6e73004650 --- /dev/null +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeConfig.java @@ -0,0 +1,33 @@ +package com.baeldung.webflux; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.reactive.HandlerMapping; +import org.springframework.web.reactive.config.EnableWebFlux; +import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; +import org.springframework.web.reactive.socket.WebSocketHandler; +import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter; + +@Configuration +@EnableWebFlux +public class EmployeeConfig { + + @Bean + public HandlerMapping handlerMapping() { + Map map = new HashMap<>(); + map.put("/employee-feed", new EmployeeWebSocketHandler()); + + SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); + mapping.setUrlMap(map); + mapping.setOrder(10); + return mapping; + } + + @Bean + public WebSocketHandlerAdapter handlerAdapter() { + return new WebSocketHandlerAdapter(); + } +} diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeController.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeController.java new file mode 100644 index 0000000000..34e44afc8b --- /dev/null +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeController.java @@ -0,0 +1,38 @@ +package com.baeldung.webflux; + +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.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@RestController +@RequestMapping("/employees") +public class EmployeeController { + + private EmployeeRepository employeeRepository; + + public EmployeeController(EmployeeRepository employeeRepository) { + this.employeeRepository = employeeRepository; + } + + @GetMapping("/{id}") + private Mono getEmployeeById(@PathVariable String id) { + return employeeRepository.findEmployeeById(id); + } + + @GetMapping + private Flux getAllEmployees() { + return employeeRepository.findAllEmployees(); + } + + @PostMapping("/update") + private Mono updateEmployee(@RequestBody Employee employee) { + return employeeRepository.updateEmployee(employee); + } + +} diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeCreationEvent.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeCreationEvent.java new file mode 100644 index 0000000000..d4f9a4fb02 --- /dev/null +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeCreationEvent.java @@ -0,0 +1,15 @@ +package com.baeldung.webflux; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +public class EmployeeCreationEvent { + private String employeeId; + private String creationTime; + public EmployeeCreationEvent(String employeeId, String creationTime) { + super(); + this.employeeId = employeeId; + this.creationTime = creationTime; + } +} diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeRepository.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeRepository.java new file mode 100644 index 0000000000..d7f618f178 --- /dev/null +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeRepository.java @@ -0,0 +1,64 @@ +package com.baeldung.webflux; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.stereotype.Repository; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@Repository +public class EmployeeRepository { + + static Map employeeData; + + static Map employeeAccessData; + + static + { + employeeData = new HashMap<>(); + employeeData.put("1",new Employee("1","Employee 1")); + employeeData.put("2",new Employee("2","Employee 2")); + employeeData.put("3",new Employee("3","Employee 3")); + employeeData.put("4",new Employee("4","Employee 4")); + employeeData.put("5",new Employee("5","Employee 5")); + employeeData.put("6",new Employee("6","Employee 6")); + employeeData.put("7",new Employee("7","Employee 7")); + employeeData.put("8",new Employee("8","Employee 8")); + employeeData.put("9",new Employee("9","Employee 9")); + employeeData.put("10",new Employee("10","Employee 10")); + + employeeAccessData=new HashMap<>(); + employeeAccessData.put("1", "Employee 1 Access Key"); + employeeAccessData.put("2", "Employee 2 Access Key"); + employeeAccessData.put("3", "Employee 3 Access Key"); + employeeAccessData.put("4", "Employee 4 Access Key"); + employeeAccessData.put("5", "Employee 5 Access Key"); + employeeAccessData.put("6", "Employee 6 Access Key"); + employeeAccessData.put("7", "Employee 7 Access Key"); + employeeAccessData.put("8", "Employee 8 Access Key"); + employeeAccessData.put("9", "Employee 9 Access Key"); + employeeAccessData.put("10", "Employee 10 Access Key"); + } + + public Mono findEmployeeById(String id) + { + return Mono.just(employeeData.get(id)); + } + + public Flux findAllEmployees() + { + return Flux.fromIterable(employeeData.values()); + } + + public Mono updateEmployee(Employee employee) + { + Employee existingEmployee=employeeData.get(employee.getId()); + if(existingEmployee!=null) + { + existingEmployee.setName(employee.getName()); + } + return Mono.just(existingEmployee); + } +} diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeSpringApplication.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeSpringApplication.java new file mode 100644 index 0000000000..2652c36695 --- /dev/null +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeSpringApplication.java @@ -0,0 +1,17 @@ +package com.baeldung.webflux; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class EmployeeSpringApplication { + + public static void main(String[] args) { + + SpringApplication.run(EmployeeSpringApplication.class, args); + + EmployeeWebClient employeeWebClient = new EmployeeWebClient(); + employeeWebClient.consume(); + } + +} diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebClient.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebClient.java new file mode 100644 index 0000000000..eb32408a7f --- /dev/null +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebClient.java @@ -0,0 +1,28 @@ +package com.baeldung.webflux; + +import org.springframework.web.reactive.function.client.WebClient; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public class EmployeeWebClient { + + WebClient client = WebClient.create("http://localhost:8080"); + + public void consume() { + + Mono employeeMono = client.get() + .uri("/employees/{id}", "1") + .retrieve() + .bodyToMono(Employee.class); + + employeeMono.subscribe(System.out::println); + + Flux employeeFlux = client.get() + .uri("/employees") + .retrieve() + .bodyToFlux(Employee.class); + + employeeFlux.subscribe(System.out::println); + } +} \ No newline at end of file diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSecurityConfig.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSecurityConfig.java new file mode 100644 index 0000000000..75475a0f08 --- /dev/null +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSecurityConfig.java @@ -0,0 +1,46 @@ +package com.baeldung.webflux; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.server.SecurityWebFilterChain; + +@EnableWebFluxSecurity +public class EmployeeWebSecurityConfig { + + @Bean + public MapReactiveUserDetailsService userDetailsService() { + UserDetails user = User + .withUsername("admin") + .password(passwordEncoder().encode("password")) + .roles("ADMIN") + .build(); + return new MapReactiveUserDetailsService(user); + } + + @Bean + public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http.csrf() + .disable() + .authorizeExchange() + .pathMatchers(HttpMethod.POST, "/employees/update") + .hasRole("ADMIN") + .pathMatchers("/**") + .permitAll() + .and() + .httpBasic(); + return http.build(); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketClient.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketClient.java new file mode 100644 index 0000000000..feb1eb62fb --- /dev/null +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketClient.java @@ -0,0 +1,21 @@ +package com.baeldung.webflux; + +import java.net.URI; + +import org.springframework.web.reactive.socket.WebSocketMessage; +import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient; +import org.springframework.web.reactive.socket.client.WebSocketClient; + +public class EmployeeWebSocketClient { + + public static void main(String[] args) { + + WebSocketClient client = new ReactorNettyWebSocketClient(); + + client.execute(URI.create("ws://localhost:8080/employee-feed"), session -> session.receive() + .map(WebSocketMessage::getPayloadAsText) + .doOnNext(System.out::println) + .then()) + .block(); // to subscribe and return the value + } +} diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketHandler.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketHandler.java new file mode 100644 index 0000000000..40b7b760ee --- /dev/null +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketHandler.java @@ -0,0 +1,39 @@ +package com.baeldung.webflux; + +import static java.time.LocalDateTime.now; +import static java.util.UUID.randomUUID; + +import java.time.Duration; + +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.socket.WebSocketHandler; +import org.springframework.web.reactive.socket.WebSocketSession; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@Component("EmployeeWebSocketHandler") +public class EmployeeWebSocketHandler implements WebSocketHandler { + + ObjectMapper om = new ObjectMapper(); + + @Override + public Mono handle(WebSocketSession webSocketSession) { + + Flux employeeCreationEvent = Flux.generate(sink -> { + EmployeeCreationEvent event = new EmployeeCreationEvent(randomUUID().toString(), now().toString()); + try { + sink.next(om.writeValueAsString(event)); + } catch (JsonProcessingException e) { + sink.error(e); + } + }); + + return webSocketSession.send(employeeCreationEvent + .map(webSocketSession::textMessage) + .delayElements(Duration.ofSeconds(1))); + } +} diff --git a/spring-5-reactive-security/src/main/resources/application.properties b/spring-5-reactive-security/src/main/resources/application.properties new file mode 100644 index 0000000000..234834b894 --- /dev/null +++ b/spring-5-reactive-security/src/main/resources/application.properties @@ -0,0 +1,5 @@ +logging.level.root=INFO + +management.endpoints.web.exposure.include.=* + +info.app.name=Spring Boot 2 actuator Application diff --git a/spring-5-reactive-security/src/main/resources/files/hello.txt b/spring-5-reactive-security/src/main/resources/files/hello.txt new file mode 100644 index 0000000000..b6fc4c620b --- /dev/null +++ b/spring-5-reactive-security/src/main/resources/files/hello.txt @@ -0,0 +1 @@ +hello \ No newline at end of file diff --git a/spring-5-reactive-security/src/main/resources/files/test/test.txt b/spring-5-reactive-security/src/main/resources/files/test/test.txt new file mode 100644 index 0000000000..30d74d2584 --- /dev/null +++ b/spring-5-reactive-security/src/main/resources/files/test/test.txt @@ -0,0 +1 @@ +test \ No newline at end of file diff --git a/spring-5-reactive-security/src/main/resources/logback.xml b/spring-5-reactive-security/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-5-reactive-security/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-5-reactive-security/src/main/resources/static/client-websocket.html b/spring-5-reactive-security/src/main/resources/static/client-websocket.html new file mode 100644 index 0000000000..3f840e8bd4 --- /dev/null +++ b/spring-5-reactive-security/src/main/resources/static/client-websocket.html @@ -0,0 +1,34 @@ + + + + +Baeldung: Spring 5 Reactive Client WebSocket (Browser) + + + +
    + + + \ No newline at end of file diff --git a/spring-5-reactive-security/src/main/webapp/WEB-INF/web.xml b/spring-5-reactive-security/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..bfcf43dad2 --- /dev/null +++ b/spring-5-reactive-security/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,21 @@ + + + + Spring Functional Application + + + functional + com.baeldung.functional.RootServlet + 1 + true + + + functional + / + + + + \ No newline at end of file diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java similarity index 95% rename from spring-5-reactive/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java rename to spring-5-reactive-security/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java index 3020e86723..94979a18ca 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java +++ b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java @@ -9,8 +9,6 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.reactive.Spring5ReactiveApplication; - import java.io.IOException; import static org.junit.Assert.assertEquals; diff --git a/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java new file mode 100644 index 0000000000..1197820066 --- /dev/null +++ b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java @@ -0,0 +1,28 @@ +package com.baeldung.reactive.functional; + +import org.junit.Test; +import org.springframework.test.web.reactive.server.WebTestClient; + +import com.baeldung.webflux.Employee; + +public class EmployeeSpringFunctionalIntegrationTest { + + private static EmployeeFunctionalConfig config = new EmployeeFunctionalConfig(); + + @Test + public void givenEmployeeId_whenGetEmployeeById_thenCorrectEmployee() { + WebTestClient client = WebTestClient + .bindToRouterFunction(config.getEmployeeByIdRoute()) + .build(); + + Employee expected = new Employee("1", "Employee 1"); + + client.get() + .uri("/employees/1") + .exchange() + .expectStatus() + .isOk() + .expectBody(Employee.class) + .isEqualTo(expected); + } +} diff --git a/spring-5-reactive-security/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java new file mode 100644 index 0000000000..3dc832d781 --- /dev/null +++ b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java @@ -0,0 +1,76 @@ +package com.baeldung.reactive.webflux; + +import static org.mockito.BDDMockito.given; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; + +import com.baeldung.reactive.actuator.Spring5ReactiveApplication; +import com.baeldung.webflux.Employee; +import com.baeldung.webflux.EmployeeRepository; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes=Spring5ReactiveApplication.class) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class EmployeeControllerIntegrationTest { + + @Autowired + private WebTestClient testClient; + + @MockBean + private EmployeeRepository employeeRepository; + + @Test + public void givenEmployeeId_whenGetEmployeeById_thenCorrectEmployee() { + + Employee employee = new Employee("1", "Employee 1 Name"); + + given(employeeRepository.findEmployeeById("1")).willReturn(Mono.just(employee)); + testClient.get() + .uri("/employees/1") + .exchange() + .expectStatus() + .isOk() + .expectBody(Employee.class) + .isEqualTo(employee); + } + + @Test + public void whenGetAllEmployees_thenCorrectEmployees() { + + List employeeList = new ArrayList<>(); + + Employee employee1 = new Employee("1", "Employee 1 Name"); + Employee employee2 = new Employee("2", "Employee 2 Name"); + Employee employee3 = new Employee("3", "Employee 3 Name"); + + employeeList.add(employee1); + employeeList.add(employee2); + employeeList.add(employee3); + + Flux employeeFlux = Flux.fromIterable(employeeList); + + given(employeeRepository.findAllEmployees()).willReturn(employeeFlux); + testClient.get() + .uri("/employees") + .exchange() + .expectStatus() + .isOk() + .expectBodyList(Employee.class) + .hasSize(3) + .isEqualTo(employeeList); + } +} diff --git a/spring-5/src/test/java/com/baeldung/security/SecurityIntegrationTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/security/SecurityIntegrationTest.java similarity index 92% rename from spring-5/src/test/java/com/baeldung/security/SecurityIntegrationTest.java rename to spring-5-reactive-security/src/test/java/com/baeldung/security/SecurityIntegrationTest.java index 5680625496..423500e09c 100644 --- a/spring-5/src/test/java/com/baeldung/security/SecurityIntegrationTest.java +++ b/spring-5-reactive-security/src/test/java/com/baeldung/security/SecurityIntegrationTest.java @@ -1,7 +1,7 @@ package com.baeldung.security; -import com.baeldung.SpringSecurity5Application; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -11,6 +11,8 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; +import com.baeldung.reactive.security.SpringSecurity5Application; + @RunWith(SpringRunner.class) @ContextConfiguration(classes = SpringSecurity5Application.class) public class SecurityIntegrationTest { @@ -31,6 +33,7 @@ public class SecurityIntegrationTest { } @Test + @Ignore @WithMockUser public void whenHasCredentials_thenSeesGreeting() { this.rest.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("Hello, user"); diff --git a/spring-5-reactive-security/src/test/resources/baeldung-weekly.png b/spring-5-reactive-security/src/test/resources/baeldung-weekly.png new file mode 100644 index 0000000000..a1b7eebcab Binary files /dev/null and b/spring-5-reactive-security/src/test/resources/baeldung-weekly.png differ diff --git a/spring-5-reactive/README.md b/spring-5-reactive/README.md index 9998dbf751..0665eb4f57 100644 --- a/spring-5-reactive/README.md +++ b/spring-5-reactive/README.md @@ -1,19 +1,15 @@ -## Spring REST Example Project +## Spring 5 Reactive Project ### The Course The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles -- [Concurrent Test Execution in Spring 5](http://www.baeldung.com/spring-5-concurrent-tests) - [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) -- [The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5](http://www.baeldung.com/spring-5-junit-config) -- [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) -- [Spring 5 Testing with @EnabledIf Annotation](https://github.com/eugenp/tutorials/tree/master/spring-5) +- [Exploring the Spring 5 MVC URL Matching Improvements](http://www.baeldung.com/spring-5-mvc-url-matching) - [Reactive WebSockets with Spring 5](http://www.baeldung.com/spring-5-reactive-websockets) -- [Spring Boot Actuator](http://www.baeldung.com/spring-boot-actuators) - [Spring Webflux Filters](http://www.baeldung.com/spring-webflux-filters) -- [Reactive Flow with MongoDB, Kotlin, and Spring WebFlux](http://www.baeldung.com/kotlin-mongodb-spring-webflux) +- [How to Set a Header on a Response with Spring 5](http://www.baeldung.com/spring-response-header) +- [Spring Webflux and CORS](http://www.baeldung.com/spring-webflux-cors) +- [Handling Errors in Spring WebFlux](http://www.baeldung.com/spring-webflux-errors) diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index fa86e9ca8a..5f455c3906 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung @@ -11,10 +11,10 @@ spring 5 sample project about new features - org.springframework.boot - spring-boot-starter-parent - 2.0.0.RELEASE - + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 @@ -39,24 +39,6 @@ javax.json.bind javax.json.bind-api - - org.springframework.boot - spring-boot-starter-actuator - - - - - - - - - - - - - - - org.projectlombok lombok @@ -102,18 +84,14 @@ - org.junit.jupiter - junit-jupiter-api + io.reactivex.rxjava2 + rxjava + ${rxjava-version} - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} + io.projectreactor + reactor-test + ${project-reactor-test} test @@ -122,26 +100,6 @@ ${junit.platform.version} test - - org.apache.commons - commons-lang3 - - - - org.springframework.boot - spring-boot-starter-data-mongodb-reactive - - - de.flapdoodle.embed - de.flapdoodle.embed.mongo - test - - - io.reactivex.rxjava2 - rxjava - ${rxjava-version} - - @@ -154,37 +112,18 @@ JAR - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - methods - true - - **/*IntegrationTest.java - **/*LiveTest.java - - - - UTF-8 - UTF-8 - 1.8 - 1.0.0 - 5.0.2 - 2.20 1.0.1.RELEASE 2.1.12 1.1.3 1.0 1.0 4.1 + 3.1.6.RELEASE + 1.2.0 diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/Actor.java b/spring-5-reactive/src/main/java/com/baeldung/functional/Actor.java new file mode 100644 index 0000000000..23c88b89e1 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/Actor.java @@ -0,0 +1,23 @@ +package com.baeldung.functional; + +class Actor { + private String firstname; + private String lastname; + + public Actor() { + } + + public Actor(String firstname, String lastname) { + this.firstname = firstname; + this.lastname = lastname; + } + + public String getFirstname() { + return firstname; + } + + public String getLastname() { + return lastname; + } + +} diff --git a/spring-5/src/main/java/com/baeldung/functional/FormHandler.java b/spring-5-reactive/src/main/java/com/baeldung/functional/FormHandler.java similarity index 94% rename from spring-5/src/main/java/com/baeldung/functional/FormHandler.java rename to spring-5-reactive/src/main/java/com/baeldung/functional/FormHandler.java index 05069735bb..c4f8c9f41f 100644 --- a/spring-5/src/main/java/com/baeldung/functional/FormHandler.java +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/FormHandler.java @@ -34,8 +34,7 @@ public class FormHandler { 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.readableByteCount())); return atomicLong; } } diff --git a/spring-5/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java similarity index 85% rename from spring-5/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java rename to spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java index 402b607b19..a1d5d87d5c 100644 --- a/spring-5/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java @@ -21,9 +21,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.core.io.ClassPathResource; import org.springframework.http.server.reactive.HttpHandler; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; @@ -68,18 +65,6 @@ public class FunctionalSpringBootApplication { return registrationBean; } - @Configuration - @EnableWebSecurity - @Profile("!https") - static class SecurityConfig extends WebSecurityConfigurerAdapter { - @Override - protected void configure(final HttpSecurity http) throws Exception { - http.authorizeRequests() - .anyRequest() - .permitAll(); - } - } - public static void main(String[] args) { SpringApplication.run(FunctionalSpringBootApplication.class, args); } diff --git a/spring-5/src/main/java/com/baeldung/functional/FunctionalWebApplication.java b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java similarity index 95% rename from spring-5/src/main/java/com/baeldung/functional/FunctionalWebApplication.java rename to spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java index 5a7d70d3db..1f40798ada 100644 --- a/spring-5/src/main/java/com/baeldung/functional/FunctionalWebApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java @@ -13,6 +13,7 @@ import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.catalina.Context; +import org.apache.catalina.Wrapper; import org.apache.catalina.startup.Tomcat; import org.springframework.boot.web.embedded.tomcat.TomcatWebServer; import org.springframework.boot.web.server.WebServer; @@ -61,7 +62,8 @@ public class FunctionalWebApplication { tomcat.setPort(9090); Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler); - Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet); + Wrapper servletWrapper = Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet); + servletWrapper.setAsyncSupported(true); rootContext.addServletMappingDecoded("/", "httpHandlerServlet"); TomcatWebServer server = new TomcatWebServer(tomcat); diff --git a/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java b/spring-5-reactive/src/main/java/com/baeldung/functional/IndexRewriteFilter.java similarity index 90% rename from spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java rename to spring-5-reactive/src/main/java/com/baeldung/functional/IndexRewriteFilter.java index 3e91a0354b..551ea6c84b 100644 --- a/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/IndexRewriteFilter.java @@ -16,8 +16,6 @@ class IndexRewriteFilter implements WebFilter { .equals("/")) { return webFilterChain.filter(serverWebExchange.mutate() .request(builder -> builder.method(request.getMethod()) - .contextPath(request.getPath() - .toString()) .path("/test")) .build()); } diff --git a/spring-5/src/main/java/com/baeldung/functional/RootServlet.java b/spring-5-reactive/src/main/java/com/baeldung/functional/RootServlet.java similarity index 100% rename from spring-5/src/main/java/com/baeldung/functional/RootServlet.java rename to spring-5-reactive/src/main/java/com/baeldung/functional/RootServlet.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java index e96767145e..1656f70221 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java @@ -1,11 +1,9 @@ package com.baeldung.reactive; -import com.mongodb.reactivestreams.client.MongoClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; -import org.springframework.data.mongodb.core.ReactiveMongoTemplate; @SpringBootApplication public class Spring5ReactiveApplication{ @@ -14,12 +12,4 @@ public class Spring5ReactiveApplication{ SpringApplication.run(Spring5ReactiveApplication.class, args); } - @Autowired - MongoClient mongoClient; - - @Bean - public ReactiveMongoTemplate reactiveMongoTemplate() { - return new ReactiveMongoTemplate(mongoClient, "test"); - } - } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java new file mode 100644 index 0000000000..d990928abe --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java @@ -0,0 +1,17 @@ +package com.baeldung.reactive.cors.annotated; + +import java.util.Collections; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CorsOnAnnotatedElementsApplication { + + public static void main(String[] args) { + SpringApplication app = new SpringApplication(CorsOnAnnotatedElementsApplication.class); + app.setDefaultProperties(Collections.singletonMap("server.port", "8081")); + app.run(args); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnClassController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnClassController.java new file mode 100644 index 0000000000..00bc93a101 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnClassController.java @@ -0,0 +1,49 @@ +package com.baeldung.reactive.cors.annotated.controllers; + +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Mono; + +@CrossOrigin(value = { "http://allowed-origin.com" }, allowedHeaders = { "Baeldung-Another-Allowed" }, maxAge = 900) +@RestController +@RequestMapping("/cors-on-controller") +public class CorsOnClassController { + + @PutMapping("/regular-endpoint") + public Mono corsDisabledEndpoint() { + return Mono.just("Regular endpoint"); + } + + @CrossOrigin + @PutMapping("/cors-enabled-endpoint") + public Mono corsEnabledEndpoint() { + return Mono.just("CORS enabled endpoint"); + } + + @CrossOrigin({ "http://another-allowed-origin.com" }) + @PutMapping("/cors-enabled-origin-restrictive-endpoint") + public Mono corsEnabledOriginRestrictiveEndpoint() { + return Mono.just("CORS enabled endpoint - Origin Restrictive"); + } + + @CrossOrigin(allowedHeaders = { "Baeldung-Allowed" }) + @PutMapping("/cors-enabled-header-restrictive-endpoint") + public Mono corsEnabledHeaderRestrictiveEndpoint() { + return Mono.just("CORS enabled endpoint - Header Restrictive"); + } + + @CrossOrigin(exposedHeaders = { "Baeldung-Exposed" }) + @PutMapping("/cors-enabled-exposed-header-endpoint") + public Mono corsEnabledExposedHeadersEndpoint() { + return Mono.just("CORS enabled endpoint - Exposed Header"); + } + + @PutMapping("/cors-enabled-mixed-config-endpoint") + @CrossOrigin(allowedHeaders = { "Baeldung-Allowed", "Baeldung-Other-Allowed" }, exposedHeaders = { "Baeldung-Allowed", "Baeldung-Exposed" }, maxAge = 3600) + public Mono corsEnabledHeaderExposedEndpoint() { + return Mono.just("CORS enabled endpoint - Mixed Config"); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnMethodsController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnMethodsController.java new file mode 100644 index 0000000000..3c72d25840 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnMethodsController.java @@ -0,0 +1,48 @@ +package com.baeldung.reactive.cors.annotated.controllers; + +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Mono; + +@RestController +@RequestMapping("/cors-on-methods") +public class CorsOnMethodsController { + + @PutMapping("/cors-disabled-endpoint") + public Mono corsDisabledEndpoint() { + return Mono.just("CORS disabled endpoint"); + } + + @CrossOrigin + @PutMapping("/cors-enabled-endpoint") + public Mono corsEnabledEndpoint() { + return Mono.just("CORS enabled endpoint"); + } + + @CrossOrigin({ "http://allowed-origin.com" }) + @PutMapping("/cors-enabled-origin-restrictive-endpoint") + public Mono corsEnabledOriginRestrictiveEndpoint() { + return Mono.just("CORS enabled endpoint - Origin Restrictive"); + } + + @CrossOrigin(allowedHeaders = { "Baeldung-Allowed" }) + @PutMapping("/cors-enabled-header-restrictive-endpoint") + public Mono corsEnabledHeaderRestrictiveEndpoint() { + return Mono.just("CORS enabled endpoint - Header Restrictive"); + } + + @CrossOrigin(exposedHeaders = { "Baeldung-Exposed" }) + @PutMapping("/cors-enabled-exposed-header-endpoint") + public Mono corsEnabledExposedHeadersEndpoint() { + return Mono.just("CORS enabled endpoint - Exposed Header"); + } + + @PutMapping("/cors-enabled-mixed-config-endpoint") + @CrossOrigin(allowedHeaders = { "Baeldung-Allowed", "Baeldung-Other-Allowed" }, exposedHeaders = { "Baeldung-Allowed", "Baeldung-Exposed" }, maxAge = 3600) + public Mono corsEnabledHeaderExposedEndpoint() { + return Mono.just("CORS enabled endpoint - Mixed Config"); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java new file mode 100644 index 0000000000..8228944569 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java @@ -0,0 +1,25 @@ +package com.baeldung.reactive.cors.global; + +import java.util.Collections; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration; +import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration; +import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; +import org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration; + +@SpringBootApplication(exclude = { MongoAutoConfiguration.class, + MongoDataAutoConfiguration.class, + MongoReactiveDataAutoConfiguration.class, + MongoReactiveAutoConfiguration.class } +) +public class CorsGlobalConfigApplication { + + public static void main(String[] args) { + SpringApplication app = new SpringApplication(CorsGlobalConfigApplication.class); + app.setDefaultProperties(Collections.singletonMap("server.port", "8082")); + app.run(args); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/config/CorsGlobalConfiguration.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/config/CorsGlobalConfiguration.java new file mode 100644 index 0000000000..92cd6ec50a --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/config/CorsGlobalConfiguration.java @@ -0,0 +1,22 @@ +package com.baeldung.reactive.cors.global.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.reactive.config.CorsRegistry; +import org.springframework.web.reactive.config.EnableWebFlux; +import org.springframework.web.reactive.config.WebFluxConfigurer; + +@Configuration +@EnableWebFlux +public class CorsGlobalConfiguration implements WebFluxConfigurer { + + @Override + public void addCorsMappings(CorsRegistry corsRegistry) { + corsRegistry.addMapping("/**") + .allowedOrigins("http://allowed-origin.com") + .allowedMethods("PUT") + .allowedHeaders("Baeldung-Allowed", "Baledung-Another-Allowed") + .exposedHeaders("Baeldung-Allowed", "Baeldung-Exposed") + .maxAge(3600); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/FurtherCorsConfigsController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/FurtherCorsConfigsController.java new file mode 100644 index 0000000000..4358326df8 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/FurtherCorsConfigsController.java @@ -0,0 +1,24 @@ +package com.baeldung.reactive.cors.global.controllers; + +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Mono; + +@RestController("FurtherCorsConfigsController-cors-on-global-config-and-more") +@RequestMapping("/cors-on-global-config-and-more") +public class FurtherCorsConfigsController { + + @DeleteMapping("/further-mixed-config-endpoint") + @CrossOrigin(methods = { RequestMethod.DELETE }, + allowedHeaders = { "Baeldung-Other-Allowed" }, + exposedHeaders = { "Baeldung-Other-Exposed" } + ) + public Mono corsEnabledHeaderExposedEndpoint() { + return Mono.just("CORS Global Configured + Request Configs."); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/RegularRestController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/RegularRestController.java new file mode 100644 index 0000000000..e57e573146 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/RegularRestController.java @@ -0,0 +1,23 @@ +package com.baeldung.reactive.cors.global.controllers; + +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Mono; + +@RestController("RegularRestController-cors-on-global-config") +@RequestMapping("/cors-on-global-config") +public class RegularRestController { + + @PutMapping("/regular-put-endpoint") + public Mono regularPutEndpoint() { + return Mono.just("Regular PUT endpoint"); + } + + @DeleteMapping("/regular-delete-endpoint") + public Mono regularDeleteEndpoint() { + return Mono.just("Regular DELETE endpoint"); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/FunctionalHandler.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/FunctionalHandler.java new file mode 100644 index 0000000000..e6e32d7cc8 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/FunctionalHandler.java @@ -0,0 +1,18 @@ +package com.baeldung.reactive.cors.global.functional.handlers; + +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; + +import reactor.core.publisher.Mono; + +@Component +public class FunctionalHandler { + + public Mono useHandler(final ServerRequest request) { + final String responseMessage = "CORS GLOBAL CONFIG IS NOT EFFECTIVE ON FUNCTIONAL ENDPOINTS!!!"; + + return ServerResponse.ok() + .body(Mono.just(responseMessage), String.class); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java new file mode 100644 index 0000000000..19621a9e97 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java @@ -0,0 +1,20 @@ +package com.baeldung.reactive.cors.global.functional.routers; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.reactive.function.server.RequestPredicates; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.reactive.cors.global.functional.handlers.FunctionalHandler; + +@Configuration +public class CorsRouterFunctions { + + @Bean + public RouterFunction responseHeaderRoute(@Autowired FunctionalHandler handler) { + return RouterFunctions.route(RequestPredicates.PUT("/global-config-on-functional/cors-disabled-functional-endpoint"), handler::useHandler); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java new file mode 100644 index 0000000000..38140c0d71 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java @@ -0,0 +1,25 @@ +package com.baeldung.reactive.cors.webfilter; + +import java.util.Collections; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration; +import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration; +import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; +import org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration; + +@SpringBootApplication(exclude = { MongoAutoConfiguration.class, + MongoDataAutoConfiguration.class, + MongoReactiveDataAutoConfiguration.class, + MongoReactiveAutoConfiguration.class } +) +public class CorsWebFilterApplication { + + public static void main(String[] args) { + SpringApplication app = new SpringApplication(CorsWebFilterApplication.class); + app.setDefaultProperties(Collections.singletonMap("server.port", "8083")); + app.run(args); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/config/CorsWebFilterConfig.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/config/CorsWebFilterConfig.java new file mode 100644 index 0000000000..55fbcc2903 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/config/CorsWebFilterConfig.java @@ -0,0 +1,29 @@ +package com.baeldung.reactive.cors.webfilter.config; + +import java.util.Arrays; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.reactive.CorsWebFilter; +import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; +import org.springframework.web.util.pattern.PathPatternParser; + +@Configuration +public class CorsWebFilterConfig { + + @Bean + CorsWebFilter corsWebFilter() { + CorsConfiguration corsConfig = new CorsConfiguration(); + corsConfig.setAllowedOrigins(Arrays.asList("http://allowed-origin.com")); + corsConfig.setMaxAge(8000L); + corsConfig.addAllowedMethod("PUT"); + corsConfig.addAllowedHeader("Baeldung-Allowed"); + + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); + source.registerCorsConfiguration("/**", corsConfig); + + return new CorsWebFilter(source); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/FurtherCorsConfigsController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/FurtherCorsConfigsController.java new file mode 100644 index 0000000000..bc5b483935 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/FurtherCorsConfigsController.java @@ -0,0 +1,26 @@ +package com.baeldung.reactive.cors.webfilter.controllers; + +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Mono; + +//@RestController +//@RequestMapping("/web-filter-and-more-on-annotated") +public class FurtherCorsConfigsController { + + @DeleteMapping("/further-mixed-config-endpoint") + @CrossOrigin(methods = { RequestMethod.DELETE }, + allowedHeaders = { "Baeldung-Other-Allowed" }, + exposedHeaders = { "Baeldung-Other-Exposed" } + ) + public Mono corsEnabledHeaderExposedEndpoint() { + final String responseMessage = "CORS @CrossOrigin IS NOT EFFECTIVE with WebFilter!!!"; + + return Mono.just(responseMessage); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/RegularRestController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/RegularRestController.java new file mode 100644 index 0000000000..1d382b222a --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/RegularRestController.java @@ -0,0 +1,23 @@ +package com.baeldung.reactive.cors.webfilter.controllers; + +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Mono; + +//@RestController +//@RequestMapping("/web-filter-on-annotated") +public class RegularRestController { + + @PutMapping("/regular-put-endpoint") + public Mono regularPutEndpoint() { + return Mono.just("Regular PUT endpoint"); + } + + @DeleteMapping("/regular-delete-endpoint") + public Mono regularDeleteEndpoint() { + return Mono.just("Regular DELETE endpoint"); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/handlers/CorsWithWebFilterHandler.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/handlers/CorsWithWebFilterHandler.java new file mode 100644 index 0000000000..04e4602049 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/handlers/CorsWithWebFilterHandler.java @@ -0,0 +1,16 @@ +package com.baeldung.reactive.cors.webfilter.functional.handlers; + +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; + +import reactor.core.publisher.Mono; + +@Component +public class CorsWithWebFilterHandler { + + public Mono useHandler(final ServerRequest request) { + return ServerResponse.ok() + .body(Mono.just("Functional Endpoint"), String.class); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java new file mode 100644 index 0000000000..a3905bb79f --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java @@ -0,0 +1,20 @@ +package com.baeldung.reactive.cors.webfilter.functional.routers; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.reactive.function.server.RequestPredicates; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.reactive.cors.webfilter.functional.handlers.CorsWithWebFilterHandler; + +@Configuration +public class CorsWithWebFilterRouterFunctions { + + @Bean + public RouterFunction responseHeaderRoute(@Autowired CorsWithWebFilterHandler handler) { + return RouterFunctions.route(RequestPredicates.PUT("/web-filter-on-functional/functional-endpoint"), handler::useHandler); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/GlobalErrorAttributes.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/GlobalErrorAttributes.java new file mode 100644 index 0000000000..a50651ced7 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/GlobalErrorAttributes.java @@ -0,0 +1,55 @@ + +package com.baeldung.reactive.errorhandling; + +import java.util.Map; +import org.springframework.boot.web.reactive.error.DefaultErrorAttributes; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.server.ServerRequest; + +@Component +public class GlobalErrorAttributes extends DefaultErrorAttributes{ + + private HttpStatus status = HttpStatus.BAD_REQUEST; + private String message = "please provide a name"; + + public GlobalErrorAttributes() { + super(false); + } + + @Override + public Map getErrorAttributes(ServerRequest request, boolean includeStackTrace) { + Map map = super.getErrorAttributes(request, includeStackTrace); + map.put("status", getStatus()); + map.put("message", getMessage()); + return map; + } + + /** + * @return the status + */ + public HttpStatus getStatus() { + return status; + } + + /** + * @param status the status to set + */ + public void setStatus(HttpStatus status) { + this.status = status; + } + + /** + * @return the message + */ + public String getMessage() { + return message; + } + + /** + * @param message the message to set + */ + public void setMessage(String message) { + this.message = message; + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/GlobalErrorWebExceptionHandler.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/GlobalErrorWebExceptionHandler.java new file mode 100644 index 0000000000..09bccb0d5e --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/GlobalErrorWebExceptionHandler.java @@ -0,0 +1,47 @@ + +package com.baeldung.reactive.errorhandling; + +import java.util.Map; +import org.springframework.boot.autoconfigure.web.ResourceProperties; +import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler; +import org.springframework.boot.web.reactive.error.ErrorAttributes; +import org.springframework.context.ApplicationContext; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.codec.ServerCodecConfigurer; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.server.RequestPredicates; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; +import reactor.core.publisher.Mono; + +@Component +@Order(-2) +public class GlobalErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler { + + public GlobalErrorWebExceptionHandler(GlobalErrorAttributes g, ApplicationContext applicationContext, + ServerCodecConfigurer serverCodecConfigurer) { + super(g, new ResourceProperties(), applicationContext); + super.setMessageWriters(serverCodecConfigurer.getWriters()); + super.setMessageReaders(serverCodecConfigurer.getReaders()); + } + + @Override + protected RouterFunction getRoutingFunction(final ErrorAttributes errorAttributes) { + return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse); + } + + private Mono renderErrorResponse(final ServerRequest request) { + + final Map errorPropertiesMap = getErrorAttributes(request, false); + + return ServerResponse.status(HttpStatus.BAD_REQUEST) + .contentType(MediaType.APPLICATION_JSON_UTF8) + .body(BodyInserters.fromObject(errorPropertiesMap)); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/NameRequiredException.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/NameRequiredException.java new file mode 100644 index 0000000000..38d35544a7 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/NameRequiredException.java @@ -0,0 +1,12 @@ + +package com.baeldung.reactive.errorhandling; + +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +public class NameRequiredException extends ResponseStatusException { + + public NameRequiredException(HttpStatus status, String message, Throwable e) { + super(status, message, e); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler1.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler1.java new file mode 100644 index 0000000000..87b78a4654 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler1.java @@ -0,0 +1,29 @@ + +package com.baeldung.reactive.errorhandling.handlers; + +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; +import reactor.core.publisher.Mono; + +@Component +public class Handler1 { + + public Mono handleRequest1(ServerRequest request) { + return sayHello(request).onErrorReturn("Hello, Stranger") + .flatMap(s -> ServerResponse.ok() + .contentType(MediaType.TEXT_PLAIN) + .syncBody(s)); + } + + private Mono sayHello(ServerRequest request) { + try { + return Mono.just("Hello, " + request.queryParam("name") + .get()); + } catch (Exception e) { + return Mono.error(e); + } + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler2.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler2.java new file mode 100644 index 0000000000..12172a0f54 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler2.java @@ -0,0 +1,38 @@ + +package com.baeldung.reactive.errorhandling.handlers; + +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; +import reactor.core.publisher.Mono; + +@Component +public class Handler2 { + +public Mono handleRequest2(ServerRequest request) { + return + sayHello(request) + .flatMap(s -> ServerResponse.ok() + .contentType(MediaType.TEXT_PLAIN) + .syncBody(s)) + .onErrorResume(e -> sayHelloFallback() + .flatMap(s -> ServerResponse.ok() + .contentType(MediaType.TEXT_PLAIN) + .syncBody(s))); +} + + private Mono sayHello(ServerRequest request) { + try { + return Mono.just("Hello, " + request.queryParam("name") + .get()); + } catch (Exception e) { + return Mono.error(e); + } + } + + private Mono sayHelloFallback() { + return Mono.just("Hello, Stranger"); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler3.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler3.java new file mode 100644 index 0000000000..e95b039cce --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler3.java @@ -0,0 +1,34 @@ + +package com.baeldung.reactive.errorhandling.handlers; + +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; +import reactor.core.publisher.Mono; + +@Component +public class Handler3 { + + public Mono handleRequest3(ServerRequest request) { + return + sayHello(request) + .flatMap(s -> ServerResponse.ok() + .contentType(MediaType.TEXT_PLAIN) + .syncBody(s)) + .onErrorResume(e -> (Mono.just("Hi, I looked around for your name but found: " + + e.getMessage())).flatMap(s -> ServerResponse.ok() + .contentType(MediaType.TEXT_PLAIN) + .syncBody(s))); + } + + private Mono sayHello(ServerRequest request) { + try { + return Mono.just("Hello, " + request.queryParam("name") + .get()); + } catch (Exception e) { + return Mono.error(e); + } + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler4.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler4.java new file mode 100644 index 0000000000..3d6ef258d3 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler4.java @@ -0,0 +1,30 @@ + +package com.baeldung.reactive.errorhandling.handlers; + +import com.baeldung.reactive.errorhandling.NameRequiredException; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; +import reactor.core.publisher.Mono; + +@Component +public class Handler4 { + +public Mono handleRequest4(ServerRequest request) { + return ServerResponse.ok() + .body(sayHello(request) + .onErrorResume(e -> + Mono.error(new NameRequiredException( + HttpStatus.BAD_REQUEST, "please provide a name", e))), String.class); +} + + private Mono sayHello(ServerRequest request) { + try { + return Mono.just("Hello, " + request.queryParam("name").get()); + } catch (Exception e) { + return Mono.error(e); + } + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler5.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler5.java new file mode 100644 index 0000000000..41605b355b --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler5.java @@ -0,0 +1,22 @@ + +package com.baeldung.reactive.errorhandling.handlers; + +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; +import reactor.core.publisher.Mono; + +@Component +public class Handler5 { + + public Mono handleRequest5(ServerRequest request) { + return ServerResponse.ok() + .body(sayHello(request), String.class); + + } + + private Mono sayHello(ServerRequest request) { + return Mono.just("Hello, " + request.queryParam("name").get()); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/routers/Router1.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/routers/Router1.java new file mode 100644 index 0000000000..91be24571c --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/routers/Router1.java @@ -0,0 +1,22 @@ + +package com.baeldung.reactive.errorhandling.routers; + +import com.baeldung.reactive.errorhandling.handlers.Handler1; +import org.springframework.context.annotation.Bean; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.server.RequestPredicates; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; + +@Component +public class Router1 { + + @Bean + public RouterFunction routeRequest1(Handler1 handler) { + return RouterFunctions.route(RequestPredicates.GET("/api/endpoint1") + .and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), handler::handleRequest1); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/routers/Router2.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/routers/Router2.java new file mode 100644 index 0000000000..bc7831f494 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/routers/Router2.java @@ -0,0 +1,22 @@ + +package com.baeldung.reactive.errorhandling.routers; + +import com.baeldung.reactive.errorhandling.handlers.Handler2; +import org.springframework.context.annotation.Bean; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.server.RequestPredicates; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; + +@Component +public class Router2 { + + @Bean + public RouterFunction routeRequest2(Handler2 handler) { + return RouterFunctions.route(RequestPredicates.GET("/api/endpoint2") + .and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), handler::handleRequest2); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/routers/Router3.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/routers/Router3.java new file mode 100644 index 0000000000..461e6fe9e7 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/routers/Router3.java @@ -0,0 +1,22 @@ + +package com.baeldung.reactive.errorhandling.routers; + +import com.baeldung.reactive.errorhandling.handlers.Handler3; +import org.springframework.context.annotation.Bean; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.server.RequestPredicates; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; + +@Component +public class Router3 { + + @Bean + public RouterFunction routeRequest3(Handler3 handler) { + return RouterFunctions.route(RequestPredicates.GET("/api/endpoint3") + .and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), handler::handleRequest3); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/routers/Router4.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/routers/Router4.java new file mode 100644 index 0000000000..9dccc6858f --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/routers/Router4.java @@ -0,0 +1,22 @@ + +package com.baeldung.reactive.errorhandling.routers; + +import com.baeldung.reactive.errorhandling.handlers.Handler4; +import org.springframework.context.annotation.Bean; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.server.RequestPredicates; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; + +@Component +public class Router4 { + + @Bean + public RouterFunction routeRequest4(Handler4 handler) { + return RouterFunctions.route(RequestPredicates.GET("/api/endpoint4") + .and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), handler::handleRequest4); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/routers/Router5.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/routers/Router5.java new file mode 100644 index 0000000000..59fd587fc8 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/routers/Router5.java @@ -0,0 +1,22 @@ + +package com.baeldung.reactive.errorhandling.routers; + +import com.baeldung.reactive.errorhandling.handlers.Handler5; +import org.springframework.context.annotation.Bean; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.server.RequestPredicates; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; + +@Component +public class Router5 { + + @Bean + public RouterFunction routeRequest5(Handler5 handler) { + return RouterFunctions.route(RequestPredicates.GET("/api/endpoint5") + .and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), handler::handleRequest5); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/controllers/ResponseHeaderController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/controllers/ResponseHeaderController.java new file mode 100644 index 0000000000..5220ea2f4c --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/controllers/ResponseHeaderController.java @@ -0,0 +1,35 @@ +package com.baeldung.reactive.responseheaders.controllers; + +import org.springframework.http.ResponseEntity; +import org.springframework.http.server.reactive.ServerHttpResponse; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Mono; + +@RestController +@RequestMapping("/response-header") +public class ResponseHeaderController { + + @GetMapping("/response-entity") + public Mono> usingResponseEntityBuilder() { + String responseHeaderKey = "Baeldung-Example-Header"; + String responseHeaderValue = "Value-ResponseEntityBuilder"; + String responseBody = "Response with header using ResponseEntity (builder)"; + + return Mono.just(ResponseEntity.ok() + .header(responseHeaderKey, responseHeaderValue) + .body(responseBody)); + } + + @GetMapping("/server-http-response") + public Mono usingServerHttpResponse(ServerHttpResponse response) { + String responseHeaderKey = "Baeldung-Example-Header"; + String responseHeaderValue = "Value-ServerHttpResponse"; + String responseBody = "Response with header using ServerHttpResponse"; + + response.getHeaders().add(responseHeaderKey, responseHeaderValue); + return Mono.just(responseBody); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/filter/AddResponseHeaderWebFilter.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/filter/AddResponseHeaderWebFilter.java new file mode 100644 index 0000000000..8d8484f5cd --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/filter/AddResponseHeaderWebFilter.java @@ -0,0 +1,20 @@ +package com.baeldung.reactive.responseheaders.filter; + +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import org.springframework.web.server.WebFilter; +import org.springframework.web.server.WebFilterChain; + +import reactor.core.publisher.Mono; + +@Component +public class AddResponseHeaderWebFilter implements WebFilter { + + @Override + public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { + exchange.getResponse() + .getHeaders() + .add("Baeldung-Example-Filter-Header", "Value-Filter"); + return chain.filter(exchange); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/functional/handlers/ResponseHeaderHandler.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/functional/handlers/ResponseHeaderHandler.java new file mode 100644 index 0000000000..20f76d3b6e --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/functional/handlers/ResponseHeaderHandler.java @@ -0,0 +1,21 @@ +package com.baeldung.reactive.responseheaders.functional.handlers; + +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; + +import reactor.core.publisher.Mono; + +@Component +public class ResponseHeaderHandler { + + public Mono useHandler(final ServerRequest request) { + String responseHeaderKey = "Baeldung-Example-Header"; + String responseHeaderValue = "Value-Handler"; + String responseBody = "Response with header using Handler"; + + return ServerResponse.ok() + .header(responseHeaderKey, responseHeaderValue) + .body(Mono.just(responseBody),String.class); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/functional/routers/ResponseHeadersRouterFunctions.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/functional/routers/ResponseHeadersRouterFunctions.java new file mode 100644 index 0000000000..63f7c7f036 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/responseheaders/functional/routers/ResponseHeadersRouterFunctions.java @@ -0,0 +1,20 @@ +package com.baeldung.reactive.responseheaders.functional.routers; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.reactive.function.server.RequestPredicates; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.reactive.responseheaders.functional.handlers.ResponseHeaderHandler; + +@Configuration +public class ResponseHeadersRouterFunctions { + + @Bean + public RouterFunction responseHeaderRoute(@Autowired ResponseHeaderHandler handler) { + return RouterFunctions.route(RequestPredicates.GET("/functional-response-header/single-handler"), handler::useHandler); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java new file mode 100644 index 0000000000..3997607ef0 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java @@ -0,0 +1,19 @@ +package com.baeldung.reactive.serversentevents.consumer; + +import java.util.Collections; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableAsync; + +@SpringBootApplication +@EnableAsync +public class ConsumerSSEApplication { + + public static void main(String[] args) { + SpringApplication app = new SpringApplication(ConsumerSSEApplication.class); + app.setDefaultProperties(Collections.singletonMap("server.port", "8082")); + app.run(args); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/controller/ClientController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/controller/ClientController.java new file mode 100644 index 0000000000..69a6bc396c --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/controller/ClientController.java @@ -0,0 +1,83 @@ +package com.baeldung.reactive.serversentevents.consumer.controller; + +import java.time.LocalTime; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.MediaType; +import org.springframework.http.codec.ServerSentEvent; +import org.springframework.scheduling.annotation.Async; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.reactive.function.client.WebClient; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@RestController +@RequestMapping("/sse-consumer") +public class ClientController { + + private static Logger logger = LoggerFactory.getLogger(ClientController.class); + private WebClient client = WebClient.create("http://localhost:8081/sse-server"); + + @GetMapping("/launch-sse-client") + public String launchSSEFromSSEWebClient() { + consumeSSE(); + return "LAUNCHED EVENT CLIENT!!! Check the logs..."; + } + + @GetMapping("/launch-flux-client") + public String launchcFluxFromSSEWebClient() { + consumeFlux(); + return "LAUNCHED EVENT CLIENT!!! Check the logs..."; + } + + @GetMapping("/launch-sse-from-flux-endpoint-client") + public String launchFluxFromFluxWebClient() { + consumeSSEFromFluxEndpoint(); + return "LAUNCHED EVENT CLIENT!!! Check the logs..."; + } + + @Async + public void consumeSSE() { + ParameterizedTypeReference> type = new ParameterizedTypeReference>() { + }; + + Flux> eventStream = client.get() + .uri("/stream-sse") + .retrieve() + .bodyToFlux(type); + + eventStream.subscribe(content -> logger.info("Current time: {} - Received SSE: name[{}], id [{}], content[{}] ", LocalTime.now(), content.event(), content.id(), content.data()), error -> logger.error("Error receiving SSE: {}", error), + () -> logger.info("Completed!!!")); + } + + @Async + public void consumeFlux() { + Flux stringStream = client.get() + .uri("/stream-flux") + .accept(MediaType.TEXT_EVENT_STREAM) + .retrieve() + .bodyToFlux(String.class); + + stringStream.subscribe(content -> logger.info("Current time: {} - Received content: {} ", LocalTime.now(), content), error -> logger.error("Error retrieving content: {}", error), () -> logger.info("Completed!!!")); + } + + @Async + public void consumeSSEFromFluxEndpoint() { + ParameterizedTypeReference> type = new ParameterizedTypeReference>() { + }; + + Flux> eventStream = client.get() + .uri("/stream-flux") + .accept(MediaType.TEXT_EVENT_STREAM) + .retrieve() + .bodyToFlux(type); + + eventStream.subscribe(content -> logger.info("Current time: {} - Received SSE: name[{}], id [{}], content[{}] ", LocalTime.now(), content.event(), content.id(), content.data()), error -> logger.error("Error receiving SSE: {}", error), + () -> logger.info("Completed!!!")); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java new file mode 100644 index 0000000000..2750e6616d --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java @@ -0,0 +1,17 @@ +package com.baeldung.reactive.serversentevents.server; + +import java.util.Collections; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ServerSSEApplication { + + public static void main(String[] args) { + SpringApplication app = new SpringApplication(ServerSSEApplication.class); + app.setDefaultProperties(Collections.singletonMap("server.port", "8081")); + app.run(args); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/controllers/ServerController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/controllers/ServerController.java new file mode 100644 index 0000000000..1ad8e848cf --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/controllers/ServerController.java @@ -0,0 +1,35 @@ +package com.baeldung.reactive.serversentevents.server.controllers; + +import java.time.Duration; +import java.time.LocalTime; + +import org.springframework.http.MediaType; +import org.springframework.http.codec.ServerSentEvent; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Flux; + +@RestController +@RequestMapping("/sse-server") +public class ServerController { + + @GetMapping("/stream-sse") + public Flux> streamEvents() { + return Flux.interval(Duration.ofSeconds(1)) + .map(sequence -> ServerSentEvent. builder() + .id(String.valueOf(sequence)) + .event("periodic-event") + .data("SSE - " + LocalTime.now() + .toString()) + .build()); + } + + @GetMapping(path = "/stream-flux", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public Flux streamFlux() { + return Flux.interval(Duration.ofSeconds(1)) + .map(sequence -> "Flux - " + LocalTime.now() + .toString()); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java index 78f40be57a..115a057915 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java @@ -7,6 +7,7 @@ import static org.springframework.web.reactive.function.server.RouterFunctions.t import static org.springframework.web.reactive.function.server.ServerResponse.ok; import org.apache.catalina.Context; +import org.apache.catalina.Wrapper; import org.apache.catalina.startup.Tomcat; import org.springframework.boot.web.embedded.tomcat.TomcatWebServer; import org.springframework.boot.web.server.WebServer; @@ -41,7 +42,8 @@ public class ExploreSpring5URLPatternUsingRouterFunctions { tomcat.setPort(9090); Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler); - Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet); + Wrapper servletWrapper = Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet); + servletWrapper.setAsyncSupported(true); rootContext.addServletMappingDecoded("/", "httpHandlerServlet"); TomcatWebServer server = new TomcatWebServer(tomcat); diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/util/CpuUtils.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/util/CpuUtils.java new file mode 100644 index 0000000000..8d16434920 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/util/CpuUtils.java @@ -0,0 +1,15 @@ +package com.baeldung.reactive.util; + +import com.sun.management.OperatingSystemMXBean; + +import java.lang.management.ManagementFactory; + +public class CpuUtils { + + private static OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); + + static Double getUsage() { + return (operatingSystemMXBean.getSystemCpuLoad() / operatingSystemMXBean.getAvailableProcessors()) * 100; + } + +} diff --git a/spring-5/src/main/java/com/baeldung/web/reactive/Task.java b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/Task.java similarity index 100% rename from spring-5/src/main/java/com/baeldung/web/reactive/Task.java rename to spring-5-reactive/src/main/java/com/baeldung/web/reactive/Task.java diff --git a/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java similarity index 100% rename from spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java rename to spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/Event.java b/spring-5-reactive/src/main/java/com/baeldung/websocket/Event.java similarity index 79% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/Event.java rename to spring-5-reactive/src/main/java/com/baeldung/websocket/Event.java index 90f83a566f..5d0260928c 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/Event.java +++ b/spring-5-reactive/src/main/java/com/baeldung/websocket/Event.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.websocket; +package com.baeldung.websocket; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveJavaClientWebSocket.java b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveJavaClientWebSocket.java similarity index 95% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveJavaClientWebSocket.java rename to spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveJavaClientWebSocket.java index c9a333c044..efb4dc238a 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveJavaClientWebSocket.java +++ b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveJavaClientWebSocket.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.websocket; +package com.baeldung.websocket; import java.net.URI; import java.time.Duration; diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveWebSocketApplication.java b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketApplication.java similarity index 88% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveWebSocketApplication.java rename to spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketApplication.java index 43b5e50387..0e71673df6 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveWebSocketApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.websocket; +package com.baeldung.websocket; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveWebSocketConfiguration.java b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketConfiguration.java similarity index 88% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveWebSocketConfiguration.java rename to spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketConfiguration.java index 974def5a91..43a98d068d 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveWebSocketConfiguration.java +++ b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketConfiguration.java @@ -1,19 +1,22 @@ -package com.baeldung.reactive.websocket; +package com.baeldung.websocket; + +import java.util.HashMap; +import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.reactive.HandlerMapping; import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; import org.springframework.web.reactive.socket.WebSocketHandler; import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter; -import java.util.HashMap; -import java.util.Map; @Configuration public class ReactiveWebSocketConfiguration { @Autowired + @Qualifier("ReactiveWebSocketHandler") private WebSocketHandler webSocketHandler; @Bean diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveWebSocketHandler.java b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketHandler.java similarity index 95% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveWebSocketHandler.java rename to spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketHandler.java index 2e93c0c0dc..f85f2c0424 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveWebSocketHandler.java +++ b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketHandler.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.websocket; +package com.baeldung.websocket; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -14,7 +14,7 @@ import java.time.Duration; import static java.time.LocalDateTime.now; import static java.util.UUID.randomUUID; -@Component +@Component("ReactiveWebSocketHandler") public class ReactiveWebSocketHandler implements WebSocketHandler { private static final ObjectMapper json = new ObjectMapper(); diff --git a/spring-5-reactive/src/main/resources/application.properties b/spring-5-reactive/src/main/resources/application.properties index 234834b894..92f3116f84 100644 --- a/spring-5-reactive/src/main/resources/application.properties +++ b/spring-5-reactive/src/main/resources/application.properties @@ -1,5 +1,2 @@ logging.level.root=INFO -management.endpoints.web.exposure.include.=* - -info.app.name=Spring Boot 2 actuator Application diff --git a/spring-5-reactive/src/main/resources/logback.xml b/spring-5-reactive/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-5-reactive/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-5/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java similarity index 100% rename from spring-5/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java rename to spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java index a7b951b930..4dea2a05cf 100644 --- a/spring-5/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java @@ -1,5 +1,8 @@ package com.baeldung.functional; +import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import static org.springframework.web.reactive.function.BodyInserters.fromResource; + import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -12,9 +15,6 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.reactive.function.BodyInserters; -import static org.springframework.web.reactive.function.BodyInserters.fromObject; -import static org.springframework.web.reactive.function.BodyInserters.fromResource; - public class FunctionalWebApplicationIntegrationTest { private static WebTestClient client; diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5ReactiveServerClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/Spring5ReactiveServerClientIntegrationTest.java similarity index 99% rename from spring-5/src/test/java/com/baeldung/jupiter/Spring5ReactiveServerClientIntegrationTest.java rename to spring-5-reactive/src/test/java/com/baeldung/reactive/Spring5ReactiveServerClientIntegrationTest.java index bbd852d625..8707c27fb3 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5ReactiveServerClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/Spring5ReactiveServerClientIntegrationTest.java @@ -1,6 +1,5 @@ -package com.baeldung.jupiter; +package com.baeldung.reactive; -import com.baeldung.web.reactive.Task; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.springframework.http.server.reactive.HttpHandler; @@ -8,6 +7,9 @@ import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.web.reactive.Task; + import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.ipc.netty.NettyContext; diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java new file mode 100644 index 0000000000..0043d62e5a --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java @@ -0,0 +1,147 @@ +package com.baeldung.reactive.cors; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class CorsOnAnnotatedElementsLiveTest { + + private static final String BASE_URL = "http://localhost:8081"; + private static final String BASE_CORS_ON_METHODS_URL = "/cors-on-methods"; + private static final String BASE_CORS_ON_CONTROLLER_URL = "/cors-on-controller"; + private static final String CONTROLLER_CORS_ALLOWED_ORIGIN = "http://allowed-origin.com"; + private static final String CORS_DEFAULT_ORIGIN = "http://default-origin.com"; + + private static WebTestClient client; + + @BeforeAll + public static void setup() { + client = WebTestClient.bindToServer() + .baseUrl(BASE_URL) + .defaultHeader("Origin", CORS_DEFAULT_ORIGIN) + .build(); + } + + @Test + public void whenRequestingMethodCorsEnabledEndpoint_thenObtainResponseWithCorsHeaders() { + ResponseSpec response = client.put() + .uri(BASE_CORS_ON_METHODS_URL + "/cors-enabled-endpoint") + .exchange(); + + response.expectHeader() + .valueEquals("Access-Control-Allow-Origin", "*"); + } + + @Test + public void whenPreflightMethodCorsEnabled_thenObtainResponseWithCorsHeaders() { + ResponseSpec response = client.options() + .uri(BASE_CORS_ON_METHODS_URL + "/cors-enabled-endpoint") + .header("Access-Control-Request-Method", "PUT") + .exchange(); + + response.expectHeader() + .valueEquals("Access-Control-Allow-Origin", "*"); + response.expectHeader() + .valueEquals("Access-Control-Allow-Methods", "PUT"); + response.expectHeader() + .exists("Access-Control-Max-Age"); + } + + @Test + public void whenRequestingMethodCorsDisabledEndpoint_thenObtainResponseWithoutCorsHeaders() { + ResponseSpec response = client.put() + .uri(BASE_CORS_ON_METHODS_URL + "/cors-disabled-put-endpoint") + .exchange(); + + response.expectHeader() + .doesNotExist("Access-Control-Allow-Origin"); + } + + @Test + public void whenRequestingMethodCorsRestrictiveOrigin_thenObtainForbiddenResponse() { + ResponseSpec response = client.put() + .uri(BASE_CORS_ON_METHODS_URL + "/cors-enabled-origin-restrictive-endpoint") + .exchange(); + + response.expectStatus() + .isForbidden(); + } + + @Test + public void whenPreflightMethodCorsRestrictiveOrigin_thenObtainForbiddenResponse() { + ResponseSpec response = client.options() + .uri(BASE_CORS_ON_METHODS_URL + "/cors-enabled-origin-restrictive-endpoint") + .header("Access-Control-Request-Method", "PUT") + .exchange(); + + response.expectStatus() + .isForbidden(); + } + + @Test + public void whenPreflightMethodCorsRestrictiveHeader_thenObtainResponseWithAllowedHeaders() { + ResponseSpec response = client.options() + .uri(BASE_CORS_ON_METHODS_URL + "/cors-enabled-header-restrictive-endpoint") + .header("Access-Control-Request-Method", "PUT") + .header("Access-Control-Request-Headers", "Baeldung-Not-Allowed, Baeldung-Allowed") + .exchange(); + + response.expectHeader() + .valueEquals("Access-Control-Allow-Headers", "Baeldung-Allowed"); + } + + @Test + public void whenPreflightControllerCorsRegularEndpoint_thenObtainResponseWithCorsHeaders() { + ResponseSpec response = client.options() + .uri(BASE_CORS_ON_CONTROLLER_URL + "/regular-endpoint") + .header("Origin", CONTROLLER_CORS_ALLOWED_ORIGIN) + .header("Access-Control-Request-Method", "PUT") + .exchange(); + + response.expectHeader() + .valueEquals("Access-Control-Allow-Origin", CONTROLLER_CORS_ALLOWED_ORIGIN); + } + + @Test + public void whenPreflightControllerCorsRestrictiveOrigin_thenObtainResponseWithCorsHeaders() { + ResponseSpec response = client.options() + .uri(BASE_CORS_ON_CONTROLLER_URL + "/cors-enabled-origin-restrictive-endpoint") + .header("Origin", CONTROLLER_CORS_ALLOWED_ORIGIN) + .header("Access-Control-Request-Method", "PUT") + .exchange(); + + response.expectHeader() + .valueEquals("Access-Control-Allow-Origin", CONTROLLER_CORS_ALLOWED_ORIGIN); + } + + @Test + public void whenPreflightControllerCorsRestrictiveOriginWithAnotherAllowedOrigin_thenObtainResponseWithCorsHeaders() { + final String anotherAllowedOrigin = "http://another-allowed-origin.com"; + ResponseSpec response = client.options() + .uri(BASE_CORS_ON_CONTROLLER_URL + "/cors-enabled-origin-restrictive-endpoint") + .header("Origin", anotherAllowedOrigin) + .header("Access-Control-Request-Method", "PUT") + .exchange(); + + response.expectHeader() + .valueEquals("Access-Control-Allow-Origin", anotherAllowedOrigin); + } + + @Test + public void whenPreflightControllerCorsExposingHeaders_thenObtainResponseWithCorsHeaders() { + ResponseSpec response = client.options() + .uri(BASE_CORS_ON_CONTROLLER_URL + "/cors-enabled-exposed-header-endpoint") + .header("Origin", CONTROLLER_CORS_ALLOWED_ORIGIN) + .header("Access-Control-Request-Method", "PUT") + .exchange(); + + response.expectHeader() + .valueEquals("Access-Control-Expose-Headers", "Baeldung-Exposed"); + } +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java new file mode 100644 index 0000000000..39927af4c3 --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java @@ -0,0 +1,99 @@ +package com.baeldung.reactive.cors; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class CorsOnGlobalConfigLiveTest { + + private static final String BASE_URL = "http://localhost:8082"; + private static final String BASE_REGULAR_URL = "/cors-on-global-config"; + private static final String BASE_EXTRA_CORS_CONFIG_URL = "/cors-on-global-config-and-more"; + private static final String BASE_FUNCTIONALS_URL = "/global-config-on-functional"; + private static final String CORS_DEFAULT_ORIGIN = "http://allowed-origin.com"; + + private static WebTestClient client; + + @BeforeAll + public static void setup() { + client = WebTestClient.bindToServer() + .baseUrl(BASE_URL) + .defaultHeader("Origin", CORS_DEFAULT_ORIGIN) + .build(); + } + + @Test + public void whenRequestingRegularEndpoint_thenObtainResponseWithCorsHeaders() { + ResponseSpec response = client.put() + .uri(BASE_REGULAR_URL + "/regular-put-endpoint") + .exchange(); + + response.expectHeader() + .valueEquals("Access-Control-Allow-Origin", CORS_DEFAULT_ORIGIN); + } + + @Test + public void whenRequestingRegularDeleteEndpoint_thenObtainForbiddenResponse() { + ResponseSpec response = client.delete() + .uri(BASE_REGULAR_URL + "/regular-delete-endpoint") + .exchange(); + + response.expectStatus() + .isForbidden(); + } + + @Test + public void whenPreflightAllowedDeleteEndpoint_thenObtainResponseWithCorsHeaders() { + ResponseSpec response = client.options() + .uri(BASE_EXTRA_CORS_CONFIG_URL + "/further-mixed-config-endpoint") + .header("Access-Control-Request-Method", "DELETE") + .header("Access-Control-Request-Headers", "Baeldung-Not-Allowed, Baeldung-Allowed, Baeldung-Other-Allowed") + .exchange(); + + response.expectHeader() + .valueEquals("Access-Control-Allow-Origin", CORS_DEFAULT_ORIGIN); + response.expectHeader() + .valueEquals("Access-Control-Allow-Methods", "PUT,DELETE"); + response.expectHeader() + .valueEquals("Access-Control-Allow-Headers", "Baeldung-Allowed, Baeldung-Other-Allowed"); + response.expectHeader() + .exists("Access-Control-Max-Age"); + } + + @Test + public void whenRequestAllowedDeleteEndpoint_thenObtainResponseWithCorsHeaders() { + ResponseSpec response = client.delete() + .uri(BASE_EXTRA_CORS_CONFIG_URL + "/further-mixed-config-endpoint") + .exchange(); + + response.expectStatus() + .isOk(); + } + + @Test + public void whenPreflightFunctionalEndpoint_thenObtain404Response() { + ResponseSpec response = client.options() + .uri(BASE_FUNCTIONALS_URL + "/cors-disabled-functional-endpoint") + .header("Access-Control-Request-Method", "PUT") + .exchange(); + + response.expectStatus() + .isNotFound(); + } + + @Test + public void whenRequestFunctionalEndpoint_thenObtainResponseWithCorsHeaders() { + ResponseSpec response = client.put() + .uri(BASE_FUNCTIONALS_URL + "/cors-disabled-functional-endpoint") + .exchange(); + + response.expectHeader() + .valueEquals("Access-Control-Allow-Origin", CORS_DEFAULT_ORIGIN); + } +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java new file mode 100644 index 0000000000..e5a3c8a99a --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java @@ -0,0 +1,96 @@ +package com.baeldung.reactive.cors; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class CorsOnWebFilterLiveTest { + + private static final String BASE_URL = "http://localhost:8083"; + private static final String BASE_REGULAR_URL = "/web-filter-on-annotated"; + private static final String BASE_EXTRA_CORS_CONFIG_URL = "/web-filter-and-more-on-annotated"; + private static final String BASE_FUNCTIONALS_URL = "/web-filter-on-functional"; + private static final String CORS_DEFAULT_ORIGIN = "http://allowed-origin.com"; + + private static WebTestClient client; + + @BeforeAll + public static void setup() { + client = WebTestClient.bindToServer() + .baseUrl(BASE_URL) + .defaultHeader("Origin", CORS_DEFAULT_ORIGIN) + .build(); + } + + @Test + public void whenRequestingRegularEndpoint_thenObtainResponseWithCorsHeaders() { + ResponseSpec response = client.put() + .uri(BASE_REGULAR_URL + "/regular-put-endpoint") + .exchange(); + + response.expectHeader() + .valueEquals("Access-Control-Allow-Origin", CORS_DEFAULT_ORIGIN); + } + + @Test + public void whenRequestingRegularDeleteEndpoint_thenObtainForbiddenResponse() { + ResponseSpec response = client.delete() + .uri(BASE_REGULAR_URL + "/regular-delete-endpoint") + .exchange(); + + response.expectStatus() + .isForbidden(); + } + + @Test + public void whenPreflightDeleteEndpointWithExtraConfigs_thenObtainForbiddenResponse() { + ResponseSpec response = client.options() + .uri(BASE_EXTRA_CORS_CONFIG_URL + "/further-mixed-config-endpoint") + .header("Access-Control-Request-Method", "DELETE") + .exchange(); + + response.expectStatus() + .isForbidden(); + } + + @Test + public void whenRequestDeleteEndpointWithExtraConfigs_thenObtainForbiddenResponse() { + ResponseSpec response = client.delete() + .uri(BASE_EXTRA_CORS_CONFIG_URL + "/further-mixed-config-endpoint") + .exchange(); + + response.expectStatus() + .isForbidden(); + } + + @Test + public void whenPreflightFunctionalEndpoint_thenObtain404Response() { + ResponseSpec response = client.options() + .uri(BASE_FUNCTIONALS_URL + "/functional-endpoint") + .header("Access-Control-Request-Method", "PUT") + .exchange(); + + response.expectHeader() + .valueEquals("Access-Control-Allow-Origin", CORS_DEFAULT_ORIGIN); + response.expectHeader() + .valueEquals("Access-Control-Allow-Methods", "PUT"); + response.expectHeader() + .valueEquals("Access-Control-Max-Age", "8000"); + } + + @Test + public void whenRequestFunctionalEndpoint_thenObtainResponseWithCorsHeaders() { + ResponseSpec response = client.put() + .uri(BASE_FUNCTIONALS_URL + "/functional-endpoint") + .exchange(); + + response.expectHeader() + .valueEquals("Access-Control-Allow-Origin", CORS_DEFAULT_ORIGIN); + } +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java new file mode 100644 index 0000000000..bea2eaa75f --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java @@ -0,0 +1,168 @@ +package com.baeldung.reactive.errorhandling; + +import java.io.IOException; +import static org.junit.Assert.assertEquals; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) +public class ErrorHandlingIntegrationTest { + + @Autowired + private WebTestClient webTestClient; + + @Test + public void givenErrorReturn_whenUsernamePresent_thenOk() throws IOException { + + String s = webTestClient.get() + .uri("/api/endpoint1?name={username}", "Tony") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .returnResult(String.class) + .getResponseBody() + .blockFirst(); + + assertEquals("Hello, Tony", s); + + } + + @Test + public void givenErrorReturn_whenNoUsername_thenOk() throws IOException { + + String s = webTestClient.get() + .uri("/api/endpoint1") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .returnResult(String.class) + .getResponseBody() + .blockFirst(); + + assertEquals("Hello, Stranger", s); + } + + @Test + public void givenResumeFallback_whenUsernamePresent_thenOk() throws IOException { + + String s = webTestClient.get() + .uri("/api/endpoint2?name={username}", "Tony") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .returnResult(String.class) + .getResponseBody() + .blockFirst(); + + assertEquals("Hello, Tony", s); + } + + @Test + public void givenResumeFallback_whenNoUsername_thenOk() throws IOException { + String s = webTestClient.get() + .uri("/api/endpoint2") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .returnResult(String.class) + .getResponseBody() + .blockFirst(); + + assertEquals("Hello, Stranger", s); + + } + + @Test + public void givenResumeDynamicValue_whenUsernamePresent_thenOk() throws IOException { + + String s = webTestClient.get() + .uri("/api/endpoint3?name={username}", "Tony") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .returnResult(String.class) + .getResponseBody() + .blockFirst(); + + assertEquals("Hello, Tony", s); + } + + @Test + public void givenResumeDynamicValue_whenNoUsername_thenOk() throws IOException { + String s = webTestClient.get() + .uri("/api/endpoint3") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .returnResult(String.class) + .getResponseBody() + .blockFirst(); + + assertEquals("Hi, I looked around for your name but found: No value present", s); + } + + @Test + public void givenResumeRethrow_whenUsernamePresent_thenOk() throws IOException { + String s = webTestClient.get() + .uri("/api/endpoint4?name={username}", "Tony") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .returnResult(String.class) + .getResponseBody() + .blockFirst(); + + assertEquals("Hello, Tony", s); + } + + @Test + public void givenResumeRethrow_whenNoUsername_thenOk() throws IOException { + + webTestClient.get() + .uri("/api/endpoint4") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .expectStatus() + .isBadRequest() + .expectHeader() + .contentType(MediaType.APPLICATION_JSON_UTF8) + .expectBody() + .jsonPath("$.message") + .isNotEmpty() + .jsonPath("$.message") + .isEqualTo("please provide a name"); + } + + @Test + public void givenGlobalErrorHandling_whenUsernamePresent_thenOk() throws IOException { + + String s = webTestClient.get() + .uri("/api/endpoint5?name={username}", "Tony") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .returnResult(String.class) + .getResponseBody() + .blockFirst(); + + assertEquals("Hello, Tony", s); + } + + @Test + public void givenGlobalErrorHandling_whenNoUsername_thenOk() throws IOException { + webTestClient.get() + .uri("/api/endpoint5") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .expectStatus() + .isBadRequest() + .expectHeader() + .contentType(MediaType.APPLICATION_JSON_UTF8) + .expectBody() + .jsonPath("$.message") + .isNotEmpty() + .jsonPath("$.message") + .isEqualTo("please provide a name"); + + } + +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java deleted file mode 100644 index 86f995ed79..0000000000 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.reactive.repository; - - -import com.baeldung.reactive.Spring5ReactiveApplication; -import com.baeldung.reactive.model.Account; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Spring5ReactiveApplication.class) -public class AccountCrudRepositoryIntegrationTest { - - @Autowired - AccountCrudRepository repository; - - @Test - public void givenValue_whenFindAllByValue_thenFindAccount() { - repository.save(new Account(null, "Bill", 12.3)).block(); - Flux accountFlux = repository.findAllByValue(12.3); - Account account = accountFlux.next().block(); - assertEquals("Bill", account.getOwner()); - assertEquals(Double.valueOf(12.3) , account.getValue()); - assertNotNull(account.getId()); - } - - @Test - public void givenOwner_whenFindFirstByOwner_thenFindAccount() { - repository.save(new Account(null, "Bill", 12.3)).block(); - Mono accountMono = repository.findFirstByOwner(Mono.just("Bill")); - Account account = accountMono.block(); - assertEquals("Bill", account.getOwner()); - assertEquals(Double.valueOf(12.3) , account.getValue()); - assertNotNull(account.getId()); - } - - @Test - public void givenAccount_whenSave_thenSaveAccount() { - Mono accountMono = repository.save(new Account(null, "Bill", 12.3)); - assertNotNull(accountMono.block().getId()); - } - - -} \ No newline at end of file diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java deleted file mode 100644 index f95c443b7f..0000000000 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.reactive.repository; - -import com.baeldung.reactive.Spring5ReactiveApplication; -import com.baeldung.reactive.model.Account; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.data.domain.Example; -import org.springframework.data.domain.ExampleMatcher; -import org.springframework.test.context.junit4.SpringRunner; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -import java.util.List; - -import static org.junit.Assert.*; -import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.startsWith; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Spring5ReactiveApplication.class) -public class AccountMongoRepositoryIntegrationTest { - - @Autowired - AccountMongoRepository repository; - - @Test - public void givenExample_whenFindAllWithExample_thenFindAllMacthings() { - repository.save(new Account(null, "john", 12.3)).block(); - ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("owner", startsWith()); - Example example = Example.of(new Account(null, "jo", null), matcher); - Flux accountFlux = repository.findAll(example); - List accounts = accountFlux.collectList().block(); - - assertTrue(accounts.stream().anyMatch(x -> x.getOwner().equals("john"))); - } - - @Test - public void givenAccount_whenSave_thenSave() { - Mono accountMono = repository.save(new Account(null, "john", 12.3)); - assertNotNull(accountMono.block().getId()); - } - - @Test - public void givenId_whenFindById_thenFindAccount() { - Account inserted = repository.save(new Account(null, "john", 12.3)).block(); - Mono accountMono = repository.findById(inserted.getId()); - assertEquals("john", accountMono.block().getOwner()); - assertEquals(Double.valueOf(12.3), accountMono.block().getValue()); - assertNotNull(accountMono.block().getId()); - } -} \ No newline at end of file diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java deleted file mode 100644 index 6199b460d0..0000000000 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.reactive.repository; - -import com.baeldung.reactive.Spring5ReactiveApplication; -import com.baeldung.reactive.model.Account; -import io.reactivex.Observable; -import io.reactivex.Single; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Spring5ReactiveApplication.class) -public class AccountRxJavaRepositoryIntegrationTest { - - @Autowired - AccountRxJavaRepository repository; - - @Test - public void givenValue_whenFindAllByValue_thenFindAccounts() { - repository.save(new Account(null, "bruno", 12.3)).blockingGet(); - Observable accountObservable = repository.findAllByValue(12.3); - Account account = accountObservable.filter(x -> x.getOwner().equals("bruno")).blockingFirst(); - assertEquals("bruno", account.getOwner()); - assertEquals(Double.valueOf(12.3), account.getValue()); - assertNotNull(account.getId()); - } - - @Test - public void givenOwner_whenFindFirstByOwner_thenFindAccount() { - repository.save(new Account(null, "bruno", 12.3)).blockingGet(); - Single accountSingle = repository.findFirstByOwner(Single.just("bruno")); - Account account = accountSingle.blockingGet(); - assertEquals("bruno", account.getOwner()); - assertEquals(Double.valueOf(12.3), account.getValue()); - assertNotNull(account.getId()); - } - -} \ No newline at end of file diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/responseheaders/ResponseHeaderLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/responseheaders/ResponseHeaderLiveTest.java new file mode 100644 index 0000000000..db563e27d1 --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/responseheaders/ResponseHeaderLiveTest.java @@ -0,0 +1,63 @@ +package com.baeldung.reactive.responseheaders; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ResponseHeaderLiveTest { + + private static final String BASE_URL = "http://localhost:8080"; + private static final String ANNOTATION_BASE_URL = BASE_URL + "/response-header"; + private static final String FUNCTIONAL_BASE_URL = BASE_URL + "/functional-response-header"; + private static final String SERVICE_SINGLE_RESPONSE_HEADER = "Baeldung-Example-Header"; + private static final String SERVICE_FILTER_RESPONSE_HEADER = "Baeldung-Example-Filter-Header"; + private static final String SERVICE_FILTER_RESPONSE_HEADER_VALUE = "Value-Filter"; + + private static WebTestClient client; + + @BeforeAll + public static void setup() { + client = WebTestClient.bindToServer() + .baseUrl(BASE_URL) + .build(); + } + + @Test + public void whenUsingResponseEntityBuilderRequest_thenObtainResponseWithCorrectHeaders() { + client = WebTestClient.bindToServer() + .baseUrl(BASE_URL) + .build(); + ResponseSpec response = client.get() + .uri(ANNOTATION_BASE_URL + "/response-entity") + .exchange(); + + response.expectHeader().valueEquals(SERVICE_SINGLE_RESPONSE_HEADER, "Value-ResponseEntityBuilder") + .expectHeader().valueEquals(SERVICE_FILTER_RESPONSE_HEADER, SERVICE_FILTER_RESPONSE_HEADER_VALUE); + } + + @Test + public void whenUsingServerHttpResponseRequest_thenObtainResponseWithCorrectHeaders() { + ResponseSpec response = client.get() + .uri(ANNOTATION_BASE_URL + "/server-http-response") + .exchange(); + + response.expectHeader().valueEquals(SERVICE_SINGLE_RESPONSE_HEADER, "Value-ServerHttpResponse") + .expectHeader().valueEquals(SERVICE_FILTER_RESPONSE_HEADER, SERVICE_FILTER_RESPONSE_HEADER_VALUE); + } + + @Test + public void whenUsingFunctionalHandlerRequest_thenObtainResponseWithCorrectHeaders() { + ResponseSpec response = client.get() + .uri(FUNCTIONAL_BASE_URL + "/single-handler") + .exchange(); + + response.expectHeader().valueEquals(SERVICE_SINGLE_RESPONSE_HEADER, "Value-Handler") + .expectHeader().valueEquals(SERVICE_FILTER_RESPONSE_HEADER, SERVICE_FILTER_RESPONSE_HEADER_VALUE); + } +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java new file mode 100644 index 0000000000..53f4a3b1bb --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java @@ -0,0 +1,49 @@ +package com.baeldung.reactive.serversentsevents; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.reactive.server.WebTestClient; + +@RunWith(JUnitPlatform.class) +@SpringBootTest +public class ServiceSentEventLiveTest { + + private WebTestClient client = WebTestClient.bindToServer() + .baseUrl("http://localhost:8081/sse-server") + .build(); + + @Test + public void whenSSEEndpointIsCalled_thenEventStreamingBegins() { + + Executable sseStreamingCall = () -> client.get() + .uri("/stream-sse") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentTypeCompatibleWith(MediaType.TEXT_EVENT_STREAM) + .expectBody(String.class); + + Assertions.assertThrows(IllegalStateException.class, sseStreamingCall, "Expected test to timeout and throw IllegalStateException, but it didn't"); + } + + @Test + public void whenFluxEndpointIsCalled_thenEventStreamingBegins() { + + Executable sseStreamingCall = () -> client.get() + .uri("/stream-flux") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentTypeCompatibleWith(MediaType.TEXT_EVENT_STREAM) + .expectBody(String.class); + + Assertions.assertThrows(IllegalStateException.class, sseStreamingCall, "Expected test to timeout and throw IllegalStateException, but it didn't"); + } +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java index 21ba11616d..91721d2cef 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java @@ -6,8 +6,6 @@ import org.junit.Test; import org.springframework.boot.web.server.WebServer; import org.springframework.test.web.reactive.server.WebTestClient; -import com.baeldung.reactive.urlmatch.ExploreSpring5URLPatternUsingRouterFunctions; - public class ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest { private static WebTestClient client; diff --git a/spring-5/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java similarity index 90% rename from spring-5/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java rename to spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java index 9a6e997ca1..08bd883b0b 100644 --- a/spring-5/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java @@ -1,6 +1,6 @@ package com.baeldung.web.client; -import com.baeldung.Spring5Application; +import com.baeldung.reactive.Spring5ReactiveApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; @@ -15,7 +15,7 @@ import org.springframework.web.server.WebHandler; import reactor.core.publisher.Mono; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Spring5Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = Spring5ReactiveApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class WebTestClientIntegrationTest { @LocalServerPort @@ -53,7 +53,7 @@ public class WebTestClientIntegrationTest { .uri("/resource") .exchange() .expectStatus() - .is3xxRedirection() + .isOk() .expectBody(); } diff --git a/spring-5-reactive/src/test/resources/baeldung-weekly.png b/spring-5-reactive/src/test/resources/baeldung-weekly.png new file mode 100644 index 0000000000..a1b7eebcab Binary files /dev/null and b/spring-5-reactive/src/test/resources/baeldung-weekly.png differ diff --git a/spring-5-security/README.md b/spring-5-security/README.md index 94a8f83281..55fa7ab042 100644 --- a/spring-5-security/README.md +++ b/spring-5-security/README.md @@ -4,4 +4,5 @@ - [Extra Login Fields with Spring Security](http://www.baeldung.com/spring-security-extra-login-fields) - [A Custom Spring SecurityConfigurer](http://www.baeldung.com/spring-security-custom-configurer) - [New Password Storage In Spring Security 5](http://www.baeldung.com/spring-security-5-password-storage) - +- [Default Password Encoder in Spring Security 5](https://www.baeldung.com/spring-security-5-default-password-encoder) +- [Extracting Principal and Authorities using Spring Security OAuth](https://www.baeldung.com/spring-security-oauth-principal-authorities-extractor) diff --git a/spring-5-security/pom.xml b/spring-5-security/pom.xml index c9b16f8b88..1435019c24 100644 --- a/spring-5-security/pom.xml +++ b/spring-5-security/pom.xml @@ -1,5 +1,5 @@ + 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-security @@ -9,10 +9,10 @@ spring 5 security sample project - org.springframework.boot - spring-boot-starter-parent - 2.0.0.RELEASE - + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 @@ -58,6 +58,12 @@ spring-security-test test + + + org.springframework.security.oauth.boot + spring-security-oauth2-autoconfigure + 2.0.1.RELEASE + @@ -70,48 +76,7 @@ JAR - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - methods - true - - **/*IntegrationTest.java - **/*LiveTest.java - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - UTF-8 - UTF-8 - 1.8 - \ No newline at end of file diff --git a/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthApplication.java b/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthApplication.java new file mode 100644 index 0000000000..6ccfd04553 --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.inmemory; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class InMemoryAuthApplication { + + public static void main(String[] args) { + SpringApplication.run(InMemoryAuthApplication.class, args); + } + + +} diff --git a/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthController.java b/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthController.java new file mode 100644 index 0000000000..ff7ae9a131 --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthController.java @@ -0,0 +1,21 @@ +package com.baeldung.inmemory; + +import java.util.Arrays; +import java.util.List; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class InMemoryAuthController { + + @GetMapping("/public/hello") + public List publicHello() { + return Arrays.asList("Hello", "World", "from", "Public"); + } + + @GetMapping("/private/hello") + public List privateHello() { + return Arrays.asList("Hello", "World", "from", "Private"); + } + +} diff --git a/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthWebSecurityConfigurer.java b/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthWebSecurityConfigurer.java new file mode 100644 index 0000000000..4b32a1126e --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthWebSecurityConfigurer.java @@ -0,0 +1,34 @@ +package com.baeldung.inmemory; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.factory.PasswordEncoderFactories; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class InMemoryAuthWebSecurityConfigurer extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); + auth.inMemoryAuthentication() + .passwordEncoder(encoder) + .withUser("spring") + .password(encoder.encode("secret")) + .roles("USER"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/private/**") + .authenticated() + .antMatchers("/public/**") + .permitAll() + .and() + .httpBasic(); + } + +} diff --git a/spring-5-security/src/main/java/com/baeldung/oauth2extractors/ExtractorsApplication.java b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/ExtractorsApplication.java new file mode 100644 index 0000000000..6ab4d525bf --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/ExtractorsApplication.java @@ -0,0 +1,29 @@ +package com.baeldung.oauth2extractors; + +import org.apache.logging.log4j.util.Strings; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.core.env.AbstractEnvironment; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +@SpringBootApplication +@Controller +public class ExtractorsApplication { + public static void main(String[] args) { + if (Strings.isEmpty(System.getProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME))) { + /*System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, + "oauth2-extractors-baeldung");*/ + System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, + "oauth2-extractors-github"); + } + + SpringApplication.run(ExtractorsApplication.class, args); + } + + @RequestMapping("/") + public String index() { + return "oauth2_extractors"; + } + +} diff --git a/spring-5-security/src/main/java/com/baeldung/oauth2extractors/configuration/SecurityConfig.java b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/configuration/SecurityConfig.java new file mode 100644 index 0000000000..b2ea19c008 --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/configuration/SecurityConfig.java @@ -0,0 +1,55 @@ +package com.baeldung.oauth2extractors.configuration; + +import com.baeldung.oauth2extractors.extractor.custom.BaeldungAuthoritiesExtractor; +import com.baeldung.oauth2extractors.extractor.custom.BaeldungPrincipalExtractor; +import com.baeldung.oauth2extractors.extractor.github.GithubAuthoritiesExtractor; +import com.baeldung.oauth2extractors.extractor.github.GithubPrincipalExtractor; +import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; +import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor; +import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableOAuth2Sso +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.antMatcher("/**") + .authorizeRequests() + .antMatchers("/login**") + .permitAll() + .anyRequest() + .authenticated() + .and() + .formLogin().disable(); + } + + @Bean + @Profile("oauth2-extractors-baeldung") + public PrincipalExtractor baeldungPrincipalExtractor() { + return new BaeldungPrincipalExtractor(); + } + + @Bean + @Profile("oauth2-extractors-baeldung") + public AuthoritiesExtractor baeldungAuthoritiesExtractor() { + return new BaeldungAuthoritiesExtractor(); + } + + @Bean + @Profile("oauth2-extractors-github") + public PrincipalExtractor githubPrincipalExtractor() { + return new GithubPrincipalExtractor(); + } + + @Bean + @Profile("oauth2-extractors-github") + public AuthoritiesExtractor githubAuthoritiesExtractor() { + return new GithubAuthoritiesExtractor(); + } +} \ No newline at end of file diff --git a/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/custom/BaeldungAuthoritiesExtractor.java b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/custom/BaeldungAuthoritiesExtractor.java new file mode 100644 index 0000000000..275bcd0d31 --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/custom/BaeldungAuthoritiesExtractor.java @@ -0,0 +1,29 @@ +package com.baeldung.oauth2extractors.extractor.custom; + +import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.AuthorityUtils; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class BaeldungAuthoritiesExtractor implements AuthoritiesExtractor { + + @Override + public List extractAuthorities(Map map) { + return AuthorityUtils + .commaSeparatedStringToAuthorityList(asAuthorities(map)); + } + + private String asAuthorities(Map map) { + List authorities = new ArrayList<>(); + authorities.add("BAELDUNG_USER"); + List> authz = (List>) map.get("authorities"); + for (LinkedHashMap entry : authz) { + authorities.add(entry.get("authority")); + } + return String.join(",", authorities); + } +} diff --git a/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/custom/BaeldungPrincipalExtractor.java b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/custom/BaeldungPrincipalExtractor.java new file mode 100644 index 0000000000..6f1b20df10 --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/custom/BaeldungPrincipalExtractor.java @@ -0,0 +1,13 @@ +package com.baeldung.oauth2extractors.extractor.custom; + +import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor; + +import java.util.Map; + +public class BaeldungPrincipalExtractor implements PrincipalExtractor { + + @Override + public Object extractPrincipal(Map map) { + return map.get("name"); + } +} diff --git a/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/github/GithubAuthoritiesExtractor.java b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/github/GithubAuthoritiesExtractor.java new file mode 100644 index 0000000000..5d90164f06 --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/github/GithubAuthoritiesExtractor.java @@ -0,0 +1,29 @@ +package com.baeldung.oauth2extractors.extractor.github; + +import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.AuthorityUtils; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +public class GithubAuthoritiesExtractor implements AuthoritiesExtractor { + private List GITHUB_FREE_AUTHORITIES = AuthorityUtils + .commaSeparatedStringToAuthorityList("GITHUB_USER,GITHUB_USER_FREE"); + private List GITHUB_SUBSCRIBED_AUTHORITIES = AuthorityUtils + .commaSeparatedStringToAuthorityList("GITHUB_USER,GITHUB_USER_SUBSCRIBED"); + + @Override + public List extractAuthorities(Map map) { + if (Objects.nonNull(map.get("plan"))) { + if (!((LinkedHashMap) map.get("plan")) + .get("name") + .equals("free")) { + return GITHUB_SUBSCRIBED_AUTHORITIES; + } + } + return GITHUB_FREE_AUTHORITIES; + } +} diff --git a/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/github/GithubPrincipalExtractor.java b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/github/GithubPrincipalExtractor.java new file mode 100644 index 0000000000..fdc5c0c9f3 --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/github/GithubPrincipalExtractor.java @@ -0,0 +1,13 @@ +package com.baeldung.oauth2extractors.extractor.github; + +import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor; + +import java.util.Map; + +public class GithubPrincipalExtractor implements PrincipalExtractor { + + @Override + public Object extractPrincipal(Map map) { + return map.get("login"); + } +} diff --git a/spring-5-security/src/main/resources/application-oauth2-extractors-baeldung.properties b/spring-5-security/src/main/resources/application-oauth2-extractors-baeldung.properties new file mode 100644 index 0000000000..6ef0f5000b --- /dev/null +++ b/spring-5-security/src/main/resources/application-oauth2-extractors-baeldung.properties @@ -0,0 +1,6 @@ +server.port=8082 +security.oauth2.client.client-id=SampleClientId +security.oauth2.client.client-secret=secret +security.oauth2.client.access-token-uri=http://localhost:8081/auth/oauth/token +security.oauth2.client.user-authorization-uri=http://localhost:8081/auth/oauth/authorize +security.oauth2.resource.user-info-uri=http://localhost:8081/auth/user/me \ No newline at end of file diff --git a/spring-5-security/src/main/resources/application-oauth2-extractors-github.properties b/spring-5-security/src/main/resources/application-oauth2-extractors-github.properties new file mode 100644 index 0000000000..8a151dcb98 --- /dev/null +++ b/spring-5-security/src/main/resources/application-oauth2-extractors-github.properties @@ -0,0 +1,7 @@ +server.port=8082 +security.oauth2.client.client-id=89a7c4facbb3434d599d +security.oauth2.client.client-secret=9b3b08e4a340bd20e866787e4645b54f73d74b6a +security.oauth2.client.access-token-uri=https://github.com/login/oauth/access_token +security.oauth2.client.user-authorization-uri=https://github.com/login/oauth/authorize +security.oauth2.client.scope=read:user,user:email +security.oauth2.resource.user-info-uri=https://api.github.com/user \ No newline at end of file diff --git a/spring-5-security/src/main/resources/logback.xml b/spring-5-security/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-5-security/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-5-security/src/main/resources/templates/oauth2_extractors.html b/spring-5-security/src/main/resources/templates/oauth2_extractors.html new file mode 100644 index 0000000000..414dd54a42 --- /dev/null +++ b/spring-5-security/src/main/resources/templates/oauth2_extractors.html @@ -0,0 +1,21 @@ + + + + + Spring Security Principal and Authorities extractor + + + + +
    +
    +

    Secured Page

    + Authenticated username: +
    + Authorities: +
    +
    +
    + + \ No newline at end of file diff --git a/spring-5-security/src/test/java/com/baeldung/inmemory/InMemoryAuthControllerIntegrationTest.java b/spring-5-security/src/test/java/com/baeldung/inmemory/InMemoryAuthControllerIntegrationTest.java new file mode 100644 index 0000000000..9d08cb7cfa --- /dev/null +++ b/spring-5-security/src/test/java/com/baeldung/inmemory/InMemoryAuthControllerIntegrationTest.java @@ -0,0 +1,48 @@ +package com.baeldung.inmemory; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = InMemoryAuthApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class InMemoryAuthControllerIntegrationTest { + + @Autowired + private TestRestTemplate template; + + @Test + public void givenRequestOnPublicService_shouldSucceedWith200() throws Exception { + ResponseEntity result = template.getForEntity("/public/hello", String.class); + assertEquals(HttpStatus.OK, result.getStatusCode()); + } + + @Test + public void givenRequestOnPrivateService_shouldFailWith401() throws Exception { + ResponseEntity result = template.getForEntity("/private/hello", String.class); + assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); + } + + @Test + public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception { + ResponseEntity result = template.withBasicAuth("spring", "secret") + .getForEntity("/private/hello", String.class); + assertEquals(HttpStatus.OK, result.getStatusCode()); + } + + @Test + public void givenInvalidAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception { + ResponseEntity result = template.withBasicAuth("spring", "wrong") + .getForEntity("/private/hello", String.class); + assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); + } + +} diff --git a/spring-5-security/src/test/java/com/baeldung/loginextrafields/AbstractExtraLoginFieldsIntegrationTest.java b/spring-5-security/src/test/java/com/baeldung/loginextrafields/AbstractExtraLoginFieldsIntegrationTest.java new file mode 100644 index 0000000000..c46cbd8113 --- /dev/null +++ b/spring-5-security/src/test/java/com/baeldung/loginextrafields/AbstractExtraLoginFieldsIntegrationTest.java @@ -0,0 +1,46 @@ +package com.baeldung.loginextrafields; + +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.web.FilterChainProxy; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +public abstract class AbstractExtraLoginFieldsIntegrationTest { + + @Autowired + private FilterChainProxy springSecurityFilterChain; + + @Autowired + private WebApplicationContext wac; + + protected MockMvc mockMvc; + + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(wac) + .apply(springSecurity(springSecurityFilterChain)) + .build(); + } + + @Test + public void givenRootPathAccess_thenRedirectToIndex() throws Exception { + this.mockMvc.perform(get("/")) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrlPattern("/index*")); + } + + @Test + public void givenSecuredResource_whenAccessUnauthenticated_thenRequiresAuthentication() throws Exception { + this.mockMvc.perform(get("/user/index")) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrlPattern("**/login")); + } +} diff --git a/spring-5-security/src/test/java/com/baeldung/loginextrafields/AbstractExtraLoginFieldsTest.java b/spring-5-security/src/test/java/com/baeldung/loginextrafields/AbstractExtraLoginFieldsTest.java deleted file mode 100644 index 30b869714f..0000000000 --- a/spring-5-security/src/test/java/com/baeldung/loginextrafields/AbstractExtraLoginFieldsTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.loginextrafields; - -import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.web.FilterChainProxy; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -public abstract class AbstractExtraLoginFieldsTest { - - @Autowired - private FilterChainProxy springSecurityFilterChain; - - @Autowired - private WebApplicationContext wac; - - protected MockMvc mockMvc; - - @Before - public void setup() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(wac) - .apply(springSecurity(springSecurityFilterChain)) - .build(); - } - - @Test - public void givenRootPathAccess_thenRedirectToIndex() throws Exception { - this.mockMvc.perform(get("/")) - .andExpect(status().is3xxRedirection()) - .andExpect(redirectedUrlPattern("/index*")); - } - - @Test - public void givenSecuredResource_whenAccessUnauthenticated_thenRequiresAuthentication() throws Exception { - this.mockMvc.perform(get("/user/index")) - .andExpect(status().is3xxRedirection()) - .andExpect(redirectedUrlPattern("**/login")); - } -} diff --git a/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsFullIntegrationTest.java b/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsFullIntegrationTest.java new file mode 100644 index 0000000000..20826eb9d7 --- /dev/null +++ b/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsFullIntegrationTest.java @@ -0,0 +1,72 @@ +package com.baeldung.loginextrafields; + +import static org.junit.Assert.assertEquals; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.util.ArrayList; +import java.util.Collection; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.web.context.HttpSessionSecurityContextRepository; +import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; + +import com.baeldung.loginextrafieldscustom.ExtraLoginFieldsApplication; +import com.baeldung.loginextrafieldscustom.User; + +@RunWith(SpringRunner.class) +@SpringJUnitWebConfig +@SpringBootTest(classes = ExtraLoginFieldsApplication.class) +public class LoginFieldsFullIntegrationTest extends AbstractExtraLoginFieldsIntegrationTest { + + @Test + public void givenAccessSecuredResource_whenAuthenticated_thenAuthHasExtraFields() throws Exception { + MockHttpServletRequestBuilder securedResourceAccess = get("/user/index"); + MvcResult unauthenticatedResult = mockMvc.perform(securedResourceAccess) + .andExpect(status().is3xxRedirection()) + .andReturn(); + + MockHttpSession session = (MockHttpSession) unauthenticatedResult.getRequest() + .getSession(); + String loginUrl = unauthenticatedResult.getResponse() + .getRedirectedUrl(); + + User user = getUser(); + + mockMvc.perform(post(loginUrl) + .param("username", user.getUsername()) + .param("password", user.getPassword()) + .param("domain", user.getDomain()) + .session(session) + .with(csrf())) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrlPattern("**/user/index")) + .andReturn(); + + mockMvc.perform(securedResourceAccess.session(session)) + .andExpect(status().isOk()); + + SecurityContext securityContext + = (SecurityContext) session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); + Authentication auth = securityContext.getAuthentication(); + assertEquals(((User)auth.getPrincipal()).getDomain(), user.getDomain()); + } + + private User getUser() { + Collection authorities = new ArrayList<>(); + return new User("myusername", "mydomain", "password", true, true, true, true, authorities); + } + +} diff --git a/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsFullTest.java b/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsFullTest.java deleted file mode 100644 index 38c219cb5e..0000000000 --- a/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsFullTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.baeldung.loginextrafields; - -import static org.junit.Assert.assertEquals; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.util.ArrayList; -import java.util.Collection; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.mock.web.MockHttpSession; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.web.context.HttpSessionSecurityContextRepository; -import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; - -import com.baeldung.loginextrafieldscustom.ExtraLoginFieldsApplication; -import com.baeldung.loginextrafieldscustom.User; - -@RunWith(SpringRunner.class) -@SpringJUnitWebConfig -@SpringBootTest(classes = ExtraLoginFieldsApplication.class) -public class LoginFieldsFullTest extends AbstractExtraLoginFieldsTest { - - @Test - public void givenAccessSecuredResource_whenAuthenticated_thenAuthHasExtraFields() throws Exception { - MockHttpServletRequestBuilder securedResourceAccess = get("/user/index"); - MvcResult unauthenticatedResult = mockMvc.perform(securedResourceAccess) - .andExpect(status().is3xxRedirection()) - .andReturn(); - - MockHttpSession session = (MockHttpSession) unauthenticatedResult.getRequest() - .getSession(); - String loginUrl = unauthenticatedResult.getResponse() - .getRedirectedUrl(); - - User user = getUser(); - - mockMvc.perform(post(loginUrl) - .param("username", user.getUsername()) - .param("password", user.getPassword()) - .param("domain", user.getDomain()) - .session(session) - .with(csrf())) - .andExpect(status().is3xxRedirection()) - .andExpect(redirectedUrlPattern("**/user/index")) - .andReturn(); - - mockMvc.perform(securedResourceAccess.session(session)) - .andExpect(status().isOk()); - - SecurityContext securityContext - = (SecurityContext) session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); - Authentication auth = securityContext.getAuthentication(); - assertEquals(((User)auth.getPrincipal()).getDomain(), user.getDomain()); - } - - private User getUser() { - Collection authorities = new ArrayList<>(); - return new User("myusername", "mydomain", "password", true, true, true, true, authorities); - } - -} diff --git a/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsSimpleIntegrationTest.java b/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsSimpleIntegrationTest.java new file mode 100644 index 0000000000..3d0e2a8d09 --- /dev/null +++ b/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsSimpleIntegrationTest.java @@ -0,0 +1,72 @@ +package com.baeldung.loginextrafields; + +import static org.junit.Assert.assertEquals; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.util.ArrayList; +import java.util.Collection; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.web.context.HttpSessionSecurityContextRepository; +import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; + +import com.baeldung.loginextrafieldssimple.ExtraLoginFieldsApplication; +import com.baeldung.loginextrafieldssimple.User; + +@RunWith(SpringRunner.class) +@SpringJUnitWebConfig +@SpringBootTest(classes = ExtraLoginFieldsApplication.class) +public class LoginFieldsSimpleIntegrationTest extends AbstractExtraLoginFieldsIntegrationTest { + + @Test + public void givenAccessSecuredResource_whenAuthenticated_thenAuthHasExtraFields() throws Exception { + MockHttpServletRequestBuilder securedResourceAccess = get("/user/index"); + MvcResult unauthenticatedResult = mockMvc.perform(securedResourceAccess) + .andExpect(status().is3xxRedirection()) + .andReturn(); + + MockHttpSession session = (MockHttpSession) unauthenticatedResult.getRequest() + .getSession(); + String loginUrl = unauthenticatedResult.getResponse() + .getRedirectedUrl(); + + User user = getUser(); + + mockMvc.perform(post(loginUrl) + .param("username", user.getUsername()) + .param("password", user.getPassword()) + .param("domain", user.getDomain()) + .session(session) + .with(csrf())) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrlPattern("**/user/index")) + .andReturn(); + + mockMvc.perform(securedResourceAccess.session(session)) + .andExpect(status().isOk()); + + SecurityContext securityContext + = (SecurityContext) session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); + Authentication auth = securityContext.getAuthentication(); + assertEquals(((User)auth.getPrincipal()).getDomain(), user.getDomain()); + } + + private User getUser() { + Collection authorities = new ArrayList<>(); + return new User("myusername", "mydomain", "password", true, true, true, true, authorities); + } + +} diff --git a/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsSimpleTest.java b/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsSimpleTest.java deleted file mode 100644 index 5c0d462772..0000000000 --- a/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsSimpleTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.baeldung.loginextrafields; - -import static org.junit.Assert.assertEquals; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.util.ArrayList; -import java.util.Collection; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.mock.web.MockHttpSession; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.web.context.HttpSessionSecurityContextRepository; -import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; - -import com.baeldung.loginextrafieldssimple.ExtraLoginFieldsApplication; -import com.baeldung.loginextrafieldssimple.User; - -@RunWith(SpringRunner.class) -@SpringJUnitWebConfig -@SpringBootTest(classes = ExtraLoginFieldsApplication.class) -public class LoginFieldsSimpleTest extends AbstractExtraLoginFieldsTest { - - @Test - public void givenAccessSecuredResource_whenAuthenticated_thenAuthHasExtraFields() throws Exception { - MockHttpServletRequestBuilder securedResourceAccess = get("/user/index"); - MvcResult unauthenticatedResult = mockMvc.perform(securedResourceAccess) - .andExpect(status().is3xxRedirection()) - .andReturn(); - - MockHttpSession session = (MockHttpSession) unauthenticatedResult.getRequest() - .getSession(); - String loginUrl = unauthenticatedResult.getResponse() - .getRedirectedUrl(); - - User user = getUser(); - - mockMvc.perform(post(loginUrl) - .param("username", user.getUsername()) - .param("password", user.getPassword()) - .param("domain", user.getDomain()) - .session(session) - .with(csrf())) - .andExpect(status().is3xxRedirection()) - .andExpect(redirectedUrlPattern("**/user/index")) - .andReturn(); - - mockMvc.perform(securedResourceAccess.session(session)) - .andExpect(status().isOk()); - - SecurityContext securityContext - = (SecurityContext) session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); - Authentication auth = securityContext.getAuthentication(); - assertEquals(((User)auth.getPrincipal()).getDomain(), user.getDomain()); - } - - private User getUser() { - Collection authorities = new ArrayList<>(); - return new User("myusername", "mydomain", "password", true, true, true, true, authorities); - } - -} diff --git a/spring-5-security/src/test/java/com/baeldung/oauth2extractors/ExtractorsUnitTest.java b/spring-5-security/src/test/java/com/baeldung/oauth2extractors/ExtractorsUnitTest.java new file mode 100644 index 0000000000..491d618291 --- /dev/null +++ b/spring-5-security/src/test/java/com/baeldung/oauth2extractors/ExtractorsUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.oauth2extractors; + +import com.baeldung.oauth2extractors.configuration.SecurityConfig; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import javax.servlet.Filter; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ExtractorsApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ContextConfiguration(classes = {SecurityConfig.class}) +@ActiveProfiles("oauth2-extractors-github") +public class ExtractorsUnitTest { + + @Autowired + private WebApplicationContext context; + + @Autowired + private Filter springSecurityFilterChain; + + private MockMvc mvc; + + @Before + public void setup() { + mvc = MockMvcBuilders + .webAppContextSetup(context) + .addFilters(springSecurityFilterChain) + .build(); + } + + @Test + public void contextLoads() throws Exception { + } + + @Test + public void givenValidRequestWithoutAuthentication_shouldFailWith302() throws Exception { + mvc + .perform(get("/")) + .andExpect(status().isFound()) + .andReturn(); + } + +} diff --git a/spring-5/README.md b/spring-5/README.md index de42d965f5..d3c1decbc7 100644 --- a/spring-5/README.md +++ b/spring-5/README.md @@ -6,14 +6,11 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles - [Concurrent Test Execution in Spring 5](http://www.baeldung.com/spring-5-concurrent-tests) -- [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) - [The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5](http://www.baeldung.com/spring-5-junit-config) -- [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) - [Spring 5 Testing with @EnabledIf Annotation](http://www.baeldung.com/spring-5-enabledIf) - [Introduction to Spring REST Docs](http://www.baeldung.com/spring-rest-docs) -- [Spring Security 5 – OAuth2 Login](http://www.baeldung.com/spring-security-5-oauth2-login) - [Spring ResponseStatusException](http://www.baeldung.com/spring-response-status-exception) - [Spring Assert Statements](http://www.baeldung.com/spring-assert) +- [Configuring a Hikari Connection Pool with Spring Boot](https://www.baeldung.com/spring-boot-hikari) + diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 67a6930569..9f60b8a364 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -1,8 +1,7 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-5 0.0.1-SNAPSHOT @@ -11,10 +10,10 @@ spring 5 sample project about new features - org.springframework.boot - spring-boot-starter-parent - 2.0.0.RELEASE - + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 @@ -34,35 +33,14 @@ org.springframework.boot spring-boot-starter-web - - org.springframework.boot - spring-boot-starter-webflux - org.springframework.boot spring-boot-starter-hateoas - - org.projectreactor - reactor-spring - ${reactor-spring.version} - javax.json.bind javax.json.bind-api - - - - - - - - - - - - org.apache.geronimo.specs geronimo-json_1.1_spec @@ -95,63 +73,32 @@ org.springframework spring-test - - org.springframework.boot - spring-boot-starter-test - test - org.springframework.security spring-security-test test - org.apache.commons commons-collections4 - 4.1 + ${commons-collections4.version} test - org.junit.jupiter junit-jupiter-api - - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - test - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - org.springframework.restdocs spring-restdocs-mockmvc test - - org.springframework.restdocs - spring-restdocs-webtestclient - test - org.springframework.restdocs spring-restdocs-restassured test - - @@ -164,21 +111,6 @@ JAR - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - methods - true - - **/*IntegrationTest.java - **/*LiveTest.java - - - org.asciidoctor asciidoctor-maven-plugin @@ -206,15 +138,9 @@ - UTF-8 - UTF-8 - 1.8 - 1.0.0 - 2.20 - 5.0.2.RELEASE - 1.0.1.RELEASE 1.0 1.5.6 + 4.1 ${project.build.directory}/generated-snippets diff --git a/spring-5/src/main/java/com/baeldung/Spring5Application.java b/spring-5/src/main/java/com/baeldung/Spring5Application.java index f321871646..41b5c1eed1 100644 --- a/spring-5/src/main/java/com/baeldung/Spring5Application.java +++ b/spring-5/src/main/java/com/baeldung/Spring5Application.java @@ -2,10 +2,8 @@ package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; @SpringBootApplication -@ComponentScan(basePackages = { "com.baeldung.web" }) public class Spring5Application { public static void main(String[] args) { diff --git a/spring-5/src/main/java/com/baeldung/config/PersistenceConfig.java b/spring-5/src/main/java/com/baeldung/config/PersistenceConfig.java new file mode 100644 index 0000000000..547685970a --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/config/PersistenceConfig.java @@ -0,0 +1,12 @@ +package com.baeldung.config; + +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +@Configuration +@EnableJpaRepositories("com.baeldung.persistence") +@EntityScan("com.baeldung.web") +public class PersistenceConfig { + +} diff --git a/spring-5/src/main/java/com/baeldung/execption/ActorController.java b/spring-5/src/main/java/com/baeldung/exception/ActorController.java similarity index 97% rename from spring-5/src/main/java/com/baeldung/execption/ActorController.java rename to spring-5/src/main/java/com/baeldung/exception/ActorController.java index 6c9c46253a..17a5b80b64 100644 --- a/spring-5/src/main/java/com/baeldung/execption/ActorController.java +++ b/spring-5/src/main/java/com/baeldung/exception/ActorController.java @@ -1,4 +1,4 @@ -package com.baeldung.execption; +package com.baeldung.exception; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; diff --git a/spring-5/src/main/java/com/baeldung/execption/ActorNotFoundException.java b/spring-5/src/main/java/com/baeldung/exception/ActorNotFoundException.java similarity index 92% rename from spring-5/src/main/java/com/baeldung/execption/ActorNotFoundException.java rename to spring-5/src/main/java/com/baeldung/exception/ActorNotFoundException.java index 642c075b5d..7439be414d 100644 --- a/spring-5/src/main/java/com/baeldung/execption/ActorNotFoundException.java +++ b/spring-5/src/main/java/com/baeldung/exception/ActorNotFoundException.java @@ -1,4 +1,4 @@ -package com.baeldung.execption; +package com.baeldung.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; diff --git a/spring-5/src/main/java/com/baeldung/execption/ActorService.java b/spring-5/src/main/java/com/baeldung/exception/ActorService.java similarity index 97% rename from spring-5/src/main/java/com/baeldung/execption/ActorService.java rename to spring-5/src/main/java/com/baeldung/exception/ActorService.java index 956fa92015..0f173d78d6 100644 --- a/spring-5/src/main/java/com/baeldung/execption/ActorService.java +++ b/spring-5/src/main/java/com/baeldung/exception/ActorService.java @@ -1,4 +1,4 @@ -package com.baeldung.execption; +package com.baeldung.exception; import java.util.Arrays; import java.util.List; diff --git a/spring-5/src/main/java/com/baeldung/execption/SpringExceptionApplication.java b/spring-5/src/main/java/com/baeldung/exception/SpringExceptionApplication.java similarity index 92% rename from spring-5/src/main/java/com/baeldung/execption/SpringExceptionApplication.java rename to spring-5/src/main/java/com/baeldung/exception/SpringExceptionApplication.java index 1670da54c3..ed163f7fa7 100644 --- a/spring-5/src/main/java/com/baeldung/execption/SpringExceptionApplication.java +++ b/spring-5/src/main/java/com/baeldung/exception/SpringExceptionApplication.java @@ -1,14 +1,14 @@ -package com.baeldung.execption; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; -import org.springframework.context.annotation.ComponentScan; - -@SpringBootApplication(exclude = SecurityAutoConfiguration.class) -@ComponentScan(basePackages = { "com.baeldung.execption" }) -public class SpringExceptionApplication { - public static void main(String[] args) { - SpringApplication.run(SpringExceptionApplication.class, args); - } +package com.baeldung.exception; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication(exclude = SecurityAutoConfiguration.class) +@ComponentScan(basePackages = { "com.baeldung.execption" }) +public class SpringExceptionApplication { + public static void main(String[] args) { + SpringApplication.run(SpringExceptionApplication.class, args); + } } \ No newline at end of file diff --git a/spring-5/src/main/java/com/baeldung/jupiter/Task.java b/spring-5/src/main/java/com/baeldung/jupiter/Task.java new file mode 100644 index 0000000000..2ea977712c --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/jupiter/Task.java @@ -0,0 +1,28 @@ +package com.baeldung.jupiter; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Task { + + private final String name; + + private final int id; + + public Task(@JsonProperty("name") String name, @JsonProperty("id") int id) { + this.name = name; + this.id = id; + } + + public String getName() { + return this.name; + } + + public int getId() { + return this.id; + } + + @Override + public String toString() { + return "Task{" + "name='" + name + '\'' + ", id=" + id + '}'; + } +} diff --git a/spring-5/src/main/java/com/baeldung/jupiter/TestConfig.java b/spring-5/src/main/java/com/baeldung/jupiter/TestConfig.java index a29f77c5df..ee866007ea 100644 --- a/spring-5/src/main/java/com/baeldung/jupiter/TestConfig.java +++ b/spring-5/src/main/java/com/baeldung/jupiter/TestConfig.java @@ -1,6 +1,5 @@ package com.baeldung.jupiter; -import com.baeldung.web.reactive.Task; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; diff --git a/spring-5/src/main/java/com/baeldung/persistence/FooRepository.java b/spring-5/src/main/java/com/baeldung/persistence/FooRepository.java index 1f1e071158..9270d58d35 100644 --- a/spring-5/src/main/java/com/baeldung/persistence/FooRepository.java +++ b/spring-5/src/main/java/com/baeldung/persistence/FooRepository.java @@ -1,10 +1,9 @@ package com.baeldung.persistence; +import com.baeldung.web.Foo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -import com.baeldung.web.Foo; - public interface FooRepository extends JpaRepository, JpaSpecificationExecutor { } diff --git a/spring-5/src/main/java/com/baeldung/security/GreetController.java b/spring-5/src/main/java/com/baeldung/security/GreetController.java deleted file mode 100644 index 6b69e3bc9b..0000000000 --- a/spring-5/src/main/java/com/baeldung/security/GreetController.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.security; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; -import reactor.core.publisher.Mono; - -import java.security.Principal; - -@RestController -public class GreetController { - - private GreetService greetService; - - public GreetController(GreetService greetService) { - this.greetService = greetService; - } - - @GetMapping("/") - public Mono greet(Mono principal) { - return principal - .map(Principal::getName) - .map(name -> String.format("Hello, %s", name)); - } - - @GetMapping("/admin") - public Mono greetAdmin(Mono principal) { - return principal - .map(Principal::getName) - .map(name -> String.format("Admin access: %s", name)); - } - - @GetMapping("/greetService") - public Mono greetService() { - return greetService.greet(); - } - -} diff --git a/spring-5/src/main/java/com/baeldung/security/SecurityConfig.java b/spring-5/src/main/java/com/baeldung/security/SecurityConfig.java deleted file mode 100644 index a9e44a2eee..0000000000 --- a/spring-5/src/main/java/com/baeldung/security/SecurityConfig.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.security; - -import org.springframework.context.annotation.Bean; -import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity; -import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; -import org.springframework.security.config.web.server.ServerHttpSecurity; -import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.web.server.SecurityWebFilterChain; - -@EnableWebFluxSecurity -@EnableReactiveMethodSecurity -public class SecurityConfig { - - @Bean - public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) { - return http.authorizeExchange() - .pathMatchers("/admin").hasAuthority("ROLE_ADMIN") - .anyExchange().authenticated() - .and().formLogin() - .and().build(); - } - - @Bean - public MapReactiveUserDetailsService userDetailsService() { - UserDetails user = User.withDefaultPasswordEncoder() - .username("user") - .password("password") - .roles("USER") - .build(); - - UserDetails admin = User.withDefaultPasswordEncoder() - .username("admin") - .password("password") - .roles("ADMIN") - .build(); - - return new MapReactiveUserDetailsService(user, admin); - } - -} 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 925f2b49f4..a09e628421 100644 --- a/spring-5/src/main/java/com/baeldung/web/FooController.java +++ b/spring-5/src/main/java/com/baeldung/web/FooController.java @@ -7,6 +7,7 @@ import org.springframework.http.HttpStatus; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; +import javax.annotation.PostConstruct; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import java.util.List; @@ -14,6 +15,11 @@ import java.util.List; @RestController("/foos") public class FooController { + @PostConstruct + public void init(){ + System.out.println("test"); + } + @Autowired private FooRepository repo; diff --git a/spring-5/src/main/resources/logback.xml b/spring-5/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-5/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java b/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java index 8b9e66213f..ecc677465e 100644 --- a/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java @@ -3,10 +3,12 @@ package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest +@EnableJpaRepositories("com.baeldung.persistence") public class Example1IntegrationTest { @Test diff --git a/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java b/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java index 6ed53ca4e9..e1d56c2fc3 100644 --- a/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java @@ -3,10 +3,12 @@ package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest +@EnableJpaRepositories("com.baeldung.persistence") public class Example2IntegrationTest { @Test diff --git a/spring-5/src/test/java/com/baeldung/Spring5ApplicationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/Spring5ApplicationIntegrationTest.java index af288c3c2d..1bbf0e3775 100644 --- a/spring-5/src/test/java/com/baeldung/Spring5ApplicationIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/Spring5ApplicationIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; @@ -7,6 +8,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest +@Ignore public class Spring5ApplicationIntegrationTest { @Test diff --git a/spring-5/src/test/java/com/baeldung/connectionpool/ApplicationWithHikariConnectionPool.java b/spring-5/src/test/java/com/baeldung/connectionpool/ApplicationWithHikariConnectionPool.java new file mode 100644 index 0000000000..0bd8637681 --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/connectionpool/ApplicationWithHikariConnectionPool.java @@ -0,0 +1,12 @@ +package com.baeldung.connectionpool; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationWithHikariConnectionPool { + + public static void main(String[] args) { + SpringApplication.run(ApplicationWithHikariConnectionPool.class, args); + } +} diff --git a/spring-5/src/test/java/com/baeldung/connectionpool/HikariIntegrationTest.java b/spring-5/src/test/java/com/baeldung/connectionpool/HikariIntegrationTest.java new file mode 100644 index 0000000000..d91cca85ee --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/connectionpool/HikariIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.connectionpool; + +import static org.junit.Assert.*; + +import javax.sql.DataSource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class HikariIntegrationTest { + + @Autowired + private DataSource dataSource; + + @Test + public void hikariConnectionPoolIsConfigured() { + assertEquals("com.zaxxer.hikari.HikariDataSource", dataSource.getClass() + .getName()); + } + +} diff --git a/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java index 5392a59343..fba01726f4 100644 --- a/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java @@ -6,6 +6,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.context.support.GenericWebApplicationContext; @@ -13,6 +14,7 @@ import com.baeldung.Spring5Application; @RunWith(SpringRunner.class) @SpringBootTest(classes = Spring5Application.class) +@EnableJpaRepositories("com.baeldung.persistence") public class BeanRegistrationIntegrationTest { @Autowired diff --git a/spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java b/spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java deleted file mode 100644 index c52e18ef7f..0000000000 --- a/spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.jdbc.autogenkey; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate; -import com.baeldung.jdbc.autogenkey.repository.MessageRepositorySimpleJDBCInsert; - -@RunWith(SpringRunner.class) -public class GetAutoGenKeyByJDBC { - - @Configuration - @EnableAutoConfiguration - @PropertySource("classpath:autogenkey-db.properties") - @ComponentScan(basePackages = { "com.baeldung.jdbc.autogenkey.repository" }) - public static class SpringConfig { - - } - - @Autowired - MessageRepositorySimpleJDBCInsert messageRepositorySimpleJDBCInsert; - - @Autowired - MessageRepositoryJDBCTemplate messageRepositoryJDBCTemplate; - - final String MESSAGE_CONTENT = "Test"; - - @Test - public void insertJDBC_whenLoadMessageByKey_thenGetTheSameMessage() { - long key = messageRepositoryJDBCTemplate.insert(MESSAGE_CONTENT); - String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key); - - assertEquals(MESSAGE_CONTENT, loadedMessage); - - } - - @Test - public void insertSimpleInsert_whenLoadMessageKey_thenGetTheSameMessage() { - long key = messageRepositorySimpleJDBCInsert.insert(MESSAGE_CONTENT); - String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key); - - assertEquals(MESSAGE_CONTENT, loadedMessage); - } - -} diff --git a/spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBCIntTest.java b/spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBCIntTest.java new file mode 100644 index 0000000000..14d2fb736b --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBCIntTest.java @@ -0,0 +1,55 @@ +package com.baeldung.jdbc.autogenkey; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate; +import com.baeldung.jdbc.autogenkey.repository.MessageRepositorySimpleJDBCInsert; + +@RunWith(SpringRunner.class) +@Ignore +public class GetAutoGenKeyByJDBCIntTest { + + @Configuration + @EnableAutoConfiguration + @PropertySource("classpath:autogenkey-db.properties") + @ComponentScan(basePackages = { "com.baeldung.jdbc.autogenkey.repository" }) + public static class SpringConfig { + + } + + @Autowired + MessageRepositorySimpleJDBCInsert messageRepositorySimpleJDBCInsert; + + @Autowired + MessageRepositoryJDBCTemplate messageRepositoryJDBCTemplate; + + final String MESSAGE_CONTENT = "Test"; + + @Test + public void insertJDBC_whenLoadMessageByKey_thenGetTheSameMessage() { + long key = messageRepositoryJDBCTemplate.insert(MESSAGE_CONTENT); + String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key); + + assertEquals(MESSAGE_CONTENT, loadedMessage); + + } + + @Test + public void insertSimpleInsert_whenLoadMessageKey_thenGetTheSameMessage() { + long key = messageRepositorySimpleJDBCInsert.insert(MESSAGE_CONTENT); + String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key); + + assertEquals(MESSAGE_CONTENT, loadedMessage); + } + +} diff --git a/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java index 756b303f3b..f4749c0d33 100644 --- a/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java @@ -5,6 +5,7 @@ import static org.junit.Assert.assertTrue; import java.math.BigDecimal; import java.time.LocalDate; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -16,18 +17,15 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = Spring5Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@Ignore 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) + ResponseEntity response = template .getForEntity("/person/1", Person.class); Person person = response.getBody(); assertTrue(person.equals(new Person(2, "Jhon", "jhon1@test.com", 0, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500.0)))); @@ -35,8 +33,8 @@ public class JsonbIntegrationTest { @Test public void whenSendPostAPerson_thenGetOkStatus() { - ResponseEntity response = template.withBasicAuth(username, password) - .postForEntity("/person", "{\"birthDate\":\"07-09-2017\",\"email\":\"jhon1@test.com\",\"person-name\":\"Jhon\",\"id\":10}", Boolean.class); + ResponseEntity response = template.withBasicAuth("user","password"). + postForEntity("/person", "{\"birthDate\":\"07-09-2017\",\"email\":\"jhon1@test.com\",\"person-name\":\"Jhon\",\"id\":10}", Boolean.class); assertTrue(response.getBody()); } diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationIntegrationTest.java new file mode 100644 index 0000000000..35363e0ea3 --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationIntegrationTest.java @@ -0,0 +1,50 @@ +package com.baeldung.jupiter; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit.jupiter.DisabledIf; +import org.springframework.test.context.junit.jupiter.EnabledIf; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +@SpringJUnitConfig(Spring5EnabledAnnotationIntegrationTest.Config.class) +@TestPropertySource(properties = { "tests.enabled=true" }) +public class Spring5EnabledAnnotationIntegrationTest { + + @Configuration + static class Config { + } + + @EnabledIf("true") + @Test + void givenEnabledIfLiteral_WhenTrue_ThenTestExecuted() { + assertTrue(true); + } + + @EnabledIf(expression = "${tests.enabled}", loadContext = true) + @Test + void givenEnabledIfExpression_WhenTrue_ThenTestExecuted() { + assertTrue(true); + } + + @EnabledIf("#{systemProperties['java.version'].startsWith('1.8')}") + @Test + void givenEnabledIfSpel_WhenTrue_ThenTestExecuted() { + assertTrue(true); + } + + @EnabledOnJava8 + @Test + void givenEnabledOnJava8_WhenTrue_ThenTestExecuted() { + assertTrue(true); + } + + @DisabledIf("#{systemProperties['java.version'].startsWith('1.7')}") + @Test + void givenDisabledIf_WhenTrue_ThenTestNotExecuted() { + assertTrue(true); + } + +} diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationTest.java deleted file mode 100644 index ae058bc8ba..0000000000 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.jupiter; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.jupiter.api.Test; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit.jupiter.DisabledIf; -import org.springframework.test.context.junit.jupiter.EnabledIf; -import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; - -@SpringJUnitConfig(Spring5EnabledAnnotationTest.Config.class) -@TestPropertySource(properties = { "tests.enabled=true" }) -public class Spring5EnabledAnnotationTest { - - @Configuration - static class Config { - } - - @EnabledIf("true") - @Test - void givenEnabledIfLiteral_WhenTrue_ThenTestExecuted() { - assertTrue(true); - } - - @EnabledIf(expression = "${tests.enabled}", loadContext = true) - @Test - void givenEnabledIfExpression_WhenTrue_ThenTestExecuted() { - assertTrue(true); - } - - @EnabledIf("#{systemProperties['java.version'].startsWith('1.8')}") - @Test - void givenEnabledIfSpel_WhenTrue_ThenTestExecuted() { - assertTrue(true); - } - - @EnabledOnJava8 - @Test - void givenEnabledOnJava8_WhenTrue_ThenTestExecuted() { - assertTrue(true); - } - - @DisabledIf("#{systemProperties['java.version'].startsWith('1.7')}") - @Test - void givenDisabledIf_WhenTrue_ThenTestNotExecuted() { - assertTrue(true); - } - -} diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ComposedAnnotationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ComposedAnnotationIntegrationTest.java index 42d27b90f4..b9bb470cbd 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ComposedAnnotationIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ComposedAnnotationIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.jupiter; -import com.baeldung.web.reactive.Task; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5IntegrationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5IntegrationTest.java index 0f00a85832..484b366132 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5IntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5IntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.jupiter; -import com.baeldung.web.reactive.Task; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigIntegrationTest.java new file mode 100644 index 0000000000..5f81c94aa0 --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigIntegrationTest.java @@ -0,0 +1,33 @@ +package com.baeldung.jupiter; + +import static org.junit.Assert.assertNotNull; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +/** + * @SpringJUnitConfig(SpringJUnitConfigTest.Config.class) is equivalent to: + * + * @ExtendWith(SpringExtension.class) + * @ContextConfiguration(classes = SpringJUnitConfigTest.Config.class ) + * + */ +@SpringJUnitConfig(SpringJUnitConfigIntegrationTest.Config.class) +public class SpringJUnitConfigIntegrationTest { + + @Configuration + static class Config { + } + + @Autowired + private ApplicationContext applicationContext; + + @Test + void givenAppContext_WhenInjected_ThenItShouldNotBeNull() { + assertNotNull(applicationContext); + } + +} diff --git a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigTest.java b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigTest.java deleted file mode 100644 index 6b0a6f9808..0000000000 --- a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.jupiter; - -import static org.junit.Assert.assertNotNull; - -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; - -/** - * @SpringJUnitConfig(SpringJUnitConfigTest.Config.class) is equivalent to: - * - * @ExtendWith(SpringExtension.class) - * @ContextConfiguration(classes = SpringJUnitConfigTest.Config.class ) - * - */ -@SpringJUnitConfig(SpringJUnitConfigTest.Config.class) -public class SpringJUnitConfigTest { - - @Configuration - static class Config { - } - - @Autowired - private ApplicationContext applicationContext; - - @Test - void givenAppContext_WhenInjected_ThenItShouldNotBeNull() { - assertNotNull(applicationContext); - } - -} diff --git a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigIntegrationTest.java new file mode 100644 index 0000000000..4c3ffda203 --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigIntegrationTest.java @@ -0,0 +1,34 @@ +package com.baeldung.jupiter; + +import static org.junit.Assert.assertNotNull; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; +import org.springframework.web.context.WebApplicationContext; + +/** + * @SpringJUnitWebConfig(SpringJUnitWebConfigTest.Config.class) is equivalent to: + * + * @ExtendWith(SpringExtension.class) + * @WebAppConfiguration + * @ContextConfiguration(classes = SpringJUnitWebConfigTest.Config.class ) + * + */ +@SpringJUnitWebConfig(SpringJUnitWebConfigIntegrationTest.Config.class) +public class SpringJUnitWebConfigIntegrationTest { + + @Configuration + static class Config { + } + + @Autowired + private WebApplicationContext webAppContext; + + @Test + void givenWebAppContext_WhenInjected_ThenItShouldNotBeNull() { + assertNotNull(webAppContext); + } + +} diff --git a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigTest.java b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigTest.java deleted file mode 100644 index c679dce77f..0000000000 --- a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.jupiter; - -import static org.junit.Assert.assertNotNull; - -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; -import org.springframework.web.context.WebApplicationContext; - -/** - * @SpringJUnitWebConfig(SpringJUnitWebConfigTest.Config.class) is equivalent to: - * - * @ExtendWith(SpringExtension.class) - * @WebAppConfiguration - * @ContextConfiguration(classes = SpringJUnitWebConfigTest.Config.class ) - * - */ -@SpringJUnitWebConfig(SpringJUnitWebConfigTest.Config.class) -public class SpringJUnitWebConfigTest { - - @Configuration - static class Config { - } - - @Autowired - private WebApplicationContext webAppContext; - - @Test - void givenWebAppContext_WhenInjected_ThenItShouldNotBeNull() { - assertNotNull(webAppContext); - } - -} diff --git a/spring-5/src/test/resources/logback-test.xml b/spring-5/src/test/resources/logback-test.xml index 84f8e4706a..424ab87f79 100644 --- a/spring-5/src/test/resources/logback-test.xml +++ b/spring-5/src/test/resources/logback-test.xml @@ -1,5 +1,15 @@ - - + + + # Pattern of log message for console appender + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml index 5b6911a450..0a19f483c1 100644 --- a/spring-activiti/pom.xml +++ b/spring-activiti/pom.xml @@ -1,26 +1,24 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.example spring-activiti - 0.0.1-SNAPSHOT jar spring-activiti Demo project for Spring Boot - org.springframework.boot - spring-boot-starter-parent - 1.5.4.RELEASE - + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-1 org.activiti activiti-spring-boot-starter-basic - 6.0.0 + ${activiti.version} org.activiti @@ -44,32 +42,6 @@ - - - - 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 - - - - - - - com.example.activitiwithspring.ActivitiWithSpringApplication UTF-8 diff --git a/spring-activiti/src/main/resources/logback.xml b/spring-activiti/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-activiti/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-akka/pom.xml b/spring-akka/pom.xml index d68e8c211b..92b3f1162d 100644 --- a/spring-akka/pom.xml +++ b/spring-akka/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 com.baeldung spring-akka diff --git a/spring-akka/src/main/resources/logback.xml b/spring-akka/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-akka/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-all/README.md b/spring-all/README.md index 173f410620..ded5e26285 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -28,3 +28,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [How To Do @Async in Spring](http://www.baeldung.com/spring-async) - [Quick Guide to the Spring @Order Annotation](http://www.baeldung.com/spring-order) - [Spring Web Contexts](http://www.baeldung.com/spring-web-contexts) +- [Spring Cache – Creating a Custom KeyGenerator](http://www.baeldung.com/spring-cache-custom-keygenerator) +- [Spring @Primary Annotation](http://www.baeldung.com/spring-primary) diff --git a/spring-all/pom.xml b/spring-all/pom.xml index f9ced963e7..c4c4cf7963 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -1,5 +1,5 @@ + 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-all @@ -8,10 +8,10 @@ war - parent-boot-5 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-2 @@ -39,7 +39,6 @@ org.springframework.retry spring-retry - ${springretry.version} org.springframework.shell @@ -55,11 +54,11 @@ org.hibernate hibernate-core - ${hibernate.version} org.javassist javassist + ${javassist.version} mysql @@ -74,6 +73,7 @@ org.hibernate hibernate-validator + ${hibernate.version} @@ -112,7 +112,6 @@ org.assertj assertj-core - ${assertj.version} test @@ -139,17 +138,14 @@ org.ehcache ehcache - ${ehcache.version} org.apache.logging.log4j log4j-api - ${log4j.version} org.apache.logging.log4j log4j-core - ${log4j.version} @@ -187,6 +183,7 @@ org.apache.maven.plugins maven-war-plugin + 3.2.2 false @@ -197,23 +194,20 @@ org.baeldung.sample.App - 4.3.4.RELEASE - 4.2.0.RELEASE - 1.1.5.RELEASE + 5.0.6.RELEASE 1.2.0.RELEASE 5.2.5.Final - 19.0 - 3.1.3 - 3.4 + 25.1-jre + 3.5.2 + 3.6 3.6.1 - 6.4.0 - - 2.8.2 + 6.6.0 + 3.22.0-GA diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java b/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java index 4df1e2e73b..318dc5ea65 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java +++ b/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java @@ -4,9 +4,11 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer; -public class AnnotationsBasedApplicationAndServletInitializer extends AbstractDispatcherServletInitializer { +public class AnnotationsBasedApplicationAndServletInitializer //extends AbstractDispatcherServletInitializer +{ - @Override + //uncomment to run the multiple contexts example + //@Override protected WebApplicationContext createRootApplicationContext() { //If this is not the only class declaring a root context, we return null because it would clash //with other classes, as there can only be a single root context. @@ -17,19 +19,19 @@ public class AnnotationsBasedApplicationAndServletInitializer extends AbstractDi return null; } - @Override + //@Override protected WebApplicationContext createServletApplicationContext() { AnnotationConfigWebApplicationContext normalWebAppContext = new AnnotationConfigWebApplicationContext(); normalWebAppContext.register(NormalWebAppConfig.class); return normalWebAppContext; } - @Override + //@Override protected String[] getServletMappings() { return new String[] { "/api/*" }; } - @Override + //@Override protected String getServletName() { return "normal-dispatcher"; } diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java b/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java index 0d2674d4f3..b685d2fa83 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java +++ b/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java @@ -4,9 +4,10 @@ import org.springframework.web.context.AbstractContextLoaderInitializer; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -public class AnnotationsBasedApplicationInitializer extends AbstractContextLoaderInitializer { - - @Override +public class AnnotationsBasedApplicationInitializer //extends AbstractContextLoaderInitializer +{ + //uncomment to run the multiple contexts example + // @Override protected WebApplicationContext createRootApplicationContext() { AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(RootApplicationConfig.class); diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java b/spring-all/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java index 09e0742394..15a2631cbb 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java +++ b/spring-all/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java @@ -12,9 +12,10 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon import org.springframework.web.context.support.XmlWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; -public class ApplicationInitializer implements WebApplicationInitializer { - - @Override +public class ApplicationInitializer //implements WebApplicationInitializer +{ + //uncomment to run the multiple contexts example + //@Override public void onStartup(ServletContext servletContext) throws ServletException { //Here, we can define a root context and register servlets, among other things. //However, since we've later defined other classes to do the same and they would clash, diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java b/spring-all/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java index c250cedc49..3da3d3beb1 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java +++ b/spring-all/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java @@ -5,14 +5,14 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.baeldung.contexts.normal" }) -public class NormalWebAppConfig extends WebMvcConfigurerAdapter { +public class NormalWebAppConfig implements WebMvcConfigurer { @Bean public ViewResolver viewResolver() { diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java b/spring-all/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java index 89ce0153f5..d74d4a6c63 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java +++ b/spring-all/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java @@ -4,27 +4,29 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer; -public class SecureAnnotationsBasedApplicationAndServletInitializer extends AbstractDispatcherServletInitializer { - - @Override +public class SecureAnnotationsBasedApplicationAndServletInitializer// extends AbstractDispatcherServletInitializer +{ + + //uncomment to run the multiple contexts example + //@Override protected WebApplicationContext createRootApplicationContext() { return null; } - @Override + //@Override protected WebApplicationContext createServletApplicationContext() { AnnotationConfigWebApplicationContext secureWebAppContext = new AnnotationConfigWebApplicationContext(); secureWebAppContext.register(SecureWebAppConfig.class); return secureWebAppContext; } - @Override + //@Override protected String[] getServletMappings() { return new String[] { "/s/api/*" }; } - @Override + //@Override protected String getServletName() { return "secure-dispatcher"; } diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java b/spring-all/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java index f499a4ceba..acc1e3092b 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java +++ b/spring-all/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java @@ -5,14 +5,14 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.baeldung.contexts.secure" }) -public class SecureWebAppConfig extends WebMvcConfigurerAdapter { +public class SecureWebAppConfig implements WebMvcConfigurer { @Bean public ViewResolver viewResolver() { diff --git a/spring-all/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java b/spring-all/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java index fbe3dfb398..8b58c51eb3 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java +++ b/spring-all/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java @@ -3,14 +3,12 @@ package com.baeldung.contexts.normal; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.context.ContextLoader; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; -import com.baeldung.contexts.services.ApplicationContextUtilService; import com.baeldung.contexts.services.GreeterService; @Controller diff --git a/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java b/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java index 3dc4db53c0..85305e057f 100644 --- a/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java +++ b/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java @@ -4,29 +4,27 @@ import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; +import org.springframework.context.support.GenericApplicationContext; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; -public class StudentControllerConfig implements WebApplicationInitializer { +public class StudentControllerConfig //implements WebApplicationInitializer +{ - @Override + //uncomment to run the student controller example + //@Override public void onStartup(ServletContext sc) throws ServletException { AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); root.register(WebConfig.class); - root.setServletContext(sc); + sc.addListener(new ContextLoaderListener(root)); - //Manages the lifecycle of the root application context. - //Conflicts with other root contexts in the application, so we've manually set the parent below. - //sc.addListener(new ContextLoaderListener(root)); - - GenericWebApplicationContext webApplicationContext = new GenericWebApplicationContext(); - webApplicationContext.setParent(root); - DispatcherServlet dv = new DispatcherServlet(webApplicationContext); - + DispatcherServlet dv = new DispatcherServlet(root); + ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc", dv); appServlet.setLoadOnStartup(1); appServlet.addMapping("/test/*"); diff --git a/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java b/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java index 251a1affa1..a17210f3b8 100644 --- a/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java +++ b/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java @@ -6,13 +6,13 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "org.baeldung.controller.controller", "org.baeldung.controller.config" }) -public class WebConfig extends WebMvcConfigurerAdapter { +public class WebConfig implements WebMvcConfigurer { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); diff --git a/spring-all/src/main/java/org/baeldung/primary/Config.java b/spring-all/src/main/java/org/baeldung/primary/Config.java new file mode 100644 index 0000000000..b39f2b9db3 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/primary/Config.java @@ -0,0 +1,22 @@ +package org.baeldung.primary; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; + +@Configuration +@ComponentScan(basePackages="org.baeldung.primary") +public class Config { + + @Bean + public Employee JohnEmployee(){ + return new Employee("John"); + } + + @Bean + @Primary + public Employee TonyEmployee(){ + return new Employee("Tony"); + } +} diff --git a/spring-all/src/main/java/org/baeldung/primary/DepartmentManager.java b/spring-all/src/main/java/org/baeldung/primary/DepartmentManager.java new file mode 100644 index 0000000000..2603951b4e --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/primary/DepartmentManager.java @@ -0,0 +1,11 @@ +package org.baeldung.primary; + +import org.springframework.stereotype.Component; + +@Component +public class DepartmentManager implements Manager { + @Override + public String getManagerName() { + return "Department manager"; + } +} diff --git a/spring-all/src/main/java/org/baeldung/primary/Employee.java b/spring-all/src/main/java/org/baeldung/primary/Employee.java new file mode 100644 index 0000000000..9168387613 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/primary/Employee.java @@ -0,0 +1,20 @@ +package org.baeldung.primary; + +/** + * Created by Gebruiker on 7/17/2018. + */ +public class Employee { + + private String name; + + public Employee(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Employee{" + + "name='" + name + '\'' + + '}'; + } +} diff --git a/spring-all/src/main/java/org/baeldung/primary/GeneralManager.java b/spring-all/src/main/java/org/baeldung/primary/GeneralManager.java new file mode 100644 index 0000000000..0a94f0f96a --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/primary/GeneralManager.java @@ -0,0 +1,14 @@ +package org.baeldung.primary; + +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Component; + +@Component +@Primary +public class GeneralManager implements Manager { + + @Override + public String getManagerName() { + return "General manager"; + } +} diff --git a/spring-all/src/main/java/org/baeldung/primary/Manager.java b/spring-all/src/main/java/org/baeldung/primary/Manager.java new file mode 100644 index 0000000000..4666a1babf --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/primary/Manager.java @@ -0,0 +1,8 @@ +package org.baeldung.primary; + +/** + * Created by Gebruiker on 7/19/2018. + */ +public interface Manager { + String getManagerName(); +} diff --git a/spring-all/src/main/java/org/baeldung/primary/ManagerService.java b/spring-all/src/main/java/org/baeldung/primary/ManagerService.java new file mode 100644 index 0000000000..94ea6785c9 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/primary/ManagerService.java @@ -0,0 +1,17 @@ +package org.baeldung.primary; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * Created by Gebruiker on 7/19/2018. + */@Service +public class ManagerService { + + @Autowired + private Manager manager; + + public Manager getManager() { + return manager; + } +} diff --git a/spring-all/src/main/java/org/baeldung/primary/PrimaryApplication.java b/spring-all/src/main/java/org/baeldung/primary/PrimaryApplication.java new file mode 100644 index 0000000000..ffa2a4028d --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/primary/PrimaryApplication.java @@ -0,0 +1,20 @@ +package org.baeldung.primary; + +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + + +public class PrimaryApplication { + + public static void main(String[] args) { + AnnotationConfigApplicationContext context + = new AnnotationConfigApplicationContext(Config.class); + + Employee employee = context.getBean(Employee.class); + System.out.println(employee); + + ManagerService service = context.getBean(ManagerService.class); + Manager manager = service.getManager(); + System.out.println(manager.getManagerName()); + } + +} diff --git a/spring-all/src/main/java/org/baeldung/spring/config/CoreConfig.java b/spring-all/src/main/java/org/baeldung/spring/config/CoreConfig.java index 21b67933ef..0d753dc447 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/CoreConfig.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/CoreConfig.java @@ -8,11 +8,11 @@ import java.util.concurrent.TimeUnit; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @ComponentScan("org.baeldung.core") -public class CoreConfig extends WebMvcConfigurerAdapter { +public class CoreConfig implements WebMvcConfigurer { public CoreConfig() { super(); diff --git a/spring-all/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java b/spring-all/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java index a857783c60..9f4b73f609 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java @@ -6,13 +6,16 @@ import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; +import org.springframework.context.support.GenericApplicationContext; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; -public class MainWebAppInitializer implements WebApplicationInitializer { +public class MainWebAppInitializer implements WebApplicationInitializer +{ /** * Register and configure all Servlet container components necessary to power the web application. @@ -26,14 +29,11 @@ public class MainWebAppInitializer implements WebApplicationInitializer { root.scan("org.baeldung.spring.config"); // root.getEnvironment().setDefaultProfiles("embedded"); - //Manages the lifecycle of the root application context. - //Conflicts with other root contexts in the application, so we've manually set the parent below. - //sc.addListener(new ContextLoaderListener(root)); + sc.addListener(new ContextLoaderListener(root)); - // Handles requests into the application - GenericWebApplicationContext webApplicationContext = new GenericWebApplicationContext(); - webApplicationContext.setParent(root); - final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(webApplicationContext)); + DispatcherServlet dv = new DispatcherServlet(root); + + final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc",dv); appServlet.setLoadOnStartup(1); final Set mappingConflicts = appServlet.addMapping("/"); if (!mappingConflicts.isEmpty()) { diff --git a/spring-all/src/main/java/org/baeldung/spring/config/MvcConfig.java b/spring-all/src/main/java/org/baeldung/spring/config/MvcConfig.java index f87e400fce..e550733c47 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/MvcConfig.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/MvcConfig.java @@ -5,13 +5,13 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration -public class MvcConfig extends WebMvcConfigurerAdapter { +public class MvcConfig implements WebMvcConfigurer { public MvcConfig() { super(); @@ -21,8 +21,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/sample.html"); } diff --git a/spring-all/src/main/java/org/baeldung/spring/config/PersistenceConfig.java b/spring-all/src/main/java/org/baeldung/spring/config/PersistenceConfig.java index d57151e259..ffe88596fa 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/PersistenceConfig.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/PersistenceConfig.java @@ -11,8 +11,8 @@ import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.orm.hibernate5.HibernateTransactionManager; +import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.google.common.base.Preconditions; diff --git a/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java b/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java index a9bc298db3..fb34725508 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java @@ -38,7 +38,7 @@ public class ScopesConfig { } @Bean - @Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) + @Scope(value = WebApplicationContext.SCOPE_APPLICATION, proxyMode = ScopedProxyMode.TARGET_CLASS) public HelloMessageGenerator globalSessionMessage() { return new HelloMessageGenerator(); } diff --git a/spring-all/src/main/resources/logback.xml b/spring-all/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-all/src/main/resources/logback.xml +++ b/spring-all/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-all/src/main/webapp/WEB-INF/web.xml b/spring-all/src/main/webapp/WEB-INF/web-old.xml similarity index 100% rename from spring-all/src/main/webapp/WEB-INF/web.xml rename to spring-all/src/main/webapp/WEB-INF/web-old.xml diff --git a/spring-all/src/test/java/org/baeldung/controller/PassParametersControllerIntegrationTest.java b/spring-all/src/test/java/org/baeldung/controller/PassParametersControllerIntegrationTest.java new file mode 100644 index 0000000000..21084f44ce --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/controller/PassParametersControllerIntegrationTest.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 PassParametersControllerIntegrationTest { + 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-all/src/test/java/org/baeldung/controller/PassParametersControllerTest.java b/spring-all/src/test/java/org/baeldung/controller/PassParametersControllerTest.java deleted file mode 100644 index 76ac14f292..0000000000 --- a/spring-all/src/test/java/org/baeldung/controller/PassParametersControllerTest.java +++ /dev/null @@ -1,69 +0,0 @@ -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-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationConfiguration.java b/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationConfiguration.java index 97ae651473..347dd399e2 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationConfiguration.java +++ b/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationConfiguration.java @@ -6,13 +6,13 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @ComponentScan @EnableWebMvc -public class AttributeAnnotationConfiguration extends WebMvcConfigurerAdapter { +public class AttributeAnnotationConfiguration implements WebMvcConfigurer { @Bean public ViewResolver viewResolver() { diff --git a/spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsIntegrationTest.java b/spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsIntegrationTest.java index 986932dafe..fa72ed6d43 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsIntegrationTest.java @@ -25,7 +25,7 @@ public class CacheRefinementsIntegrationTest extends AbstractJUnit4SpringContext executorService.execute(() -> service.getFoo("test").printInstanceNumber()); } executorService.awaitTermination(1, TimeUnit.SECONDS); - assertEquals(Foo.getInstanceCount(), 1); + assertEquals(1, Foo.getInstanceCount()); } } diff --git a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalTest.java b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalTest.java deleted file mode 100644 index c7b95bced4..0000000000 --- a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.spring43.defaultmethods; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.test.context.transaction.AfterTransaction; -import org.springframework.test.context.transaction.BeforeTransaction; - -public interface ITransactionalTest { - - Logger log = LoggerFactory.getLogger(ITransactionalTest.class); - - @BeforeTransaction - default void beforeTransaction() { - log.info("Opening transaction"); - } - - @AfterTransaction - default void afterTransaction() { - log.info("Closing transaction"); - } - -} diff --git a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalUnitTest.java b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalUnitTest.java new file mode 100644 index 0000000000..3c180e91c8 --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalUnitTest.java @@ -0,0 +1,22 @@ +package org.baeldung.spring43.defaultmethods; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.test.context.transaction.AfterTransaction; +import org.springframework.test.context.transaction.BeforeTransaction; + +public interface ITransactionalUnitTest { + + Logger log = LoggerFactory.getLogger(ITransactionalUnitTest.class); + + @BeforeTransaction + default void beforeTransaction() { + log.info("Opening transaction"); + } + + @AfterTransaction + default void afterTransaction() { + log.info("Closing transaction"); + } + +} diff --git a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java index b4ac7e8ccf..dde153487d 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java @@ -5,7 +5,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; @ContextConfiguration(classes = TransactionalTestConfiguration.class) -public class TransactionalIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests implements ITransactionalTest { +public class TransactionalIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests implements ITransactionalUnitTest { @Test public void whenDefaultMethodAnnotatedWithBeforeTransaction_thenDefaultMethodIsExecuted() { diff --git a/spring-amqp-simple/pom.xml b/spring-amqp-simple/pom.xml index f3dfbccaec..3d9ea55cfa 100644 --- a/spring-amqp-simple/pom.xml +++ b/spring-amqp-simple/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-amqp-simple @@ -8,10 +8,10 @@ Spring AMQP Simple App - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-amqp-simple/src/main/resources/logback.xml b/spring-amqp-simple/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-amqp-simple/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-amqp-simple/src/test/java/broadcast/BroadcastMessageControllerIntegrationTest.java b/spring-amqp-simple/src/test/java/broadcast/BroadcastMessageControllerIntegrationTest.java deleted file mode 100644 index c3be7f1ede..0000000000 --- a/spring-amqp-simple/src/test/java/broadcast/BroadcastMessageControllerIntegrationTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package broadcast; - -import com.baeldung.springamqpsimple.broadcast.BroadcastConfig; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.amqp.rabbit.core.RabbitTemplate; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -@RunWith(SpringRunner.class) -@ActiveProfiles("test") -@SpringBootTest(webEnvironment = RANDOM_PORT) -public class BroadcastMessageControllerIntegrationTest { - - @Autowired - private TestRestTemplate restTemplate; - - @MockBean - private RabbitTemplate rabbitTemplate; - - @Test - public void whenPostingMessage_thenMessageIsCreated() { - final String message = "Hello World!"; - ResponseEntity responseEntity = restTemplate.postForEntity("/broadcast", message, Void.class); - - assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); - } - - @Test - public void whenPostingMessage_thenMessageIsSentToBroker() { - final String message = "Hello World!"; - restTemplate.postForEntity("/broadcast", message, Void.class); - - verify(rabbitTemplate).convertAndSend(BroadcastConfig.fanoutExchangeName, "", message); - verify(rabbitTemplate).convertAndSend(BroadcastConfig.topicExchangeName, "user.not-important.info", message); - verify(rabbitTemplate).convertAndSend(BroadcastConfig.topicExchangeName, "user.important.error", message); - } -} \ No newline at end of file diff --git a/spring-amqp-simple/src/test/java/com/baeldung/springamqpsimple/MessageControllerIntegrationTest.java b/spring-amqp-simple/src/test/java/com/baeldung/springamqpsimple/MessageControllerIntegrationTest.java deleted file mode 100644 index a053edaa0e..0000000000 --- a/spring-amqp-simple/src/test/java/com/baeldung/springamqpsimple/MessageControllerIntegrationTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.springamqpsimple; - - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.amqp.rabbit.core.RabbitTemplate; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verify; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -@RunWith(SpringRunner.class) -@ActiveProfiles("test") -@SpringBootTest(webEnvironment = RANDOM_PORT) -public class MessageControllerIntegrationTest { - - @Autowired - private TestRestTemplate restTemplate; - - @MockBean - private RabbitTemplate rabbitTemplate; - - @Test - public void whenPostingMessage_thenMessageIsCreated() { - final String message = "Hello World!"; - ResponseEntity responseEntity = restTemplate.postForEntity("/messages", message, Void.class); - - assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); - } - - @Test - public void whenPostingMessage_thenMessageIsSentToBroker() { - final String message = "Hello World!"; - restTemplate.postForEntity("/messages", message, Void.class); - - verify(rabbitTemplate).convertAndSend(SpringAmqpConfig.queueName, message); - } -} \ No newline at end of file diff --git a/spring-amqp/pom.xml b/spring-amqp/pom.xml index a11261084a..e08a4243b3 100755 --- a/spring-amqp/pom.xml +++ b/spring-amqp/pom.xml @@ -1,11 +1,11 @@ + 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 - springamqp + spring-amqp 0.1-SNAPSHOT jar - springamqp + spring-amqp Introduction to Spring-AMQP @@ -18,7 +18,7 @@ org.springframework.amqp spring-rabbit - 1.6.6.RELEASE + ${spring-rabbit} commons-logging @@ -29,11 +29,11 @@ - springamqp + spring-amqp - UTF-8 + 1.6.6.RELEASE diff --git a/spring-amqp/src/main/resources/logback.xml b/spring-amqp/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-amqp/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-aop/pom.xml b/spring-aop/pom.xml index 7cdf9bd7cc..b9b97eb076 100644 --- a/spring-aop/pom.xml +++ b/spring-aop/pom.xml @@ -1,5 +1,5 @@ + 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-aop @@ -8,10 +8,10 @@ spring-aop - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-aop/src/main/resources/logback.xml b/spring-aop/src/main/resources/logback.xml index 3245e94f08..7c15f603a0 100644 --- a/spring-aop/src/main/resources/logback.xml +++ b/spring-aop/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodTest.java b/spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodTest.java deleted file mode 100644 index 7ecb2a3ee3..0000000000 --- a/spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung.aspectj; - -import org.junit.Test; - -public class SecuredMethodTest { - @Test - public void testMethod() throws Exception { - SecuredMethod service = new SecuredMethod(); - service.unlockedMethod(); - service.lockedMethod(); - } -} \ No newline at end of file diff --git a/spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodUnitTest.java b/spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodUnitTest.java new file mode 100644 index 0000000000..cbdb2db057 --- /dev/null +++ b/spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodUnitTest.java @@ -0,0 +1,12 @@ +package org.baeldung.aspectj; + +import org.junit.Test; + +public class SecuredMethodUnitTest { + @Test + public void testMethod() throws Exception { + SecuredMethod service = new SecuredMethod(); + service.unlockedMethod(); + service.lockedMethod(); + } +} \ No newline at end of file diff --git a/spring-aop/src/test/java/org/baeldung/logger/CalculatorIntegrationTest.java b/spring-aop/src/test/java/org/baeldung/logger/CalculatorIntegrationTest.java new file mode 100644 index 0000000000..8c31b7f892 --- /dev/null +++ b/spring-aop/src/test/java/org/baeldung/logger/CalculatorIntegrationTest.java @@ -0,0 +1,29 @@ +package org.baeldung.logger; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(value = {"classpath:springAop-applicationContext.xml"}) +public class CalculatorIntegrationTest { + + @Autowired + private SampleAdder sampleAdder; + + @Test + public void whenAddValidValues_returnsSucessfully() { + final int addedValue = sampleAdder.add(12, 12); + + assertEquals(24, addedValue); + } + + @Test (expected = IllegalArgumentException.class) + public void whenAddInValidValues_throwsException() { + sampleAdder.add(12, -12); + } + +} diff --git a/spring-aop/src/test/java/org/baeldung/logger/CalculatorTest.java b/spring-aop/src/test/java/org/baeldung/logger/CalculatorTest.java deleted file mode 100644 index b1c88c67df..0000000000 --- a/spring-aop/src/test/java/org/baeldung/logger/CalculatorTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.logger; - -import static org.junit.Assert.assertEquals; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(value = {"classpath:springAop-applicationContext.xml"}) -public class CalculatorTest { - - @Autowired - private SampleAdder sampleAdder; - - @Test - public void whenAddValidValues_returnsSucessfully() { - final int addedValue = sampleAdder.add(12, 12); - - assertEquals(24, addedValue); - } - - @Test (expected = IllegalArgumentException.class) - public void whenAddInValidValues_throwsException() { - sampleAdder.add(12, -12); - } - -} diff --git a/spring-apache-camel/pom.xml b/spring-apache-camel/pom.xml index 4c963fc32c..662b3f899c 100644 --- a/spring-apache-camel/pom.xml +++ b/spring-apache-camel/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 org.apache.camel spring-apache-camel @@ -52,7 +52,6 @@ 2.18.1 4.3.4.RELEASE - 1.8 diff --git a/spring-apache-camel/src/main/resources/logback.xml b/spring-apache-camel/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-apache-camel/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-batch/README.md b/spring-batch/README.md index 754fc5f980..737e7e13f5 100644 --- a/spring-batch/README.md +++ b/spring-batch/README.md @@ -7,3 +7,4 @@ - [Introduction to Spring Batch](http://www.baeldung.com/introduction-to-spring-batch) - [Spring Batch using Partitioner](http://www.baeldung.com/spring-batch-partitioner) - [Spring Batch Tasklets vs Chunks Approach](http://www.baeldung.com/spring-batch-tasklet-chunk) +- [How to Trigger and Stop a Scheduled Spring Batch Job](http://www.baeldung.com/spring-batch-start-stop-job) diff --git a/spring-batch/pom.xml b/spring-batch/pom.xml index d274c046e2..cfd725b2bd 100644 --- a/spring-batch/pom.xml +++ b/spring-batch/pom.xml @@ -1,5 +1,5 @@ + 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-batch @@ -52,15 +52,21 @@ opencsv ${opencsv.version} + + + org.awaitility + awaitility + ${awaitility.version} + test + - - UTF-8 5.0.3.RELEASE 4.0.0.RELEASE 3.15.1 4.1 + 3.1.1 diff --git a/spring-batch/src/main/java/org/baeldung/batchscheduler/SpringBatchScheduler.java b/spring-batch/src/main/java/org/baeldung/batchscheduler/SpringBatchScheduler.java new file mode 100644 index 0000000000..1beeb6b2bf --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/batchscheduler/SpringBatchScheduler.java @@ -0,0 +1,172 @@ +package org.baeldung.batchscheduler; + +import java.util.Date; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import org.baeldung.batchscheduler.model.Book; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.batch.core.Job; +import org.springframework.batch.core.JobExecution; +import org.springframework.batch.core.JobParametersBuilder; +import org.springframework.batch.core.Step; +import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; +import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; +import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; +import org.springframework.batch.core.launch.JobLauncher; +import org.springframework.batch.core.launch.support.SimpleJobLauncher; +import org.springframework.batch.core.repository.JobRepository; +import org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean; +import org.springframework.batch.item.ItemWriter; +import org.springframework.batch.item.file.FlatFileItemReader; +import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder; +import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper; +import org.springframework.batch.support.transaction.ResourcelessTransactionManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.scheduling.TaskScheduler; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; +import org.springframework.scheduling.support.ScheduledMethodRunnable; + +@Configuration +@EnableBatchProcessing +@EnableScheduling +public class SpringBatchScheduler { + + private final Logger logger = LoggerFactory.getLogger(SpringBatchScheduler.class); + + private AtomicBoolean enabled = new AtomicBoolean(true); + + private AtomicInteger batchRunCounter = new AtomicInteger(0); + + private final Map> scheduledTasks = new IdentityHashMap<>(); + + @Autowired + private JobBuilderFactory jobBuilderFactory; + + @Autowired + private StepBuilderFactory stepBuilderFactory; + + @Scheduled(fixedRate = 2000) + public void launchJob() throws Exception { + Date date = new Date(); + logger.debug("scheduler starts at " + date); + if (enabled.get()) { + JobExecution jobExecution = jobLauncher().run(job(), new JobParametersBuilder().addDate("launchDate", date) + .toJobParameters()); + batchRunCounter.incrementAndGet(); + logger.debug("Batch job ends with status as " + jobExecution.getStatus()); + } + logger.debug("scheduler ends "); + } + + public void stop() { + enabled.set(false); + } + + public void start() { + enabled.set(true); + } + + @Bean + public TaskScheduler poolScheduler() { + return new CustomTaskScheduler(); + } + + private class CustomTaskScheduler extends ThreadPoolTaskScheduler { + + private static final long serialVersionUID = -7142624085505040603L; + + @Override + public ScheduledFuture scheduleAtFixedRate(Runnable task, long period) { + ScheduledFuture future = super.scheduleAtFixedRate(task, period); + + ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task; + scheduledTasks.put(runnable.getTarget(), future); + + return future; + } + + } + + public void cancelFutureSchedulerTasks() { + scheduledTasks.forEach((k, v) -> { + if (k instanceof SpringBatchScheduler) { + v.cancel(false); + } + }); + } + + @Bean + public Job job() { + return jobBuilderFactory.get("job") + .start(readBooks()) + .build(); + } + + @Bean + public JobLauncher jobLauncher() throws Exception { + SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); + jobLauncher.setJobRepository(jobRepository()); + jobLauncher.afterPropertiesSet(); + return jobLauncher; + } + + @Bean + public JobRepository jobRepository() throws Exception { + MapJobRepositoryFactoryBean factory = new MapJobRepositoryFactoryBean(); + factory.setTransactionManager(new ResourcelessTransactionManager()); + return (JobRepository) factory.getObject(); + } + + @Bean + protected Step readBooks() { + return stepBuilderFactory.get("readBooks") + . chunk(2) + .reader(reader()) + .writer(writer()) + .build(); + } + + @Bean + public FlatFileItemReader reader() { + return new FlatFileItemReaderBuilder().name("bookItemReader") + .resource(new ClassPathResource("books.csv")) + .delimited() + .names(new String[] { "id", "name" }) + .fieldSetMapper(new BeanWrapperFieldSetMapper() { + { + setTargetType(Book.class); + } + }) + .build(); + } + + @Bean + public ItemWriter writer() { + return new ItemWriter() { + + @Override + public void write(List items) throws Exception { + logger.debug("writer..." + items.size()); + for (Book item : items) { + logger.debug(item.toString()); + } + + } + }; + } + + public AtomicInteger getBatchRunCounter() { + return batchRunCounter; + } + +} diff --git a/spring-batch/src/main/java/org/baeldung/batchscheduler/model/Book.java b/spring-batch/src/main/java/org/baeldung/batchscheduler/model/Book.java new file mode 100644 index 0000000000..f992bde20e --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/batchscheduler/model/Book.java @@ -0,0 +1,35 @@ +package org.baeldung.batchscheduler.model; + +public class Book { + private int id; + private String name; + + public Book() {} + + public Book(int id, String name) { + super(); + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String toString() { + return "Book [id=" + id + ", name=" + name + "]"; + } + +} diff --git a/spring-batch/src/main/resources/books.csv b/spring-batch/src/main/resources/books.csv new file mode 100644 index 0000000000..af68e986a2 --- /dev/null +++ b/spring-batch/src/main/resources/books.csv @@ -0,0 +1,4 @@ +1,SHARP OBJECTS (MOVIE TIE-IN): A NOVEL +2,ARTEMIS: A NOVEL +3,HER PRETTY FACE +4,ALL WE EVER WANTED \ No newline at end of file diff --git a/spring-batch/src/main/resources/logback.xml b/spring-batch/src/main/resources/logback.xml index b110d1c226..91d4292b8e 100644 --- a/spring-batch/src/main/resources/logback.xml +++ b/spring-batch/src/main/resources/logback.xml @@ -3,7 +3,7 @@ - %d{yyyy-MM-dd HH:mm:ss} [%thread] %level %logger{35} - %msg%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n @@ -12,6 +12,10 @@ additivity="false"> + + + + diff --git a/spring-batch/src/test/java/org/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java b/spring-batch/src/test/java/org/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java new file mode 100644 index 0000000000..8927421ac5 --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java @@ -0,0 +1,60 @@ +package org.baeldung.batchscheduler; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static org.awaitility.Awaitility.await; +import static java.util.concurrent.TimeUnit.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = SpringBatchScheduler.class) +public class SpringBatchSchedulerIntegrationTest { + + @Autowired + private ApplicationContext context; + + @Test + public void stopJobsWhenSchedulerDisabled() throws Exception { + SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class); + await().untilAsserted(() -> Assert.assertEquals(2, schedulerBean.getBatchRunCounter() + .get())); + schedulerBean.stop(); + await().atLeast(3, SECONDS); + + Assert.assertEquals(2, schedulerBean.getBatchRunCounter() + .get()); + } + + @Test + public void stopJobSchedulerWhenSchedulerDestroyed() throws Exception { + ScheduledAnnotationBeanPostProcessor bean = context.getBean(ScheduledAnnotationBeanPostProcessor.class); + SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class); + await().untilAsserted(() -> Assert.assertEquals(2, schedulerBean.getBatchRunCounter() + .get())); + bean.postProcessBeforeDestruction(schedulerBean, "SpringBatchScheduler"); + await().atLeast(3, SECONDS); + + Assert.assertEquals(2, schedulerBean.getBatchRunCounter() + .get()); + } + + @Test + public void stopJobSchedulerWhenFutureTasksCancelled() throws Exception { + SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class); + await().untilAsserted(() -> Assert.assertEquals(2, schedulerBean.getBatchRunCounter() + .get())); + schedulerBean.cancelFutureSchedulerTasks(); + await().atLeast(3, SECONDS); + + Assert.assertEquals(2, schedulerBean.getBatchRunCounter() + .get()); + } + + +} diff --git a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java b/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java new file mode 100644 index 0000000000..eaf73e4a4a --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java @@ -0,0 +1,25 @@ +package org.baeldung.taskletsvschunks.chunks; + +import org.baeldung.taskletsvschunks.config.ChunksConfig; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.batch.core.ExitStatus; +import org.springframework.batch.core.JobExecution; +import org.springframework.batch.test.JobLauncherTestUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ChunksConfig.class) +public class ChunksIntegrationTest { + + @Autowired private JobLauncherTestUtils jobLauncherTestUtils; + + @Test + public void givenChunksJob_WhenJobEnds_ThenStatusCompleted() throws Exception { + JobExecution jobExecution = jobLauncherTestUtils.launchJob(); + Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); + } +} \ No newline at end of file diff --git a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksTest.java b/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksTest.java deleted file mode 100644 index 2a71970637..0000000000 --- a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.baeldung.taskletsvschunks.chunks; - -import org.baeldung.taskletsvschunks.config.ChunksConfig; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.JobExecution; -import org.springframework.batch.test.JobLauncherTestUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = ChunksConfig.class) -public class ChunksTest { - - @Autowired private JobLauncherTestUtils jobLauncherTestUtils; - - @Test - public void givenChunksJob_WhenJobEnds_ThenStatusCompleted() throws Exception { - JobExecution jobExecution = jobLauncherTestUtils.launchJob(); - Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); - } -} \ No newline at end of file diff --git a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java b/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java new file mode 100644 index 0000000000..322b17bd55 --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java @@ -0,0 +1,25 @@ +package org.baeldung.taskletsvschunks.tasklets; + +import org.baeldung.taskletsvschunks.config.TaskletsConfig; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.batch.core.ExitStatus; +import org.springframework.batch.core.JobExecution; +import org.springframework.batch.test.JobLauncherTestUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = TaskletsConfig.class) +public class TaskletsIntegrationTest { + + @Autowired private JobLauncherTestUtils jobLauncherTestUtils; + + @Test + public void givenTaskletsJob_WhenJobEnds_ThenStatusCompleted() throws Exception { + JobExecution jobExecution = jobLauncherTestUtils.launchJob(); + Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); + } +} \ No newline at end of file diff --git a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsTest.java b/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsTest.java deleted file mode 100644 index 20379b58fe..0000000000 --- a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.baeldung.taskletsvschunks.tasklets; - -import org.baeldung.taskletsvschunks.config.TaskletsConfig; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.JobExecution; -import org.springframework.batch.test.JobLauncherTestUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = TaskletsConfig.class) -public class TaskletsTest { - - @Autowired private JobLauncherTestUtils jobLauncherTestUtils; - - @Test - public void givenTaskletsJob_WhenJobEnds_ThenStatusCompleted() throws Exception { - JobExecution jobExecution = jobLauncherTestUtils.launchJob(); - Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); - } -} \ No newline at end of file diff --git a/spring-bom/pom.xml b/spring-bom/pom.xml index ddecb9dc0d..f974eb2334 100644 --- a/spring-bom/pom.xml +++ b/spring-bom/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.baeldung spring-bom @@ -38,7 +37,6 @@ - UTF-8 4.3.8.RELEASE diff --git a/spring-bom/src/main/resources/logback.xml b/spring-bom/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-bom/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot-admin/pom.xml b/spring-boot-admin/pom.xml index d285a01ec5..58cea728cc 100644 --- a/spring-boot-admin/pom.xml +++ b/spring-boot-admin/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-boot-admin 0.0.1-SNAPSHOT @@ -29,7 +29,6 @@ - UTF-8 1.5.8.RELEASE diff --git a/spring-boot-admin/spring-boot-admin-client/pom.xml b/spring-boot-admin/spring-boot-admin-client/pom.xml index d119450e0b..ea03d6ef6d 100644 --- a/spring-boot-admin/spring-boot-admin-client/pom.xml +++ b/spring-boot-admin/spring-boot-admin-client/pom.xml @@ -1,12 +1,10 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - spring-boot-admin-client 0.0.1-SNAPSHOT jar - spring-boot-admin-client Spring Boot Admin Client @@ -17,13 +15,6 @@ ../../spring-boot-admin - - UTF-8 - UTF-8 - 1.8 - 1.5.4 - - org.springframework.boot @@ -55,6 +46,7 @@ org.springframework.boot spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} @@ -66,5 +58,9 @@ + + 1.5.4 + 2.0.4.RELEASE + diff --git a/spring-boot-admin/spring-boot-admin-server/pom.xml b/spring-boot-admin/spring-boot-admin-server/pom.xml index d5c2e19f37..d8e7bb5574 100644 --- a/spring-boot-admin/spring-boot-admin-server/pom.xml +++ b/spring-boot-admin/spring-boot-admin-server/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-boot-admin-server 0.0.1-SNAPSHOT @@ -15,14 +15,6 @@ ../../spring-boot-admin - - UTF-8 - UTF-8 - 1.8 - 1.5.4 - 1.5.4 - - org.springframework.boot @@ -84,9 +76,15 @@ org.springframework.boot spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} + + 1.5.4 + 1.5.4 + 2.0.4.RELEASE + diff --git a/spring-boot-angular-ecommerce/README.md b/spring-boot-angular-ecommerce/README.md new file mode 100644 index 0000000000..c6564643e2 --- /dev/null +++ b/spring-boot-angular-ecommerce/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [A Simple E-Commerce Implementation with Spring](https://www.baeldung.com/spring-angular-ecommerce) diff --git a/spring-boot-angular-ecommerce/pom.xml b/spring-boot-angular-ecommerce/pom.xml new file mode 100644 index 0000000000..dc92a91d02 --- /dev/null +++ b/spring-boot-angular-ecommerce/pom.xml @@ -0,0 +1,84 @@ + + + 4.0.0 + + spring-boot-angular-ecommerce + 0.0.1-SNAPSHOT + jar + + spring-boot-angular-ecommerce + Spring Boot Angular E-commerce Appliciation + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring.boot.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + ${spring.boot.version} + + + org.springframework.boot + spring-boot-starter-web + ${spring.boot.version} + + + org.springframework.boot + spring-boot-devtools + ${spring.boot.version} + runtime + + + com.h2database + h2 + 1.4.197 + runtime + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + 2.9.6 + + + org.springframework.boot + spring-boot-starter-test + ${spring.boot.version} + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} + + + + + + UTF-8 + UTF-8 + 1.8 + 2.0.3.RELEASE + 2.0.4.RELEASE + + diff --git a/spring-boot-angular-ecommerce/src/main/frontend/.editorconfig b/spring-boot-angular-ecommerce/src/main/frontend/.editorconfig new file mode 100644 index 0000000000..9b7352176a --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/.editorconfig @@ -0,0 +1,13 @@ +# Editor configuration, see http://editorconfig.org +root = true + +[*] +charset = utf-8 +indent_style = space +indent_size = 4 +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +max_line_length = off +trim_trailing_whitespace = false diff --git a/spring-boot-angular-ecommerce/src/main/frontend/README.md b/spring-boot-angular-ecommerce/src/main/frontend/README.md new file mode 100644 index 0000000000..4217895796 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/README.md @@ -0,0 +1,27 @@ +# Frontend + +This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 6.0.8. + +## Development server + +Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. + +## Code scaffolding + +Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. + +## Build + +Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. + +## Running unit tests + +Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). + +## Running end-to-end tests + +Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). + +## Further help + +To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). diff --git a/spring-boot-angular-ecommerce/src/main/frontend/angular.json b/spring-boot-angular-ecommerce/src/main/frontend/angular.json new file mode 100644 index 0000000000..815c461f30 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/angular.json @@ -0,0 +1,128 @@ +{ + "$schema": "./node_modules/@angular/cli/lib/config/schema.json", + "version": 1, + "newProjectRoot": "projects", + "projects": { + "frontend": { + "root": "", + "sourceRoot": "src", + "projectType": "application", + "prefix": "app", + "schematics": {}, + "architect": { + "build": { + "builder": "@angular-devkit/build-angular:browser", + "options": { + "outputPath": "dist/frontend", + "index": "src/index.html", + "main": "src/main.ts", + "polyfills": "src/polyfills.ts", + "tsConfig": "src/tsconfig.app.json", + "assets": [ + "src/favicon.ico", + "src/assets" + ], + "styles": [ + "node_modules/bootstrap/dist/css/bootstrap.min.css", + "src/styles.css" + ], + "scripts": [] + }, + "configurations": { + "production": { + "fileReplacements": [ + { + "replace": "src/environments/environment.ts", + "with": "src/environments/environment.prod.ts" + } + ], + "optimization": true, + "outputHashing": "all", + "sourceMap": false, + "extractCss": true, + "namedChunks": false, + "aot": true, + "extractLicenses": true, + "vendorChunk": false, + "buildOptimizer": true + } + } + }, + "serve": { + "builder": "@angular-devkit/build-angular:dev-server", + "options": { + "browserTarget": "frontend:build" + }, + "configurations": { + "production": { + "browserTarget": "frontend:build:production" + } + } + }, + "extract-i18n": { + "builder": "@angular-devkit/build-angular:extract-i18n", + "options": { + "browserTarget": "frontend:build" + } + }, + "test": { + "builder": "@angular-devkit/build-angular:karma", + "options": { + "main": "src/test.ts", + "polyfills": "src/polyfills.ts", + "tsConfig": "src/tsconfig.spec.json", + "karmaConfig": "src/karma.conf.js", + "styles": [ + "src/styles.css" + ], + "scripts": [], + "assets": [ + "src/favicon.ico", + "src/assets" + ] + } + }, + "lint": { + "builder": "@angular-devkit/build-angular:tslint", + "options": { + "tsConfig": [ + "src/tsconfig.app.json", + "src/tsconfig.spec.json" + ], + "exclude": [ + "**/node_modules/**" + ] + } + } + } + }, + "frontend-e2e": { + "root": "e2e/", + "projectType": "application", + "architect": { + "e2e": { + "builder": "@angular-devkit/build-angular:protractor", + "options": { + "protractorConfig": "e2e/protractor.conf.js", + "devServerTarget": "frontend:serve" + }, + "configurations": { + "production": { + "devServerTarget": "frontend:serve:production" + } + } + }, + "lint": { + "builder": "@angular-devkit/build-angular:tslint", + "options": { + "tsConfig": "e2e/tsconfig.e2e.json", + "exclude": [ + "**/node_modules/**" + ] + } + } + } + } + }, + "defaultProject": "frontend" +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/e2e/protractor.conf.js b/spring-boot-angular-ecommerce/src/main/frontend/e2e/protractor.conf.js new file mode 100644 index 0000000000..86776a391a --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/e2e/protractor.conf.js @@ -0,0 +1,28 @@ +// Protractor configuration file, see link for more information +// https://github.com/angular/protractor/blob/master/lib/config.ts + +const { SpecReporter } = require('jasmine-spec-reporter'); + +exports.config = { + allScriptsTimeout: 11000, + specs: [ + './src/**/*.e2e-spec.ts' + ], + capabilities: { + 'browserName': 'chrome' + }, + directConnect: true, + baseUrl: 'http://localhost:4200/', + framework: 'jasmine', + jasmineNodeOpts: { + showColors: true, + defaultTimeoutInterval: 30000, + print: function() {} + }, + onPrepare() { + require('ts-node').register({ + project: require('path').join(__dirname, './tsconfig.e2e.json') + }); + jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); + } +}; \ No newline at end of file diff --git a/spring-boot-angular-ecommerce/src/main/frontend/e2e/src/app.e2e-spec.ts b/spring-boot-angular-ecommerce/src/main/frontend/e2e/src/app.e2e-spec.ts new file mode 100644 index 0000000000..87525cf2c7 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/e2e/src/app.e2e-spec.ts @@ -0,0 +1,14 @@ +import { AppPage } from './app.po'; + +describe('workspace-project App', () => { + let page: AppPage; + + beforeEach(() => { + page = new AppPage(); + }); + + it('should display welcome message', () => { + page.navigateTo(); + expect(page.getParagraphText()).toEqual('Welcome to frontend!'); + }); +}); diff --git a/spring-boot-angular-ecommerce/src/main/frontend/e2e/src/app.po.ts b/spring-boot-angular-ecommerce/src/main/frontend/e2e/src/app.po.ts new file mode 100644 index 0000000000..82ea75ba50 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/e2e/src/app.po.ts @@ -0,0 +1,11 @@ +import { browser, by, element } from 'protractor'; + +export class AppPage { + navigateTo() { + return browser.get('/'); + } + + getParagraphText() { + return element(by.css('app-root h1')).getText(); + } +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/e2e/tsconfig.e2e.json b/spring-boot-angular-ecommerce/src/main/frontend/e2e/tsconfig.e2e.json new file mode 100644 index 0000000000..a6dd622028 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/e2e/tsconfig.e2e.json @@ -0,0 +1,13 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "outDir": "../out-tsc/app", + "module": "commonjs", + "target": "es5", + "types": [ + "jasmine", + "jasminewd2", + "node" + ] + } +} \ No newline at end of file diff --git a/spring-boot-angular-ecommerce/src/main/frontend/package-lock.json b/spring-boot-angular-ecommerce/src/main/frontend/package-lock.json new file mode 100644 index 0000000000..d87b39cad5 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/package-lock.json @@ -0,0 +1,10591 @@ +{ + "name": "frontend", + "version": "0.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@angular-devkit/architect": { + "version": "0.6.8", + "resolved": "https://registry.npmjs.org/@angular-devkit/architect/-/architect-0.6.8.tgz", + "integrity": "sha512-ZKTm/zC61iY9IBHOEAKoMSzZpvhkmv+1O/HHzpHEuR551jCzu6vSyCmMY9Z7GBcccscCV+hjeSMwgFrFRcqlkw==", + "dev": true, + "requires": { + "@angular-devkit/core": "0.6.8", + "rxjs": "^6.0.0" + } + }, + "@angular-devkit/build-angular": { + "version": "0.6.8", + "resolved": "https://registry.npmjs.org/@angular-devkit/build-angular/-/build-angular-0.6.8.tgz", + "integrity": "sha512-VGqYAk8jpISraz2UHfsDre270NOUmV0CTSZw2p9sm5g/XIr5m+IHetFZz3gpoAr9+If2aFTs8Rt3sGdCRzwBqA==", + "dev": true, + "requires": { + "@angular-devkit/architect": "0.6.8", + "@angular-devkit/build-optimizer": "0.6.8", + "@angular-devkit/core": "0.6.8", + "@ngtools/webpack": "6.0.8", + "ajv": "~6.4.0", + "autoprefixer": "^8.4.1", + "cache-loader": "^1.2.2", + "chalk": "~2.2.2", + "circular-dependency-plugin": "^5.0.2", + "clean-css": "^4.1.11", + "copy-webpack-plugin": "^4.5.1", + "file-loader": "^1.1.11", + "glob": "^7.0.3", + "html-webpack-plugin": "^3.0.6", + "istanbul": "^0.4.5", + "istanbul-instrumenter-loader": "^3.0.1", + "karma-source-map-support": "^1.2.0", + "less": "^3.0.4", + "less-loader": "^4.1.0", + "license-webpack-plugin": "^1.3.1", + "lodash": "^4.17.4", + "memory-fs": "^0.4.1", + "mini-css-extract-plugin": "~0.4.0", + "minimatch": "^3.0.4", + "node-sass": "^4.9.0", + "opn": "^5.1.0", + "parse5": "^4.0.0", + "portfinder": "^1.0.13", + "postcss": "^6.0.22", + "postcss-import": "^11.1.0", + "postcss-loader": "^2.1.5", + "postcss-url": "^7.3.2", + "raw-loader": "^0.5.1", + "resolve": "^1.5.0", + "rxjs": "^6.0.0", + "sass-loader": "^7.0.1", + "silent-error": "^1.1.0", + "source-map-support": "^0.5.0", + "stats-webpack-plugin": "^0.6.2", + "style-loader": "^0.21.0", + "stylus": "^0.54.5", + "stylus-loader": "^3.0.2", + "tree-kill": "^1.2.0", + "uglifyjs-webpack-plugin": "^1.2.5", + "url-loader": "^1.0.1", + "webpack": "~4.8.1", + "webpack-dev-middleware": "^3.1.3", + "webpack-dev-server": "^3.1.4", + "webpack-merge": "^4.1.2", + "webpack-sources": "^1.1.0", + "webpack-subresource-integrity": "^1.1.0-rc.4" + } + }, + "@angular-devkit/build-optimizer": { + "version": "0.6.8", + "resolved": "https://registry.npmjs.org/@angular-devkit/build-optimizer/-/build-optimizer-0.6.8.tgz", + "integrity": "sha512-of5syQbv3uNPp4AQkfRecfnp8AE8kvffbfYi+FFPZ6OGr7e59T1fGwk6+Zgb2qQFQg8HO2tzWI/uygtLIqmbmw==", + "dev": true, + "requires": { + "loader-utils": "^1.1.0", + "source-map": "^0.5.6", + "typescript": "~2.9.1", + "webpack-sources": "^1.1.0" + }, + "dependencies": { + "typescript": { + "version": "2.9.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-2.9.2.tgz", + "integrity": "sha512-Gr4p6nFNaoufRIY4NMdpQRNmgxVIGMs4Fcu/ujdYk3nAZqk7supzBE9idmvfZIlH/Cuj//dvi+019qEue9lV0w==", + "dev": true + } + } + }, + "@angular-devkit/core": { + "version": "0.6.8", + "resolved": "https://registry.npmjs.org/@angular-devkit/core/-/core-0.6.8.tgz", + "integrity": "sha512-rkIa1OSVWTt4g9leLSK/PsqOj3HZbDKHbZjqlslyfVa3AyCeiumFoOgViOVXlYgPX3HHDbE5uH24nyUWSD8uww==", + "dev": true, + "requires": { + "ajv": "~6.4.0", + "chokidar": "^2.0.3", + "rxjs": "^6.0.0", + "source-map": "^0.5.6" + } + }, + "@angular-devkit/schematics": { + "version": "0.6.8", + "resolved": "https://registry.npmjs.org/@angular-devkit/schematics/-/schematics-0.6.8.tgz", + "integrity": "sha512-R4YqAUdo62wtrhX/5HSRGSKXNTWqfQb66ZE6m8jj6GEJNFKdNXMdxOchxr07LCiKTxfh1w6G3nGzxIsu/+D4KA==", + "dev": true, + "requires": { + "@angular-devkit/core": "0.6.8", + "rxjs": "^6.0.0" + } + }, + "@angular/animations": { + "version": "6.0.9", + "resolved": "https://registry.npmjs.org/@angular/animations/-/animations-6.0.9.tgz", + "integrity": "sha512-UJTHlxVGZLefCDxTS7T0qZxrAIaQ8gGghHwDI7F3QXpXZTsAk4nHiGSt2EvneW5o6io83i6Hpr/9Fde+YvzWNg==", + "requires": { + "tslib": "^1.9.0" + } + }, + "@angular/cli": { + "version": "6.0.8", + "resolved": "https://registry.npmjs.org/@angular/cli/-/cli-6.0.8.tgz", + "integrity": "sha512-DhH1Zq5Yonthw6zh6W07fhf+9XrAZbD1fcQ0MrmbxlieCfLlTAdBqyK2LavFCKwSZkUMLF6UHM3+jiNRVZSSIg==", + "dev": true, + "requires": { + "@angular-devkit/architect": "0.6.8", + "@angular-devkit/core": "0.6.8", + "@angular-devkit/schematics": "0.6.8", + "@schematics/angular": "0.6.8", + "@schematics/update": "0.6.8", + "opn": "~5.3.0", + "resolve": "^1.1.7", + "rxjs": "^6.0.0", + "semver": "^5.1.0", + "silent-error": "^1.0.0", + "symbol-observable": "^1.2.0", + "yargs-parser": "^10.0.0" + }, + "dependencies": { + "camelcase": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-4.1.0.tgz", + "integrity": "sha1-1UVjW+HjPFQmScaRc+Xeas+uNN0=", + "dev": true + }, + "yargs-parser": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-10.1.0.tgz", + "integrity": "sha512-VCIyR1wJoEBZUqk5PA+oOBF6ypbwh5aNB3I50guxAL/quggdfs4TtNHQrSazFA3fYZ+tEqfs0zIGlv0c/rgjbQ==", + "dev": true, + "requires": { + "camelcase": "^4.1.0" + } + } + } + }, + "@angular/common": { + "version": "6.0.9", + "resolved": "https://registry.npmjs.org/@angular/common/-/common-6.0.9.tgz", + "integrity": "sha512-zjJ9WDW9787sTRiNeUvQaCvGZJu1dI8A3fYtSL8BKrGhxLsf24cSa3ljbrSmtIsCGImNxTToHzPFXo4sx2dvYg==", + "requires": { + "tslib": "^1.9.0" + } + }, + "@angular/compiler": { + "version": "6.0.9", + "resolved": "https://registry.npmjs.org/@angular/compiler/-/compiler-6.0.9.tgz", + "integrity": "sha512-/A6U/W0settfkh3tmX9p3t7+OyZ0c2sIJMlQjhfF36do0ylnIl4wuqJtHF0BWr/wmmbQzg+qAsQyWrx8vp+2Iw==", + "requires": { + "tslib": "^1.9.0" + } + }, + "@angular/compiler-cli": { + "version": "6.0.9", + "resolved": "https://registry.npmjs.org/@angular/compiler-cli/-/compiler-cli-6.0.9.tgz", + "integrity": "sha512-v3C5RyJLKoDcQocDt/U195t9v8UpBH+mwVaBkEM+nLkZAGC1Uvg9nPuUXisOwljuMm9VtOWG3A8hKQ5ZYieNBg==", + "dev": true, + "requires": { + "chokidar": "^1.4.2", + "minimist": "^1.2.0", + "reflect-metadata": "^0.1.2", + "tsickle": "^0.29.0" + }, + "dependencies": { + "anymatch": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-1.3.2.tgz", + "integrity": "sha512-0XNayC8lTHQ2OI8aljNCN3sSx6hsr/1+rlcDAotXJR7C1oZZHCNsfpbKwMjRA3Uqb5tF1Rae2oloTr4xpq+WjA==", + "dev": true, + "requires": { + "micromatch": "^2.1.5", + "normalize-path": "^2.0.0" + } + }, + "arr-diff": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-2.0.0.tgz", + "integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=", + "dev": true, + "requires": { + "arr-flatten": "^1.0.1" + } + }, + "array-unique": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.2.1.tgz", + "integrity": "sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=", + "dev": true + }, + "braces": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/braces/-/braces-1.8.5.tgz", + "integrity": "sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=", + "dev": true, + "requires": { + "expand-range": "^1.8.1", + "preserve": "^0.2.0", + "repeat-element": "^1.1.2" + } + }, + "chokidar": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-1.7.0.tgz", + "integrity": "sha1-eY5ol3gVHIB2tLNg5e3SjNortGg=", + "dev": true, + "requires": { + "anymatch": "^1.3.0", + "async-each": "^1.0.0", + "fsevents": "^1.0.0", + "glob-parent": "^2.0.0", + "inherits": "^2.0.1", + "is-binary-path": "^1.0.0", + "is-glob": "^2.0.0", + "path-is-absolute": "^1.0.0", + "readdirp": "^2.0.0" + } + }, + "expand-brackets": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-0.1.5.tgz", + "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=", + "dev": true, + "requires": { + "is-posix-bracket": "^0.1.0" + } + }, + "extglob": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-0.3.2.tgz", + "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=", + "dev": true, + "requires": { + "is-extglob": "^1.0.0" + } + }, + "glob-parent": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-2.0.0.tgz", + "integrity": "sha1-gTg9ctsFT8zPUzbaqQLxgvbtuyg=", + "dev": true, + "requires": { + "is-glob": "^2.0.0" + } + }, + "is-extglob": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-1.0.0.tgz", + "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=", + "dev": true + }, + "is-glob": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-2.0.1.tgz", + "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", + "dev": true, + "requires": { + "is-extglob": "^1.0.0" + } + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + }, + "micromatch": { + "version": "2.3.11", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-2.3.11.tgz", + "integrity": "sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=", + "dev": true, + "requires": { + "arr-diff": "^2.0.0", + "array-unique": "^0.2.1", + "braces": "^1.8.2", + "expand-brackets": "^0.1.4", + "extglob": "^0.3.1", + "filename-regex": "^2.0.0", + "is-extglob": "^1.0.0", + "is-glob": "^2.0.1", + "kind-of": "^3.0.2", + "normalize-path": "^2.0.1", + "object.omit": "^2.0.0", + "parse-glob": "^3.0.4", + "regex-cache": "^0.4.2" + } + }, + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + } + } + }, + "@angular/core": { + "version": "6.0.9", + "resolved": "https://registry.npmjs.org/@angular/core/-/core-6.0.9.tgz", + "integrity": "sha512-NeEUgymsR/tLvWeEAA4mGEX/S4hHbIo/2uwPGGAQAvzlk+pL7xqPoFSMKeqQahdTnWSmYa/2+X33OdJgXKKXyg==", + "requires": { + "tslib": "^1.9.0" + } + }, + "@angular/forms": { + "version": "6.0.9", + "resolved": "https://registry.npmjs.org/@angular/forms/-/forms-6.0.9.tgz", + "integrity": "sha512-hZxzoO/QAd9EetNUdGpb5Wiw4Lb7R+iOCjdV8sh+C8q6Ow5G35/dfiAlNanGXVqSi8e6Qqm1aO/r4cTUWFm6vw==", + "requires": { + "tslib": "^1.9.0" + } + }, + "@angular/http": { + "version": "6.0.9", + "resolved": "https://registry.npmjs.org/@angular/http/-/http-6.0.9.tgz", + "integrity": "sha512-JaYvBQQ+hJ7SKqZ+zw4C20lc7b6U5kK50nSkams10tzhITke6L/+wK8g3kiNu4XcqE5nqcIN8S95UkMGPMsa7Q==", + "requires": { + "tslib": "^1.9.0" + } + }, + "@angular/language-service": { + "version": "6.0.9", + "resolved": "https://registry.npmjs.org/@angular/language-service/-/language-service-6.0.9.tgz", + "integrity": "sha512-a9/Ee1DfRlj4duhDW17xl+52mO6zKlBLm3JOIyANrmJqoHCf/Nfvw3OmEhjMJ1A8O6xLCXyPF/Fq0WD9BfVSrg==", + "dev": true + }, + "@angular/platform-browser": { + "version": "6.0.9", + "resolved": "https://registry.npmjs.org/@angular/platform-browser/-/platform-browser-6.0.9.tgz", + "integrity": "sha512-q/1UGlbWBwZ6c63p8SDmBsgjYgMQUxyByY9GGt0hd5XhOfVFzvBSzybKSRc3FBhmxQJMCtVhEbI0kIzqrDxcWg==", + "requires": { + "tslib": "^1.9.0" + } + }, + "@angular/platform-browser-dynamic": { + "version": "6.0.9", + "resolved": "https://registry.npmjs.org/@angular/platform-browser-dynamic/-/platform-browser-dynamic-6.0.9.tgz", + "integrity": "sha512-HsmLafy0hpMIZlwHz1XRicXczZWCKb0H6oCY+TepFV4u3SLZgJEO7/HZrhO0kEviipXuXrgZSpafV3IYP6eWPQ==", + "requires": { + "tslib": "^1.9.0" + } + }, + "@angular/router": { + "version": "6.0.9", + "resolved": "https://registry.npmjs.org/@angular/router/-/router-6.0.9.tgz", + "integrity": "sha512-kS489FFpGWD4GEDDozfVb+eD5qf1E9cLYgsE7RO914uNMh/sJuRZt9PVu0bcX12fOOO7mTcOiWtlkefzUAJbkA==", + "requires": { + "tslib": "^1.9.0" + } + }, + "@ngtools/webpack": { + "version": "6.0.8", + "resolved": "https://registry.npmjs.org/@ngtools/webpack/-/webpack-6.0.8.tgz", + "integrity": "sha512-jorGpTd82ILbyUwg4JQekovHFaYwSMlZan4f7x+sd3+2WgyL3Z1+ZbVSGKvXZWKS/mAVx7eLkRikzJkuC4FgHw==", + "dev": true, + "requires": { + "@angular-devkit/core": "0.6.8", + "tree-kill": "^1.0.0", + "webpack-sources": "^1.1.0" + } + }, + "@schematics/angular": { + "version": "0.6.8", + "resolved": "https://registry.npmjs.org/@schematics/angular/-/angular-0.6.8.tgz", + "integrity": "sha512-9kRphqTYG5Df/I8fvnT1zMsw0YNDPO9tl18tQZXj4am4raT7l9UCr+WkwJdlBoA5pwG6baWE9sL0iGWV/bzF/g==", + "dev": true, + "requires": { + "@angular-devkit/core": "0.6.8", + "@angular-devkit/schematics": "0.6.8", + "typescript": ">=2.6.2 <2.8" + } + }, + "@schematics/update": { + "version": "0.6.8", + "resolved": "https://registry.npmjs.org/@schematics/update/-/update-0.6.8.tgz", + "integrity": "sha512-1Uq7LYnwL2wBwGVCgNz76QAR13ghAk+2vDDHOi+VX5+usHManxydrpoMGeX66OBPd+y5D3D2MFb+8mYHE7mygg==", + "dev": true, + "requires": { + "@angular-devkit/core": "0.6.8", + "@angular-devkit/schematics": "0.6.8", + "npm-registry-client": "^8.5.1", + "rxjs": "^6.0.0", + "semver": "^5.3.0", + "semver-intersect": "^1.1.2" + } + }, + "@types/jasmine": { + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/@types/jasmine/-/jasmine-2.8.8.tgz", + "integrity": "sha512-OJSUxLaxXsjjhob2DBzqzgrkLmukM3+JMpRp0r0E4HTdT1nwDCWhaswjYxazPij6uOdzHCJfNbDjmQ1/rnNbCg==", + "dev": true + }, + "@types/jasminewd2": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@types/jasminewd2/-/jasminewd2-2.0.3.tgz", + "integrity": "sha512-hYDVmQZT5VA2kigd4H4bv7vl/OhlympwREUemqBdOqtrYTo5Ytm12a5W5/nGgGYdanGVxj0x/VhZ7J3hOg/YKg==", + "dev": true, + "requires": { + "@types/jasmine": "*" + } + }, + "@types/node": { + "version": "8.9.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-8.9.5.tgz", + "integrity": "sha512-jRHfWsvyMtXdbhnz5CVHxaBgnV6duZnPlQuRSo/dm/GnmikNcmZhxIES4E9OZjUmQ8C+HCl4KJux+cXN/ErGDQ==", + "dev": true + }, + "@types/q": { + "version": "0.0.32", + "resolved": "https://registry.npmjs.org/@types/q/-/q-0.0.32.tgz", + "integrity": "sha1-vShOV8hPEyXacCur/IKlMoGQwMU=", + "dev": true + }, + "@types/selenium-webdriver": { + "version": "2.53.43", + "resolved": "https://registry.npmjs.org/@types/selenium-webdriver/-/selenium-webdriver-2.53.43.tgz", + "integrity": "sha512-UBYHWph6P3tutkbXpW6XYg9ZPbTKjw/YC2hGG1/GEvWwTbvezBUv3h+mmUFw79T3RFPnmedpiXdOBbXX+4l0jg==", + "dev": true + }, + "@webassemblyjs/ast": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.4.3.tgz", + "integrity": "sha512-S6npYhPcTHDYe9nlsKa9CyWByFi8Vj8HovcAgtmMAQZUOczOZbQ8CnwMYKYC5HEZzxEE+oY0jfQk4cVlI3J59Q==", + "dev": true, + "requires": { + "@webassemblyjs/helper-wasm-bytecode": "1.4.3", + "@webassemblyjs/wast-parser": "1.4.3", + "debug": "^3.1.0", + "webassemblyjs": "1.4.3" + }, + "dependencies": { + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + } + } + }, + "@webassemblyjs/floating-point-hex-parser": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.4.3.tgz", + "integrity": "sha512-3zTkSFswwZOPNHnzkP9ONq4bjJSeKVMcuahGXubrlLmZP8fmTIJ58dW7h/zOVWiFSuG2em3/HH3BlCN7wyu9Rw==", + "dev": true + }, + "@webassemblyjs/helper-buffer": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.4.3.tgz", + "integrity": "sha512-e8+KZHh+RV8MUvoSRtuT1sFXskFnWG9vbDy47Oa166xX+l0dD5sERJ21g5/tcH8Yo95e9IN3u7Jc3NbhnUcSkw==", + "dev": true, + "requires": { + "debug": "^3.1.0" + }, + "dependencies": { + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + } + } + }, + "@webassemblyjs/helper-code-frame": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-code-frame/-/helper-code-frame-1.4.3.tgz", + "integrity": "sha512-9FgHEtNsZQYaKrGCtsjswBil48Qp1agrzRcPzCbQloCoaTbOXLJ9IRmqT+uEZbenpULLRNFugz3I4uw18hJM8w==", + "dev": true, + "requires": { + "@webassemblyjs/wast-printer": "1.4.3" + } + }, + "@webassemblyjs/helper-fsm": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-fsm/-/helper-fsm-1.4.3.tgz", + "integrity": "sha512-JINY76U+702IRf7ePukOt037RwmtH59JHvcdWbTTyHi18ixmQ+uOuNhcdCcQHTquDAH35/QgFlp3Y9KqtyJsCQ==", + "dev": true + }, + "@webassemblyjs/helper-wasm-bytecode": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.4.3.tgz", + "integrity": "sha512-I7bS+HaO0K07Io89qhJv+z1QipTpuramGwUSDkwEaficbSvCcL92CUZEtgykfNtk5wb0CoLQwWlmXTwGbNZUeQ==", + "dev": true + }, + "@webassemblyjs/helper-wasm-section": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.4.3.tgz", + "integrity": "sha512-p0yeeO/h2r30PyjnJX9xXSR6EDcvJd/jC6xa/Pxg4lpfcNi7JUswOpqDToZQ55HMMVhXDih/yqkaywHWGLxqyQ==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.4.3", + "@webassemblyjs/helper-buffer": "1.4.3", + "@webassemblyjs/helper-wasm-bytecode": "1.4.3", + "@webassemblyjs/wasm-gen": "1.4.3", + "debug": "^3.1.0" + }, + "dependencies": { + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + } + } + }, + "@webassemblyjs/leb128": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.4.3.tgz", + "integrity": "sha512-4u0LJLSPzuRDWHwdqsrThYn+WqMFVqbI2ltNrHvZZkzFPO8XOZ0HFQ5eVc4jY/TNHgXcnwrHjONhPGYuuf//KQ==", + "dev": true, + "requires": { + "leb": "^0.3.0" + } + }, + "@webassemblyjs/validation": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/@webassemblyjs/validation/-/validation-1.4.3.tgz", + "integrity": "sha512-R+rRMKfhd9mq0rj2mhU9A9NKI2l/Rw65vIYzz4lui7eTKPcCu1l7iZNi4b9Gen8D42Sqh/KGiaQNk/x5Tn/iBQ==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.4.3" + } + }, + "@webassemblyjs/wasm-edit": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.4.3.tgz", + "integrity": "sha512-qzuwUn771PV6/LilqkXcS0ozJYAeY/OKbXIWU3a8gexuqb6De2p4ya/baBeH5JQ2WJdfhWhSvSbu86Vienttpw==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.4.3", + "@webassemblyjs/helper-buffer": "1.4.3", + "@webassemblyjs/helper-wasm-bytecode": "1.4.3", + "@webassemblyjs/helper-wasm-section": "1.4.3", + "@webassemblyjs/wasm-gen": "1.4.3", + "@webassemblyjs/wasm-opt": "1.4.3", + "@webassemblyjs/wasm-parser": "1.4.3", + "@webassemblyjs/wast-printer": "1.4.3", + "debug": "^3.1.0" + }, + "dependencies": { + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + } + } + }, + "@webassemblyjs/wasm-gen": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.4.3.tgz", + "integrity": "sha512-eR394T8dHZfpLJ7U/Z5pFSvxl1L63JdREebpv9gYc55zLhzzdJPAuxjBYT4XqevUdW67qU2s0nNA3kBuNJHbaQ==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.4.3", + "@webassemblyjs/helper-wasm-bytecode": "1.4.3", + "@webassemblyjs/leb128": "1.4.3" + } + }, + "@webassemblyjs/wasm-opt": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.4.3.tgz", + "integrity": "sha512-7Gp+nschuKiDuAL1xmp4Xz0rgEbxioFXw4nCFYEmy+ytynhBnTeGc9W9cB1XRu1w8pqRU2lbj2VBBA4cL5Z2Kw==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.4.3", + "@webassemblyjs/helper-buffer": "1.4.3", + "@webassemblyjs/wasm-gen": "1.4.3", + "@webassemblyjs/wasm-parser": "1.4.3", + "debug": "^3.1.0" + }, + "dependencies": { + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + } + } + }, + "@webassemblyjs/wasm-parser": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.4.3.tgz", + "integrity": "sha512-KXBjtlwA3BVukR/yWHC9GF+SCzBcgj0a7lm92kTOaa4cbjaTaa47bCjXw6cX4SGQpkncB9PU2hHGYVyyI7wFRg==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.4.3", + "@webassemblyjs/helper-wasm-bytecode": "1.4.3", + "@webassemblyjs/leb128": "1.4.3", + "@webassemblyjs/wasm-parser": "1.4.3", + "webassemblyjs": "1.4.3" + } + }, + "@webassemblyjs/wast-parser": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-parser/-/wast-parser-1.4.3.tgz", + "integrity": "sha512-QhCsQzqV0CpsEkRYyTzQDilCNUZ+5j92f+g35bHHNqS22FppNTywNFfHPq8ZWZfYCgbectc+PoghD+xfzVFh1Q==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.4.3", + "@webassemblyjs/floating-point-hex-parser": "1.4.3", + "@webassemblyjs/helper-code-frame": "1.4.3", + "@webassemblyjs/helper-fsm": "1.4.3", + "long": "^3.2.0", + "webassemblyjs": "1.4.3" + } + }, + "@webassemblyjs/wast-printer": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.4.3.tgz", + "integrity": "sha512-EgXk4anf8jKmuZJsqD8qy5bz2frEQhBvZruv+bqwNoLWUItjNSFygk8ywL3JTEz9KtxTlAmqTXNrdD1d9gNDtg==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.4.3", + "@webassemblyjs/wast-parser": "1.4.3", + "long": "^3.2.0" + } + }, + "@webpack-contrib/schema-utils": { + "version": "1.0.0-beta.0", + "resolved": "https://registry.npmjs.org/@webpack-contrib/schema-utils/-/schema-utils-1.0.0-beta.0.tgz", + "integrity": "sha512-LonryJP+FxQQHsjGBi6W786TQB1Oym+agTpY0c+Kj8alnIw+DLUJb6SI8Y1GHGhLCH1yPRrucjObUmxNICQ1pg==", + "dev": true, + "requires": { + "ajv": "^6.1.0", + "ajv-keywords": "^3.1.0", + "chalk": "^2.3.2", + "strip-ansi": "^4.0.0", + "text-table": "^0.2.0", + "webpack-log": "^1.1.2" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", + "dev": true + }, + "chalk": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", + "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "dev": true, + "requires": { + "ansi-regex": "^3.0.0" + } + } + } + }, + "abbrev": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.9.tgz", + "integrity": "sha1-kbR5JYinc4wl813W9jdSovh3YTU=", + "dev": true + }, + "accepts": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.5.tgz", + "integrity": "sha1-63d99gEXI6OxTopywIBcjoZ0a9I=", + "dev": true, + "requires": { + "mime-types": "~2.1.18", + "negotiator": "0.6.1" + } + }, + "acorn": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.7.1.tgz", + "integrity": "sha512-d+nbxBUGKg7Arpsvbnlq61mc12ek3EY8EQldM3GPAhWJ1UVxC6TDGbIvUMNU6obBX3i1+ptCIzV4vq0gFPEGVQ==", + "dev": true + }, + "acorn-dynamic-import": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/acorn-dynamic-import/-/acorn-dynamic-import-3.0.0.tgz", + "integrity": "sha512-zVWV8Z8lislJoOKKqdNMOB+s6+XV5WERty8MnKBeFgwA+19XJjJHs2RP5dzM57FftIs+jQnRToLiWazKr6sSWg==", + "dev": true, + "requires": { + "acorn": "^5.0.0" + } + }, + "adm-zip": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.4.4.tgz", + "integrity": "sha1-ph7VrmkFw66lizplfSUDMJEFJzY=", + "dev": true + }, + "after": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/after/-/after-0.8.2.tgz", + "integrity": "sha1-/ts5T58OAqqXaOcCvaI7UF+ufh8=", + "dev": true + }, + "agent-base": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-4.2.1.tgz", + "integrity": "sha512-JVwXMr9nHYTUXsBFKUqhJwvlcYU/blreOEUkhNR2eXZIvwd+c+o5V4MgDPKWnMS/56awN3TRzIP+KoPn+roQtg==", + "dev": true, + "requires": { + "es6-promisify": "^5.0.0" + } + }, + "ajv": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.4.0.tgz", + "integrity": "sha1-06/3jpJ3VJdx2vAWTP9ISCt1T8Y=", + "dev": true, + "requires": { + "fast-deep-equal": "^1.0.0", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.3.0", + "uri-js": "^3.0.2" + } + }, + "ajv-keywords": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.2.0.tgz", + "integrity": "sha1-6GuBnGAs+IIa1jdBNpjx3sAhhHo=", + "dev": true + }, + "align-text": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/align-text/-/align-text-0.1.4.tgz", + "integrity": "sha1-DNkKVhCT810KmSVsIrcGlDP60Rc=", + "dev": true, + "requires": { + "kind-of": "^3.0.2", + "longest": "^1.0.1", + "repeat-string": "^1.5.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "amdefine": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/amdefine/-/amdefine-1.0.1.tgz", + "integrity": "sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=", + "dev": true + }, + "ansi-html": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/ansi-html/-/ansi-html-0.0.7.tgz", + "integrity": "sha1-gTWEAhliqenm/QOflA0S9WynhZ4=", + "dev": true + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "anymatch": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-2.0.0.tgz", + "integrity": "sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw==", + "dev": true, + "requires": { + "micromatch": "^3.1.4", + "normalize-path": "^2.1.1" + } + }, + "app-root-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/app-root-path/-/app-root-path-2.1.0.tgz", + "integrity": "sha1-mL9lmTJ+zqGZMJhm6BQDaP0uZGo=", + "dev": true + }, + "append-transform": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/append-transform/-/append-transform-1.0.0.tgz", + "integrity": "sha512-P009oYkeHyU742iSZJzZZywj4QRJdnTWffaKuJQLablCZ1uz6/cW4yaRgcDaoQ+uwOxxnt0gRUcwfsNP2ri0gw==", + "dev": true, + "requires": { + "default-require-extensions": "^2.0.0" + } + }, + "aproba": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-1.2.0.tgz", + "integrity": "sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==", + "dev": true + }, + "are-we-there-yet": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-1.1.5.tgz", + "integrity": "sha512-5hYdAkZlcG8tOLujVDTgCT+uPX0VnpAH28gWsLfzpXYm7wP6mp5Q/gYyR7YQ0cKVJcXJnl3j2kpBan13PtQf6w==", + "dev": true, + "requires": { + "delegates": "^1.0.0", + "readable-stream": "^2.0.6" + } + }, + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "requires": { + "sprintf-js": "~1.0.2" + } + }, + "arr-diff": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", + "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", + "dev": true + }, + "arr-flatten": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/arr-flatten/-/arr-flatten-1.1.0.tgz", + "integrity": "sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==", + "dev": true + }, + "arr-union": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-3.1.0.tgz", + "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=", + "dev": true + }, + "array-find-index": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-find-index/-/array-find-index-1.0.2.tgz", + "integrity": "sha1-3wEKoSh+Fku9pvlyOwqWoexBh6E=", + "dev": true + }, + "array-flatten": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-2.1.1.tgz", + "integrity": "sha1-Qmu52oQJDBg42BLIFQryCoMx4pY=", + "dev": true + }, + "array-includes": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.0.3.tgz", + "integrity": "sha1-GEtI9i2S10UrsxsyMWXH+L0CJm0=", + "dev": true, + "requires": { + "define-properties": "^1.1.2", + "es-abstract": "^1.7.0" + } + }, + "array-slice": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/array-slice/-/array-slice-0.2.3.tgz", + "integrity": "sha1-3Tz7gO15c6dRF82sabC5nshhhvU=", + "dev": true + }, + "array-union": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz", + "integrity": "sha1-mjRBDk9OPaI96jdb5b5w8kd47Dk=", + "dev": true, + "requires": { + "array-uniq": "^1.0.1" + } + }, + "array-uniq": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", + "integrity": "sha1-r2rId6Jcx/dOBYiUdThY39sk/bY=", + "dev": true + }, + "array-unique": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", + "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", + "dev": true + }, + "arraybuffer.slice": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/arraybuffer.slice/-/arraybuffer.slice-0.0.6.tgz", + "integrity": "sha1-8zshWfBTKj8xB6JywMz70a0peco=", + "dev": true + }, + "arrify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", + "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=", + "dev": true + }, + "asap": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz", + "integrity": "sha1-5QNHYR1+aQlDIIu9r+vLwvuGbUY=", + "dev": true, + "optional": true + }, + "asn1": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.3.tgz", + "integrity": "sha1-2sh4dxPJlmhJ/IGAd36+nB3fO4Y=", + "dev": true + }, + "asn1.js": { + "version": "4.10.1", + "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-4.10.1.tgz", + "integrity": "sha512-p32cOF5q0Zqs9uBiONKYLm6BClCoBCM5O9JfeUSlnQLBTxYdTK+pW+nXflm8UkKd2UYlEbYz5qEi0JuZR9ckSw==", + "dev": true, + "requires": { + "bn.js": "^4.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" + } + }, + "assert": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/assert/-/assert-1.4.1.tgz", + "integrity": "sha1-mZEtWRg2tab1s0XA8H7vwI/GXZE=", + "dev": true, + "requires": { + "util": "0.10.3" + }, + "dependencies": { + "inherits": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "integrity": "sha1-sX0I0ya0Qj5Wjv9xn5GwscvfafE=", + "dev": true + }, + "util": { + "version": "0.10.3", + "resolved": "https://registry.npmjs.org/util/-/util-0.10.3.tgz", + "integrity": "sha1-evsa/lCAUkZInj23/g7TeTNqwPk=", + "dev": true, + "requires": { + "inherits": "2.0.1" + } + } + } + }, + "assert-plus": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", + "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", + "dev": true + }, + "assign-symbols": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assign-symbols/-/assign-symbols-1.0.0.tgz", + "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=", + "dev": true + }, + "async": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", + "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=", + "dev": true + }, + "async-each": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/async-each/-/async-each-1.0.1.tgz", + "integrity": "sha1-GdOGodntxufByF04iu28xW0zYC0=", + "dev": true + }, + "async-foreach": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/async-foreach/-/async-foreach-0.1.3.tgz", + "integrity": "sha1-NhIfhFwFeBct5Bmpfb6x0W7DRUI=", + "dev": true, + "optional": true + }, + "asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", + "dev": true + }, + "atob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.1.tgz", + "integrity": "sha1-ri1acpR38onWDdf5amMUoi3Wwio=", + "dev": true + }, + "autoprefixer": { + "version": "8.6.5", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-8.6.5.tgz", + "integrity": "sha512-PLWJN3Xo/rycNkx+mp8iBDMTm3FeWe4VmYaZDSqL5QQB9sLsQkG5k8n+LNDFnhh9kdq2K+egL/icpctOmDHwig==", + "dev": true, + "requires": { + "browserslist": "^3.2.8", + "caniuse-lite": "^1.0.30000864", + "normalize-range": "^0.1.2", + "num2fraction": "^1.2.2", + "postcss": "^6.0.23", + "postcss-value-parser": "^3.2.3" + } + }, + "aws-sign2": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", + "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=", + "dev": true + }, + "aws4": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.7.0.tgz", + "integrity": "sha512-32NDda82rhwD9/JBCCkB+MRYDp0oSvlo2IL6rQWA10PQi7tDUM3eqMSltXmY+Oyl/7N3P3qNtAlv7X0d9bI28w==", + "dev": true + }, + "babel-code-frame": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", + "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", + "dev": true, + "requires": { + "chalk": "^1.1.3", + "esutils": "^2.0.2", + "js-tokens": "^3.0.2" + }, + "dependencies": { + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + } + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + } + } + }, + "babel-generator": { + "version": "6.26.1", + "resolved": "https://registry.npmjs.org/babel-generator/-/babel-generator-6.26.1.tgz", + "integrity": "sha512-HyfwY6ApZj7BYTcJURpM5tznulaBvyio7/0d4zFOeMPUmfxkCjHocCuoLa2SAGzBI8AREcH3eP3758F672DppA==", + "dev": true, + "requires": { + "babel-messages": "^6.23.0", + "babel-runtime": "^6.26.0", + "babel-types": "^6.26.0", + "detect-indent": "^4.0.0", + "jsesc": "^1.3.0", + "lodash": "^4.17.4", + "source-map": "^0.5.7", + "trim-right": "^1.0.1" + } + }, + "babel-messages": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-messages/-/babel-messages-6.23.0.tgz", + "integrity": "sha1-8830cDhYA1sqKVHG7F7fbGLyYw4=", + "dev": true, + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-runtime": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", + "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=", + "dev": true, + "requires": { + "core-js": "^2.4.0", + "regenerator-runtime": "^0.11.0" + } + }, + "babel-template": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-template/-/babel-template-6.26.0.tgz", + "integrity": "sha1-3gPi0WOWsGn0bdn/+FIfsaDjXgI=", + "dev": true, + "requires": { + "babel-runtime": "^6.26.0", + "babel-traverse": "^6.26.0", + "babel-types": "^6.26.0", + "babylon": "^6.18.0", + "lodash": "^4.17.4" + } + }, + "babel-traverse": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-traverse/-/babel-traverse-6.26.0.tgz", + "integrity": "sha1-RqnL1+3MYsjlwGTi0tjQ9ANXZu4=", + "dev": true, + "requires": { + "babel-code-frame": "^6.26.0", + "babel-messages": "^6.23.0", + "babel-runtime": "^6.26.0", + "babel-types": "^6.26.0", + "babylon": "^6.18.0", + "debug": "^2.6.8", + "globals": "^9.18.0", + "invariant": "^2.2.2", + "lodash": "^4.17.4" + } + }, + "babel-types": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-types/-/babel-types-6.26.0.tgz", + "integrity": "sha1-o7Bz+Uq0nrb6Vc1lInozQ4BjJJc=", + "dev": true, + "requires": { + "babel-runtime": "^6.26.0", + "esutils": "^2.0.2", + "lodash": "^4.17.4", + "to-fast-properties": "^1.0.3" + } + }, + "babylon": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-6.18.0.tgz", + "integrity": "sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ==", + "dev": true + }, + "backo2": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/backo2/-/backo2-1.0.2.tgz", + "integrity": "sha1-MasayLEpNjRj41s+u2n038+6eUc=", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "base": { + "version": "0.11.2", + "resolved": "https://registry.npmjs.org/base/-/base-0.11.2.tgz", + "integrity": "sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg==", + "dev": true, + "requires": { + "cache-base": "^1.0.1", + "class-utils": "^0.3.5", + "component-emitter": "^1.2.1", + "define-property": "^1.0.0", + "isobject": "^3.0.1", + "mixin-deep": "^1.2.0", + "pascalcase": "^0.1.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "base64-arraybuffer": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-0.1.5.tgz", + "integrity": "sha1-c5JncZI7Whl0etZmqlzUv5xunOg=", + "dev": true + }, + "base64-js": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.3.0.tgz", + "integrity": "sha512-ccav/yGvoa80BQDljCxsmmQ3Xvx60/UpBIij5QN21W3wBi/hhIC9OoO+KLpu9IJTS9j4DRVJ3aDDF9cMSoa2lw==", + "dev": true + }, + "base64id": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/base64id/-/base64id-1.0.0.tgz", + "integrity": "sha1-R2iMuZu2gE8OBtPnY7HDLlfY5rY=", + "dev": true + }, + "batch": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/batch/-/batch-0.6.1.tgz", + "integrity": "sha1-3DQxT05nkxgJP8dgJyUl+UvyXBY=", + "dev": true + }, + "bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", + "dev": true, + "optional": true, + "requires": { + "tweetnacl": "^0.14.3" + } + }, + "better-assert": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/better-assert/-/better-assert-1.0.2.tgz", + "integrity": "sha1-QIZrnhueC1W0gYlDEeaPr/rrxSI=", + "dev": true, + "requires": { + "callsite": "1.0.0" + } + }, + "big.js": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/big.js/-/big.js-3.2.0.tgz", + "integrity": "sha512-+hN/Zh2D08Mx65pZ/4g5bsmNiZUuChDiQfTUQ7qJr4/kuopCr88xZsAXv6mBoZEsUI4OuGHlX59qE94K2mMW8Q==", + "dev": true + }, + "binary-extensions": { + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-1.11.0.tgz", + "integrity": "sha1-RqoXUftqL5PuXmibsQh9SxTGwgU=", + "dev": true + }, + "blob": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/blob/-/blob-0.0.4.tgz", + "integrity": "sha1-vPEwUspURj8w+fx+lbmkdjCpSSE=", + "dev": true + }, + "block-stream": { + "version": "0.0.9", + "resolved": "https://registry.npmjs.org/block-stream/-/block-stream-0.0.9.tgz", + "integrity": "sha1-E+v+d4oDIFz+A3UUgeu0szAMEmo=", + "dev": true, + "optional": true, + "requires": { + "inherits": "~2.0.0" + } + }, + "blocking-proxy": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/blocking-proxy/-/blocking-proxy-1.0.1.tgz", + "integrity": "sha512-KE8NFMZr3mN2E0HcvCgRtX7DjhiIQrwle+nSVJVC/yqFb9+xznHl2ZcoBp2L9qzkI4t4cBFJ1efXF8Dwi132RA==", + "dev": true, + "requires": { + "minimist": "^1.2.0" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + } + } + }, + "bluebird": { + "version": "3.5.1", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.1.tgz", + "integrity": "sha512-MKiLiV+I1AA596t9w1sQJ8jkiSr5+ZKi0WKrYGUn6d1Fx+Ij4tIj+m2WMQSGczs5jZVxV339chE8iwk6F64wjA==", + "dev": true + }, + "bn.js": { + "version": "4.11.8", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.8.tgz", + "integrity": "sha512-ItfYfPLkWHUjckQCk8xC+LwxgK8NYcXywGigJgSwOP8Y2iyWT4f2vsZnoOXTTbo+o5yXmIUJ4gn5538SO5S3gA==", + "dev": true + }, + "body-parser": { + "version": "1.18.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.18.2.tgz", + "integrity": "sha1-h2eKGdhLR9hZuDGZvVm84iKxBFQ=", + "dev": true, + "requires": { + "bytes": "3.0.0", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "~1.1.1", + "http-errors": "~1.6.2", + "iconv-lite": "0.4.19", + "on-finished": "~2.3.0", + "qs": "6.5.1", + "raw-body": "2.3.2", + "type-is": "~1.6.15" + }, + "dependencies": { + "qs": { + "version": "6.5.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.1.tgz", + "integrity": "sha512-eRzhrN1WSINYCDCbrz796z37LOe3m5tmW7RQf6oBntukAG1nmovJvhnwHHRMAfeoItc1m2Hk02WER2aQ/iqs+A==", + "dev": true + } + } + }, + "bonjour": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/bonjour/-/bonjour-3.5.0.tgz", + "integrity": "sha1-jokKGD2O6aI5OzhExpGkK897yfU=", + "dev": true, + "requires": { + "array-flatten": "^2.1.0", + "deep-equal": "^1.0.1", + "dns-equal": "^1.0.0", + "dns-txt": "^2.0.2", + "multicast-dns": "^6.0.1", + "multicast-dns-service-types": "^1.1.0" + } + }, + "boolbase": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", + "integrity": "sha1-aN/1++YMUes3cl6p4+0xDcwed24=", + "dev": true + }, + "boom": { + "version": "2.10.1", + "resolved": "https://registry.npmjs.org/boom/-/boom-2.10.1.tgz", + "integrity": "sha1-OciRjO/1eZ+D+UkqhI9iWt0Mdm8=", + "dev": true, + "requires": { + "hoek": "2.x.x" + } + }, + "bootstrap": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/bootstrap/-/bootstrap-4.1.2.tgz", + "integrity": "sha512-3bP609EdMc/8EwgGp8KgpN8HwnR4V4lZ9CTi5pImMrXNxpkw7dK1B05aMwQWpG1ZWmTLlBSN/uzkuz5GsmQNFA==" + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "braces": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.2.tgz", + "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==", + "dev": true, + "requires": { + "arr-flatten": "^1.1.0", + "array-unique": "^0.3.2", + "extend-shallow": "^2.0.1", + "fill-range": "^4.0.0", + "isobject": "^3.0.1", + "repeat-element": "^1.1.2", + "snapdragon": "^0.8.1", + "snapdragon-node": "^2.0.1", + "split-string": "^3.0.2", + "to-regex": "^3.0.1" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "brorand": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/brorand/-/brorand-1.1.0.tgz", + "integrity": "sha1-EsJe/kCkXjwyPrhnWgoM5XsiNx8=", + "dev": true + }, + "browserify-aes": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", + "integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==", + "dev": true, + "requires": { + "buffer-xor": "^1.0.3", + "cipher-base": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.3", + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "browserify-cipher": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/browserify-cipher/-/browserify-cipher-1.0.1.tgz", + "integrity": "sha512-sPhkz0ARKbf4rRQt2hTpAHqn47X3llLkUGn+xEJzLjwY8LRs2p0v7ljvI5EyoRO/mexrNunNECisZs+gw2zz1w==", + "dev": true, + "requires": { + "browserify-aes": "^1.0.4", + "browserify-des": "^1.0.0", + "evp_bytestokey": "^1.0.0" + } + }, + "browserify-des": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/browserify-des/-/browserify-des-1.0.2.tgz", + "integrity": "sha512-BioO1xf3hFwz4kc6iBhI3ieDFompMhrMlnDFC4/0/vd5MokpuAc3R+LYbwTA9A5Yc9pq9UYPqffKpW2ObuwX5A==", + "dev": true, + "requires": { + "cipher-base": "^1.0.1", + "des.js": "^1.0.0", + "inherits": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, + "browserify-rsa": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz", + "integrity": "sha1-IeCr+vbyApzy+vsTNWenAdQTVSQ=", + "dev": true, + "requires": { + "bn.js": "^4.1.0", + "randombytes": "^2.0.1" + } + }, + "browserify-sign": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.0.4.tgz", + "integrity": "sha1-qk62jl17ZYuqa/alfmMMvXqT0pg=", + "dev": true, + "requires": { + "bn.js": "^4.1.1", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "create-hmac": "^1.1.2", + "elliptic": "^6.0.0", + "inherits": "^2.0.1", + "parse-asn1": "^5.0.0" + } + }, + "browserify-zlib": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.2.0.tgz", + "integrity": "sha512-Z942RysHXmJrhqk88FmKBVq/v5tqmSkDz7p54G/MGyjMnCFFnC79XWNbg+Vta8W6Wb2qtSZTSxIGkJrRpCFEiA==", + "dev": true, + "requires": { + "pako": "~1.0.5" + } + }, + "browserslist": { + "version": "3.2.8", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-3.2.8.tgz", + "integrity": "sha512-WHVocJYavUwVgVViC0ORikPHQquXwVh939TaelZ4WDqpWgTX/FsGhl/+P4qBUAGcRvtOgDgC+xftNWWp2RUTAQ==", + "dev": true, + "requires": { + "caniuse-lite": "^1.0.30000844", + "electron-to-chromium": "^1.3.47" + } + }, + "buffer": { + "version": "4.9.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.1.tgz", + "integrity": "sha1-bRu2AbB6TvztlwlBMgkwJ8lbwpg=", + "dev": true, + "requires": { + "base64-js": "^1.0.2", + "ieee754": "^1.1.4", + "isarray": "^1.0.0" + } + }, + "buffer-from": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.0.tgz", + "integrity": "sha512-c5mRlguI/Pe2dSZmpER62rSCu0ryKmWddzRYsuXc50U2/g8jMOulc31VZMa4mYx31U5xsmSOpDCgH88Vl9cDGQ==", + "dev": true + }, + "buffer-indexof": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/buffer-indexof/-/buffer-indexof-1.1.1.tgz", + "integrity": "sha512-4/rOEg86jivtPTeOUUT61jJO1Ya1TrR/OkqCSZDyq84WJh3LuuiphBYJN+fm5xufIk4XAFcEwte/8WzC8If/1g==", + "dev": true + }, + "buffer-xor": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", + "integrity": "sha1-JuYe0UIvtw3ULm42cp7VHYVf6Nk=", + "dev": true + }, + "builtin-modules": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-1.1.1.tgz", + "integrity": "sha1-Jw8HbFpywC9bZaR9+Uxf46J4iS8=", + "dev": true + }, + "builtin-status-codes": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/builtin-status-codes/-/builtin-status-codes-3.0.0.tgz", + "integrity": "sha1-hZgoeOIbmOHGZCXgPQF0eI9Wnug=", + "dev": true + }, + "builtins": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/builtins/-/builtins-1.0.3.tgz", + "integrity": "sha1-y5T662HIaWRR2zZTThQi+U8K7og=", + "dev": true + }, + "bytes": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz", + "integrity": "sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg=", + "dev": true + }, + "cacache": { + "version": "10.0.4", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-10.0.4.tgz", + "integrity": "sha512-Dph0MzuH+rTQzGPNT9fAnrPmMmjKfST6trxJeK7NQuHRaVw24VzPRWTmg9MpcwOVQZO0E1FBICUlFeNaKPIfHA==", + "dev": true, + "requires": { + "bluebird": "^3.5.1", + "chownr": "^1.0.1", + "glob": "^7.1.2", + "graceful-fs": "^4.1.11", + "lru-cache": "^4.1.1", + "mississippi": "^2.0.0", + "mkdirp": "^0.5.1", + "move-concurrently": "^1.0.1", + "promise-inflight": "^1.0.1", + "rimraf": "^2.6.2", + "ssri": "^5.2.4", + "unique-filename": "^1.1.0", + "y18n": "^4.0.0" + } + }, + "cache-base": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz", + "integrity": "sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ==", + "dev": true, + "requires": { + "collection-visit": "^1.0.0", + "component-emitter": "^1.2.1", + "get-value": "^2.0.6", + "has-value": "^1.0.0", + "isobject": "^3.0.1", + "set-value": "^2.0.0", + "to-object-path": "^0.3.0", + "union-value": "^1.0.0", + "unset-value": "^1.0.0" + } + }, + "cache-loader": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cache-loader/-/cache-loader-1.2.2.tgz", + "integrity": "sha512-rsGh4SIYyB9glU+d0OcHwiXHXBoUgDhHZaQ1KAbiXqfz1CDPxtTboh1gPbJ0q2qdO8a9lfcjgC5CJ2Ms32y5bw==", + "dev": true, + "requires": { + "loader-utils": "^1.1.0", + "mkdirp": "^0.5.1", + "neo-async": "^2.5.0", + "schema-utils": "^0.4.2" + } + }, + "callsite": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/callsite/-/callsite-1.0.0.tgz", + "integrity": "sha1-KAOY5dZkvXQDi28JBRU+borxvCA=", + "dev": true + }, + "camel-case": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/camel-case/-/camel-case-3.0.0.tgz", + "integrity": "sha1-yjw2iKTpzzpM2nd9xNy8cTJJz3M=", + "dev": true, + "requires": { + "no-case": "^2.2.0", + "upper-case": "^1.1.1" + } + }, + "camelcase": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-1.2.1.tgz", + "integrity": "sha1-m7UwTS4LVmmLLHWLCKPqqdqlijk=", + "dev": true, + "optional": true + }, + "camelcase-keys": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz", + "integrity": "sha1-MIvur/3ygRkFHvodkyITyRuPkuc=", + "dev": true, + "requires": { + "camelcase": "^2.0.0", + "map-obj": "^1.0.0" + }, + "dependencies": { + "camelcase": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-2.1.1.tgz", + "integrity": "sha1-fB0W1nmhu+WcoCys7PsBHiAfWh8=", + "dev": true + } + } + }, + "caniuse-lite": { + "version": "1.0.30000865", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30000865.tgz", + "integrity": "sha512-vs79o1mOSKRGv/1pSkp4EXgl4ZviWeYReXw60XfacPU64uQWZwJT6vZNmxRF9O+6zu71sJwMxLK5JXxbzuVrLw==", + "dev": true + }, + "caseless": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", + "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=", + "dev": true + }, + "center-align": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/center-align/-/center-align-0.1.3.tgz", + "integrity": "sha1-qg0yYptu6XIgBBHL1EYckHvCt60=", + "dev": true, + "optional": true, + "requires": { + "align-text": "^0.1.3", + "lazy-cache": "^1.0.3" + } + }, + "chalk": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.2.2.tgz", + "integrity": "sha512-LvixLAQ4MYhbf7hgL4o5PeK32gJKvVzDRiSNIApDofQvyhl8adgG2lJVXn4+ekQoK7HL9RF8lqxwerpe0x2pCw==", + "dev": true, + "requires": { + "ansi-styles": "^3.1.0", + "escape-string-regexp": "^1.0.5", + "supports-color": "^4.0.0" + }, + "dependencies": { + "has-flag": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-2.0.0.tgz", + "integrity": "sha1-6CB68cx7MNRGzHC3NLXovhj4jVE=", + "dev": true + }, + "supports-color": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-4.5.0.tgz", + "integrity": "sha1-vnoN5ITexcXN34s9WRJQRJEvY1s=", + "dev": true, + "requires": { + "has-flag": "^2.0.0" + } + } + } + }, + "chokidar": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-2.0.4.tgz", + "integrity": "sha512-z9n7yt9rOvIJrMhvDtDictKrkFHeihkNl6uWMmZlmL6tJtX9Cs+87oK+teBx+JIgzvbX3yZHT3eF8vpbDxHJXQ==", + "dev": true, + "requires": { + "anymatch": "^2.0.0", + "async-each": "^1.0.0", + "braces": "^2.3.0", + "fsevents": "^1.2.2", + "glob-parent": "^3.1.0", + "inherits": "^2.0.1", + "is-binary-path": "^1.0.0", + "is-glob": "^4.0.0", + "lodash.debounce": "^4.0.8", + "normalize-path": "^2.1.1", + "path-is-absolute": "^1.0.0", + "readdirp": "^2.0.0", + "upath": "^1.0.5" + } + }, + "chownr": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.0.1.tgz", + "integrity": "sha1-4qdQQqlVGQi+vSW4Uj1fl2nXkYE=", + "dev": true + }, + "chrome-trace-event": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-0.1.3.tgz", + "integrity": "sha512-sjndyZHrrWiu4RY7AkHgjn80GfAM2ZSzUkZLV/Js59Ldmh6JDThf0SUmOHU53rFu2rVxxfCzJ30Ukcfch3Gb/A==", + "dev": true + }, + "cipher-base": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.4.tgz", + "integrity": "sha512-Kkht5ye6ZGmwv40uUDZztayT2ThLQGfnj/T71N/XzeZeo3nf8foyW7zGTsPYkEya3m5f3cAypH+qe7YOrM1U2Q==", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "circular-dependency-plugin": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/circular-dependency-plugin/-/circular-dependency-plugin-5.0.2.tgz", + "integrity": "sha512-oC7/DVAyfcY3UWKm0sN/oVoDedQDQiw/vIiAnuTWTpE5s0zWf7l3WY417Xw/Fbi/QbAjctAkxgMiS9P0s3zkmA==", + "dev": true + }, + "class-utils": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz", + "integrity": "sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg==", + "dev": true, + "requires": { + "arr-union": "^3.1.0", + "define-property": "^0.2.5", + "isobject": "^3.0.0", + "static-extend": "^0.1.1" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + } + } + }, + "clean-css": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/clean-css/-/clean-css-4.1.11.tgz", + "integrity": "sha1-Ls3xRaujj1R0DybO/Q/z4D4SXWo=", + "dev": true, + "requires": { + "source-map": "0.5.x" + } + }, + "cliui": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-2.1.0.tgz", + "integrity": "sha1-S0dXYP+AJkx2LDoXGQMukcf+oNE=", + "dev": true, + "optional": true, + "requires": { + "center-align": "^0.1.1", + "right-align": "^0.1.1", + "wordwrap": "0.0.2" + }, + "dependencies": { + "wordwrap": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.2.tgz", + "integrity": "sha1-t5Zpu0LstAn4PVg8rVLKF+qhZD8=", + "dev": true, + "optional": true + } + } + }, + "clone": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.1.tgz", + "integrity": "sha1-0hfR6WERjjrJpLi7oyhVU79kfNs=", + "dev": true + }, + "clone-deep": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/clone-deep/-/clone-deep-2.0.2.tgz", + "integrity": "sha512-SZegPTKjCgpQH63E+eN6mVEEPdQBOUzjyJm5Pora4lrwWRFS8I0QAxV/KD6vV/i0WuijHZWQC1fMsPEdxfdVCQ==", + "dev": true, + "requires": { + "for-own": "^1.0.0", + "is-plain-object": "^2.0.4", + "kind-of": "^6.0.0", + "shallow-clone": "^1.0.0" + } + }, + "co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=", + "dev": true + }, + "code-point-at": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz", + "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=", + "dev": true + }, + "codelyzer": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/codelyzer/-/codelyzer-4.2.1.tgz", + "integrity": "sha512-CKwfgpfkqi9dyzy4s6ELaxJ54QgJ6A8iTSsM4bzHbLuTpbKncvNc3DUlCvpnkHBhK47gEf4qFsWoYqLrJPhy6g==", + "dev": true, + "requires": { + "app-root-path": "^2.0.1", + "css-selector-tokenizer": "^0.7.0", + "cssauron": "^1.4.0", + "semver-dsl": "^1.0.1", + "source-map": "^0.5.6", + "sprintf-js": "^1.0.3" + } + }, + "collection-visit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/collection-visit/-/collection-visit-1.0.0.tgz", + "integrity": "sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA=", + "dev": true, + "requires": { + "map-visit": "^1.0.0", + "object-visit": "^1.0.0" + } + }, + "color-convert": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.2.tgz", + "integrity": "sha512-3NUJZdhMhcdPn8vJ9v2UQJoH0qqoGUkYTgFEPZaPjEtwmmKUfNV46zZmgB2M5M4DCEQHMaCfWHCxiBflLm04Tg==", + "dev": true, + "requires": { + "color-name": "1.1.1" + } + }, + "color-name": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.1.tgz", + "integrity": "sha1-SxQVMEz1ACjqgWQ2Q72C6gWANok=", + "dev": true + }, + "colors": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.1.2.tgz", + "integrity": "sha1-FopHAXVran9RoSzgyXv6KMCE7WM=", + "dev": true + }, + "combine-lists": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/combine-lists/-/combine-lists-1.0.1.tgz", + "integrity": "sha1-RYwH4J4NkA/Ci3Cj/sLazR0st/Y=", + "dev": true, + "requires": { + "lodash": "^4.5.0" + } + }, + "combined-stream": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.6.tgz", + "integrity": "sha1-cj599ugBrFYTETp+RFqbactjKBg=", + "dev": true, + "requires": { + "delayed-stream": "~1.0.0" + } + }, + "commander": { + "version": "2.16.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.16.0.tgz", + "integrity": "sha512-sVXqklSaotK9at437sFlFpyOcJonxe0yST/AG9DkQKUdIE6IqGIMv4SfAQSKaJbSdVEJYItASCrBiVQHq1HQew==", + "dev": true + }, + "commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=", + "dev": true + }, + "compare-versions": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-3.3.0.tgz", + "integrity": "sha512-MAAAIOdi2s4Gl6rZ76PNcUa9IOYB+5ICdT41o5uMRf09aEu/F9RK+qhe8RjXNPwcTjGV7KU7h2P/fljThFVqyQ==", + "dev": true + }, + "component-bind": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/component-bind/-/component-bind-1.0.0.tgz", + "integrity": "sha1-AMYIq33Nk4l8AAllGx06jh5zu9E=", + "dev": true + }, + "component-emitter": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.2.1.tgz", + "integrity": "sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=", + "dev": true + }, + "component-inherit": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/component-inherit/-/component-inherit-0.0.3.tgz", + "integrity": "sha1-ZF/ErfWLcrZJ1crmUTVhnbJv8UM=", + "dev": true + }, + "compressible": { + "version": "2.0.14", + "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.14.tgz", + "integrity": "sha1-MmxfUH+7BV9UEWeCuWmoG2einac=", + "dev": true, + "requires": { + "mime-db": ">= 1.34.0 < 2" + } + }, + "compression": { + "version": "1.7.3", + "resolved": "https://registry.npmjs.org/compression/-/compression-1.7.3.tgz", + "integrity": "sha512-HSjyBG5N1Nnz7tF2+O7A9XUhyjru71/fwgNb7oIsEVHR0WShfs2tIS/EySLgiTe98aOK18YDlMXpzjCXY/n9mg==", + "dev": true, + "requires": { + "accepts": "~1.3.5", + "bytes": "3.0.0", + "compressible": "~2.0.14", + "debug": "2.6.9", + "on-headers": "~1.0.1", + "safe-buffer": "5.1.2", + "vary": "~1.1.2" + } + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "concat-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + } + }, + "connect": { + "version": "3.6.6", + "resolved": "https://registry.npmjs.org/connect/-/connect-3.6.6.tgz", + "integrity": "sha1-Ce/2xVr3I24TcTWnJXSFi2eG9SQ=", + "dev": true, + "requires": { + "debug": "2.6.9", + "finalhandler": "1.1.0", + "parseurl": "~1.3.2", + "utils-merge": "1.0.1" + }, + "dependencies": { + "finalhandler": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.0.tgz", + "integrity": "sha1-zgtoVbRYU+eRsvzGgARtiCU91/U=", + "dev": true, + "requires": { + "debug": "2.6.9", + "encodeurl": "~1.0.1", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "parseurl": "~1.3.2", + "statuses": "~1.3.1", + "unpipe": "~1.0.0" + } + }, + "statuses": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.3.1.tgz", + "integrity": "sha1-+vUbnrdKrvOzrPStX2Gr8ky3uT4=", + "dev": true + } + } + }, + "connect-history-api-fallback": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/connect-history-api-fallback/-/connect-history-api-fallback-1.5.0.tgz", + "integrity": "sha1-sGhzk0vF40T+9hGhlqb6rgruAVo=", + "dev": true + }, + "console-browserify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.1.0.tgz", + "integrity": "sha1-8CQcRXMKn8YyOyBtvzjtx0HQuxA=", + "dev": true, + "requires": { + "date-now": "^0.1.4" + } + }, + "console-control-strings": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", + "integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=", + "dev": true + }, + "constants-browserify": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/constants-browserify/-/constants-browserify-1.0.0.tgz", + "integrity": "sha1-wguW2MYXdIqvHBYCF2DNJ/y4y3U=", + "dev": true + }, + "content-disposition": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.2.tgz", + "integrity": "sha1-DPaLud318r55YcOoUXjLhdunjLQ=", + "dev": true + }, + "content-type": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", + "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==", + "dev": true + }, + "convert-source-map": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.5.1.tgz", + "integrity": "sha1-uCeAl7m8IpNl3lxiz1/K7YtVmeU=", + "dev": true + }, + "cookie": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.3.1.tgz", + "integrity": "sha1-5+Ch+e9DtMi6klxcWpboBtFoc7s=", + "dev": true + }, + "cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=", + "dev": true + }, + "copy-concurrently": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/copy-concurrently/-/copy-concurrently-1.0.5.tgz", + "integrity": "sha512-f2domd9fsVDFtaFcbaRZuYXwtdmnzqbADSwhSWYxYB/Q8zsdUUFMXVRwXGDMWmbEzAn1kdRrtI1T/KTFOL4X2A==", + "dev": true, + "requires": { + "aproba": "^1.1.1", + "fs-write-stream-atomic": "^1.0.8", + "iferr": "^0.1.5", + "mkdirp": "^0.5.1", + "rimraf": "^2.5.4", + "run-queue": "^1.0.0" + } + }, + "copy-descriptor": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", + "integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=", + "dev": true + }, + "copy-webpack-plugin": { + "version": "4.5.2", + "resolved": "https://registry.npmjs.org/copy-webpack-plugin/-/copy-webpack-plugin-4.5.2.tgz", + "integrity": "sha512-zmC33E8FFSq3AbflTvqvPvBo621H36Afsxlui91d+QyZxPIuXghfnTsa1CuqiAaCPgJoSUWfTFbKJnadZpKEbQ==", + "dev": true, + "requires": { + "cacache": "^10.0.4", + "find-cache-dir": "^1.0.0", + "globby": "^7.1.1", + "is-glob": "^4.0.0", + "loader-utils": "^1.1.0", + "minimatch": "^3.0.4", + "p-limit": "^1.0.0", + "serialize-javascript": "^1.4.0" + } + }, + "core-js": { + "version": "2.5.7", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.5.7.tgz", + "integrity": "sha512-RszJCAxg/PP6uzXVXL6BsxSXx/B05oJAQ2vkJRjyjrEcNVycaqOmNb5OTxZPE3xa5gwZduqza6L9JOCenh/Ecw==" + }, + "core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", + "dev": true + }, + "cosmiconfig": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-4.0.0.tgz", + "integrity": "sha512-6e5vDdrXZD+t5v0L8CrurPeybg4Fmf+FCSYxXKYVAqLUtyCSbuyqE059d0kDthTNRzKVjL7QMgNpEUlsoYH3iQ==", + "dev": true, + "requires": { + "is-directory": "^0.3.1", + "js-yaml": "^3.9.0", + "parse-json": "^4.0.0", + "require-from-string": "^2.0.1" + }, + "dependencies": { + "parse-json": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", + "integrity": "sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA=", + "dev": true, + "requires": { + "error-ex": "^1.3.1", + "json-parse-better-errors": "^1.0.1" + } + } + } + }, + "create-ecdh": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/create-ecdh/-/create-ecdh-4.0.3.tgz", + "integrity": "sha512-GbEHQPMOswGpKXM9kCWVrremUcBmjteUaQ01T9rkKCPDXfUHX0IoP9LpHYo2NPFampa4e+/pFDc3jQdxrxQLaw==", + "dev": true, + "requires": { + "bn.js": "^4.1.0", + "elliptic": "^6.0.0" + } + }, + "create-hash": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", + "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==", + "dev": true, + "requires": { + "cipher-base": "^1.0.1", + "inherits": "^2.0.1", + "md5.js": "^1.3.4", + "ripemd160": "^2.0.1", + "sha.js": "^2.4.0" + } + }, + "create-hmac": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz", + "integrity": "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==", + "dev": true, + "requires": { + "cipher-base": "^1.0.3", + "create-hash": "^1.1.0", + "inherits": "^2.0.1", + "ripemd160": "^2.0.0", + "safe-buffer": "^5.0.1", + "sha.js": "^2.4.8" + } + }, + "cross-spawn": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-3.0.1.tgz", + "integrity": "sha1-ElYDfsufDF9549bvE14wdwGEuYI=", + "dev": true, + "optional": true, + "requires": { + "lru-cache": "^4.0.1", + "which": "^1.2.9" + } + }, + "cryptiles": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/cryptiles/-/cryptiles-2.0.5.tgz", + "integrity": "sha1-O9/s3GCBR8HGcgL6KR59ylnqo7g=", + "dev": true, + "optional": true, + "requires": { + "boom": "2.x.x" + } + }, + "crypto-browserify": { + "version": "3.12.0", + "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.12.0.tgz", + "integrity": "sha512-fz4spIh+znjO2VjL+IdhEpRJ3YN6sMzITSBijk6FK2UvTqruSQW+/cCZTSNsMiZNvUeq0CqurF+dAbyiGOY6Wg==", + "dev": true, + "requires": { + "browserify-cipher": "^1.0.0", + "browserify-sign": "^4.0.0", + "create-ecdh": "^4.0.0", + "create-hash": "^1.1.0", + "create-hmac": "^1.1.0", + "diffie-hellman": "^5.0.0", + "inherits": "^2.0.1", + "pbkdf2": "^3.0.3", + "public-encrypt": "^4.0.0", + "randombytes": "^2.0.0", + "randomfill": "^1.0.3" + } + }, + "css-parse": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/css-parse/-/css-parse-1.7.0.tgz", + "integrity": "sha1-Mh9s9zeCpv91ERE5D8BeLGV9jJs=", + "dev": true + }, + "css-select": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/css-select/-/css-select-1.2.0.tgz", + "integrity": "sha1-KzoRBTnFNV8c2NMUYj6HCxIeyFg=", + "dev": true, + "requires": { + "boolbase": "~1.0.0", + "css-what": "2.1", + "domutils": "1.5.1", + "nth-check": "~1.0.1" + } + }, + "css-selector-tokenizer": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/css-selector-tokenizer/-/css-selector-tokenizer-0.7.0.tgz", + "integrity": "sha1-5piEdK6MlTR3v15+/s/OzNnPTIY=", + "dev": true, + "requires": { + "cssesc": "^0.1.0", + "fastparse": "^1.1.1", + "regexpu-core": "^1.0.0" + } + }, + "css-what": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-2.1.0.tgz", + "integrity": "sha1-lGfQMsOM+u+58teVASUwYvh/ob0=", + "dev": true + }, + "cssauron": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/cssauron/-/cssauron-1.4.0.tgz", + "integrity": "sha1-pmAt/34EqDBtwNuaVR6S6LVmKtg=", + "dev": true, + "requires": { + "through": "X.X.X" + } + }, + "cssesc": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-0.1.0.tgz", + "integrity": "sha1-yBSQPkViM3GgR3tAEJqq++6t27Q=", + "dev": true + }, + "cuint": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/cuint/-/cuint-0.2.2.tgz", + "integrity": "sha1-QICG1AlVDCYxFVYZ6fp7ytw7mRs=", + "dev": true + }, + "currently-unhandled": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/currently-unhandled/-/currently-unhandled-0.4.1.tgz", + "integrity": "sha1-mI3zP+qxke95mmE2nddsF635V+o=", + "dev": true, + "requires": { + "array-find-index": "^1.0.1" + } + }, + "custom-event": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/custom-event/-/custom-event-1.0.1.tgz", + "integrity": "sha1-XQKkaFCt8bSjF5RqOSj8y1v9BCU=", + "dev": true + }, + "cyclist": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/cyclist/-/cyclist-0.2.2.tgz", + "integrity": "sha1-GzN5LhHpFKL9bW7WRHRkRE5fpkA=", + "dev": true + }, + "d": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/d/-/d-1.0.0.tgz", + "integrity": "sha1-dUu1v+VUUdpppYuU1F9MWwRi1Y8=", + "dev": true, + "requires": { + "es5-ext": "^0.10.9" + } + }, + "dashdash": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", + "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", + "dev": true, + "requires": { + "assert-plus": "^1.0.0" + } + }, + "date-now": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/date-now/-/date-now-0.1.4.tgz", + "integrity": "sha1-6vQ5/U1ISK105cx9vvIAZyueNFs=", + "dev": true + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", + "dev": true + }, + "decode-uri-component": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz", + "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=", + "dev": true + }, + "deep-equal": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.0.1.tgz", + "integrity": "sha1-9dJgKStmDghO/0zbyfCK0yR0SLU=", + "dev": true + }, + "deep-is": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "dev": true + }, + "default-require-extensions": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/default-require-extensions/-/default-require-extensions-2.0.0.tgz", + "integrity": "sha1-9fj7sYp9bVCyH2QfZJ67Uiz+JPc=", + "dev": true, + "requires": { + "strip-bom": "^3.0.0" + }, + "dependencies": { + "strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", + "dev": true + } + } + }, + "define-properties": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.2.tgz", + "integrity": "sha1-g6c/L+pWmJj7c3GTyPhzyvbUXJQ=", + "dev": true, + "requires": { + "foreach": "^2.0.5", + "object-keys": "^1.0.8" + } + }, + "define-property": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-2.0.2.tgz", + "integrity": "sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ==", + "dev": true, + "requires": { + "is-descriptor": "^1.0.2", + "isobject": "^3.0.1" + }, + "dependencies": { + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "del": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/del/-/del-3.0.0.tgz", + "integrity": "sha1-U+z2mf/LyzljdpGrE7rxYIGXZuU=", + "dev": true, + "requires": { + "globby": "^6.1.0", + "is-path-cwd": "^1.0.0", + "is-path-in-cwd": "^1.0.0", + "p-map": "^1.1.1", + "pify": "^3.0.0", + "rimraf": "^2.2.8" + }, + "dependencies": { + "globby": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-6.1.0.tgz", + "integrity": "sha1-9abXDoOV4hyFj7BInWTfAkJNUGw=", + "dev": true, + "requires": { + "array-union": "^1.0.1", + "glob": "^7.0.3", + "object-assign": "^4.0.1", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" + }, + "dependencies": { + "pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", + "dev": true + } + } + } + } + }, + "delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", + "dev": true + }, + "delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=", + "dev": true + }, + "depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", + "dev": true + }, + "des.js": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.0.0.tgz", + "integrity": "sha1-wHTS4qpqipoH29YfmhXCzYPsjsw=", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" + } + }, + "destroy": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", + "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=", + "dev": true + }, + "detect-indent": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-4.0.0.tgz", + "integrity": "sha1-920GQ1LN9Docts5hnE7jqUdd4gg=", + "dev": true, + "requires": { + "repeating": "^2.0.0" + } + }, + "detect-node": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.0.3.tgz", + "integrity": "sha1-ogM8CcyOFY03dI+951B4Mr1s4Sc=", + "dev": true + }, + "di": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/di/-/di-0.0.1.tgz", + "integrity": "sha1-gGZJMmzqp8qjMG112YXqJ0i6kTw=", + "dev": true + }, + "diff": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz", + "integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==", + "dev": true + }, + "diffie-hellman": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz", + "integrity": "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==", + "dev": true, + "requires": { + "bn.js": "^4.1.0", + "miller-rabin": "^4.0.0", + "randombytes": "^2.0.0" + } + }, + "dir-glob": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-2.0.0.tgz", + "integrity": "sha512-37qirFDz8cA5fimp9feo43fSuRo2gHwaIn6dXL8Ber1dGwUosDrGZeCCXq57WnIqE4aQ+u3eQZzsk1yOzhdwag==", + "dev": true, + "requires": { + "arrify": "^1.0.1", + "path-type": "^3.0.0" + } + }, + "dns-equal": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/dns-equal/-/dns-equal-1.0.0.tgz", + "integrity": "sha1-s55/HabrCnW6nBcySzR1PEfgZU0=", + "dev": true + }, + "dns-packet": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-1.3.1.tgz", + "integrity": "sha512-0UxfQkMhYAUaZI+xrNZOz/as5KgDU0M/fQ9b6SpkyLbk3GEswDi6PADJVaYJradtRVsRIlF1zLyOodbcTCDzUg==", + "dev": true, + "requires": { + "ip": "^1.1.0", + "safe-buffer": "^5.0.1" + } + }, + "dns-txt": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/dns-txt/-/dns-txt-2.0.2.tgz", + "integrity": "sha1-uR2Ab10nGI5Ks+fRB9iBocxGQrY=", + "dev": true, + "requires": { + "buffer-indexof": "^1.0.0" + } + }, + "dom-converter": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/dom-converter/-/dom-converter-0.1.4.tgz", + "integrity": "sha1-pF71cnuJDJv/5tfIduexnLDhfzs=", + "dev": true, + "requires": { + "utila": "~0.3" + }, + "dependencies": { + "utila": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/utila/-/utila-0.3.3.tgz", + "integrity": "sha1-1+jn1+MJEHCSsF+NloiCTWM6QiY=", + "dev": true + } + } + }, + "dom-serialize": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/dom-serialize/-/dom-serialize-2.2.1.tgz", + "integrity": "sha1-ViromZ9Evl6jB29UGdzVnrQ6yVs=", + "dev": true, + "requires": { + "custom-event": "~1.0.0", + "ent": "~2.2.0", + "extend": "^3.0.0", + "void-elements": "^2.0.0" + } + }, + "dom-serializer": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.1.0.tgz", + "integrity": "sha1-BzxpdUbOB4DOI75KKOKT5AvDDII=", + "dev": true, + "requires": { + "domelementtype": "~1.1.1", + "entities": "~1.1.1" + }, + "dependencies": { + "domelementtype": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.1.3.tgz", + "integrity": "sha1-vSh3PiZCiBrsUVRJJCmcXNgiGFs=", + "dev": true + } + } + }, + "domain-browser": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/domain-browser/-/domain-browser-1.2.0.tgz", + "integrity": "sha512-jnjyiM6eRyZl2H+W8Q/zLMA481hzi0eszAaBUzIVnmYVDBbnLxVNnfu1HgEBvCbL+71FrxMl3E6lpKH7Ge3OXA==", + "dev": true + }, + "domelementtype": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.0.tgz", + "integrity": "sha1-sXrtguirWeUt2cGbF1bg/BhyBMI=", + "dev": true + }, + "domhandler": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.1.0.tgz", + "integrity": "sha1-0mRvXlf2w7qxHPbLBdPArPdBJZQ=", + "dev": true, + "requires": { + "domelementtype": "1" + } + }, + "domutils": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.5.1.tgz", + "integrity": "sha1-3NhIiib1Y9YQeeSMn3t+Mjc2gs8=", + "dev": true, + "requires": { + "dom-serializer": "0", + "domelementtype": "1" + } + }, + "duplexify": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-3.6.0.tgz", + "integrity": "sha512-fO3Di4tBKJpYTFHAxTU00BcfWMY9w24r/x21a6rZRbsD/ToUgGxsMbiGRmB7uVAXeGKXD9MwiLZa5E97EVgIRQ==", + "dev": true, + "requires": { + "end-of-stream": "^1.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.0.0", + "stream-shift": "^1.0.0" + } + }, + "ecc-jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz", + "integrity": "sha1-D8c6ntXw1Tw4GTOYUj735UN3dQU=", + "dev": true, + "optional": true, + "requires": { + "jsbn": "~0.1.0" + } + }, + "ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=", + "dev": true + }, + "ejs": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-2.6.1.tgz", + "integrity": "sha512-0xy4A/twfrRCnkhfk8ErDi5DqdAsAqeGxht4xkCUrsvhhbQNs7E+4jV0CN7+NKIY0aHE72+XvqtBIXzD31ZbXQ==", + "dev": true + }, + "electron-to-chromium": { + "version": "1.3.52", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.52.tgz", + "integrity": "sha1-0tnxJwuko7lnuDHEDvcftNmrXOA=", + "dev": true + }, + "elliptic": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.4.0.tgz", + "integrity": "sha1-ysmvh2LIWDYYcAPI3+GT5eLq5d8=", + "dev": true, + "requires": { + "bn.js": "^4.4.0", + "brorand": "^1.0.1", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.0" + } + }, + "emojis-list": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-2.1.0.tgz", + "integrity": "sha1-TapNnbAPmBmIDHn6RXrlsJof04k=", + "dev": true + }, + "encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=", + "dev": true + }, + "end-of-stream": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.1.tgz", + "integrity": "sha512-1MkrZNvWTKCaigbn+W15elq2BB/L22nqrSY5DKlo3X6+vclJm8Bb5djXJBmEX6fS3+zCh/F4VBK5Z2KxJt4s2Q==", + "dev": true, + "requires": { + "once": "^1.4.0" + } + }, + "engine.io": { + "version": "1.8.3", + "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-1.8.3.tgz", + "integrity": "sha1-jef5eJXSDTm4X4ju7nd7K9QrE9Q=", + "dev": true, + "requires": { + "accepts": "1.3.3", + "base64id": "1.0.0", + "cookie": "0.3.1", + "debug": "2.3.3", + "engine.io-parser": "1.3.2", + "ws": "1.1.2" + }, + "dependencies": { + "accepts": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.3.tgz", + "integrity": "sha1-w8p0NJOGSMPg2cHjKN1otiLChMo=", + "dev": true, + "requires": { + "mime-types": "~2.1.11", + "negotiator": "0.6.1" + } + }, + "debug": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.3.3.tgz", + "integrity": "sha1-QMRT5n5uE8kB3ewxeviYbNqe/4w=", + "dev": true, + "requires": { + "ms": "0.7.2" + } + }, + "ms": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.2.tgz", + "integrity": "sha1-riXPJRKziFodldfwN4aNhDESR2U=", + "dev": true + } + } + }, + "engine.io-client": { + "version": "1.8.3", + "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-1.8.3.tgz", + "integrity": "sha1-F5jtk0USRkU9TG9jXXogH+lA1as=", + "dev": true, + "requires": { + "component-emitter": "1.2.1", + "component-inherit": "0.0.3", + "debug": "2.3.3", + "engine.io-parser": "1.3.2", + "has-cors": "1.1.0", + "indexof": "0.0.1", + "parsejson": "0.0.3", + "parseqs": "0.0.5", + "parseuri": "0.0.5", + "ws": "1.1.2", + "xmlhttprequest-ssl": "1.5.3", + "yeast": "0.1.2" + }, + "dependencies": { + "debug": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.3.3.tgz", + "integrity": "sha1-QMRT5n5uE8kB3ewxeviYbNqe/4w=", + "dev": true, + "requires": { + "ms": "0.7.2" + } + }, + "ms": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.2.tgz", + "integrity": "sha1-riXPJRKziFodldfwN4aNhDESR2U=", + "dev": true + } + } + }, + "engine.io-parser": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-1.3.2.tgz", + "integrity": "sha1-k3sHnwAH0Ik+xW1GyyILjLQ1Igo=", + "dev": true, + "requires": { + "after": "0.8.2", + "arraybuffer.slice": "0.0.6", + "base64-arraybuffer": "0.1.5", + "blob": "0.0.4", + "has-binary": "0.1.7", + "wtf-8": "1.0.0" + } + }, + "enhanced-resolve": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-4.1.0.tgz", + "integrity": "sha512-F/7vkyTtyc/llOIn8oWclcB25KdRaiPBpZYDgJHgh/UHtpgT2p2eldQgtQnLtUvfMKPKxbRaQM/hHkvLHt1Vng==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "memory-fs": "^0.4.0", + "tapable": "^1.0.0" + } + }, + "ent": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/ent/-/ent-2.2.0.tgz", + "integrity": "sha1-6WQhkyWiHQX0RGai9obtbOX13R0=", + "dev": true + }, + "entities": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-1.1.1.tgz", + "integrity": "sha1-blwtClYhtdra7O+AuQ7ftc13cvA=", + "dev": true + }, + "errno": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/errno/-/errno-0.1.7.tgz", + "integrity": "sha512-MfrRBDWzIWifgq6tJj60gkAwtLNb6sQPlcFrSOflcP1aFmmruKQ2wRnze/8V6kgyz7H3FF8Npzv78mZ7XLLflg==", + "dev": true, + "requires": { + "prr": "~1.0.1" + } + }, + "error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, + "requires": { + "is-arrayish": "^0.2.1" + } + }, + "es-abstract": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.12.0.tgz", + "integrity": "sha512-C8Fx/0jFmV5IPoMOFPA9P9G5NtqW+4cOPit3MIuvR2t7Ag2K15EJTpxnHAYTzL+aYQJIESYeXZmDBfOBE1HcpA==", + "dev": true, + "requires": { + "es-to-primitive": "^1.1.1", + "function-bind": "^1.1.1", + "has": "^1.0.1", + "is-callable": "^1.1.3", + "is-regex": "^1.0.4" + } + }, + "es-to-primitive": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.1.1.tgz", + "integrity": "sha1-RTVSSKiJeQNLZ5Lhm7gfK3l13Q0=", + "dev": true, + "requires": { + "is-callable": "^1.1.1", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.1" + } + }, + "es5-ext": { + "version": "0.10.45", + "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.45.tgz", + "integrity": "sha512-FkfM6Vxxfmztilbxxz5UKSD4ICMf5tSpRFtDNtkAhOxZ0EKtX6qwmXNyH/sFyIbX2P/nU5AMiA9jilWsUGJzCQ==", + "dev": true, + "requires": { + "es6-iterator": "~2.0.3", + "es6-symbol": "~3.1.1", + "next-tick": "1" + } + }, + "es6-iterator": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz", + "integrity": "sha1-p96IkUGgWpSwhUQDstCg+/qY87c=", + "dev": true, + "requires": { + "d": "1", + "es5-ext": "^0.10.35", + "es6-symbol": "^3.1.1" + } + }, + "es6-promise": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.4.tgz", + "integrity": "sha512-/NdNZVJg+uZgtm9eS3O6lrOLYmQag2DjdEXuPaHlZ6RuVqgqaVZfgYCepEIKsLqwdQArOPtC3XzRLqGGfT8KQQ==", + "dev": true + }, + "es6-promisify": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/es6-promisify/-/es6-promisify-5.0.0.tgz", + "integrity": "sha1-UQnWLz5W6pZ8S2NQWu8IKRyKUgM=", + "dev": true, + "requires": { + "es6-promise": "^4.0.3" + } + }, + "es6-symbol": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.1.tgz", + "integrity": "sha1-vwDvT9q2uhtG7Le2KbTH7VcVzHc=", + "dev": true, + "requires": { + "d": "1", + "es5-ext": "~0.10.14" + } + }, + "escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=", + "dev": true + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "escodegen": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.8.1.tgz", + "integrity": "sha1-WltTr0aTEQvrsIZ6o0MN07cKEBg=", + "dev": true, + "requires": { + "esprima": "^2.7.1", + "estraverse": "^1.9.1", + "esutils": "^2.0.2", + "optionator": "^0.8.1", + "source-map": "~0.2.0" + }, + "dependencies": { + "source-map": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.2.0.tgz", + "integrity": "sha1-2rc/vPwrqBm03gO9b26qSBZLP50=", + "dev": true, + "optional": true, + "requires": { + "amdefine": ">=0.0.4" + } + } + } + }, + "eslint-scope": { + "version": "3.7.3", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-3.7.3.tgz", + "integrity": "sha512-W+B0SvF4gamyCTmUc+uITPY0989iXVfKvhwtmJocTaYoc/3khEHmEmvfY/Gn9HA9VV75jrQECsHizkNw1b68FA==", + "dev": true, + "requires": { + "esrecurse": "^4.1.0", + "estraverse": "^4.1.1" + }, + "dependencies": { + "estraverse": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", + "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=", + "dev": true + } + } + }, + "esprima": { + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-2.7.3.tgz", + "integrity": "sha1-luO3DVd59q1JzQMmc9HDEnZ7pYE=", + "dev": true + }, + "esrecurse": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.1.tgz", + "integrity": "sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ==", + "dev": true, + "requires": { + "estraverse": "^4.1.0" + }, + "dependencies": { + "estraverse": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", + "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=", + "dev": true + } + } + }, + "estraverse": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-1.9.3.tgz", + "integrity": "sha1-r2fy3JIlgkFZUJJgkaQAXSnJu0Q=", + "dev": true + }, + "esutils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", + "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", + "dev": true + }, + "etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=", + "dev": true + }, + "eventemitter3": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-3.1.0.tgz", + "integrity": "sha512-ivIvhpq/Y0uSjcHDcOIccjmYjGLcP09MFGE7ysAwkAvkXfpZlC985pH2/ui64DKazbTW/4kN3yqozUxlXzI6cA==", + "dev": true + }, + "events": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/events/-/events-1.1.1.tgz", + "integrity": "sha1-nr23Y1rQmccNzEwqH1AEKI6L2SQ=", + "dev": true + }, + "eventsource": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-0.1.6.tgz", + "integrity": "sha1-Cs7ehJ7X3RzMMsgRuxG5RNTykjI=", + "dev": true, + "requires": { + "original": ">=0.0.5" + } + }, + "evp_bytestokey": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz", + "integrity": "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA==", + "dev": true, + "requires": { + "md5.js": "^1.3.4", + "safe-buffer": "^5.1.1" + } + }, + "execa": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-0.7.0.tgz", + "integrity": "sha1-lEvs00zEHuMqY6n68nrVpl/Fl3c=", + "dev": true, + "requires": { + "cross-spawn": "^5.0.1", + "get-stream": "^3.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" + }, + "dependencies": { + "cross-spawn": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-5.1.0.tgz", + "integrity": "sha1-6L0O/uWPz/b4+UUQoKVUu/ojVEk=", + "dev": true, + "requires": { + "lru-cache": "^4.0.1", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + } + } + }, + "exit": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", + "integrity": "sha1-BjJjj42HfMghB9MKD/8aF8uhzQw=", + "dev": true + }, + "expand-braces": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/expand-braces/-/expand-braces-0.1.2.tgz", + "integrity": "sha1-SIsdHSRRyz06axks/AMPRMWFX+o=", + "dev": true, + "requires": { + "array-slice": "^0.2.3", + "array-unique": "^0.2.1", + "braces": "^0.1.2" + }, + "dependencies": { + "array-unique": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.2.1.tgz", + "integrity": "sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=", + "dev": true + }, + "braces": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/braces/-/braces-0.1.5.tgz", + "integrity": "sha1-wIVxEIUpHYt1/ddOqw+FlygHEeY=", + "dev": true, + "requires": { + "expand-range": "^0.1.0" + } + }, + "expand-range": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/expand-range/-/expand-range-0.1.1.tgz", + "integrity": "sha1-TLjtoJk8pW+k9B/ELzy7TMrf8EQ=", + "dev": true, + "requires": { + "is-number": "^0.1.1", + "repeat-string": "^0.2.2" + } + }, + "is-number": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-0.1.1.tgz", + "integrity": "sha1-aaevEWlj1HIG7JvZtIoUIW8eOAY=", + "dev": true + }, + "repeat-string": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-0.2.2.tgz", + "integrity": "sha1-x6jTI2BoNiBZp+RlH8aITosftK4=", + "dev": true + } + } + }, + "expand-brackets": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz", + "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=", + "dev": true, + "requires": { + "debug": "^2.3.3", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "posix-character-classes": "^0.1.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "expand-range": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/expand-range/-/expand-range-1.8.2.tgz", + "integrity": "sha1-opnv/TNf4nIeuujiV+x5ZE/IUzc=", + "dev": true, + "requires": { + "fill-range": "^2.1.0" + }, + "dependencies": { + "fill-range": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-2.2.4.tgz", + "integrity": "sha512-cnrcCbj01+j2gTG921VZPnHbjmdAf8oQV/iGeV2kZxGSyfYjjTyY79ErsK1WJWMpw6DaApEX72binqJE+/d+5Q==", + "dev": true, + "requires": { + "is-number": "^2.1.0", + "isobject": "^2.0.0", + "randomatic": "^3.0.0", + "repeat-element": "^1.1.2", + "repeat-string": "^1.5.2" + } + }, + "is-number": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-2.1.0.tgz", + "integrity": "sha1-Afy7s5NGOlSPL0ZszhbezknbkI8=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + } + }, + "isobject": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", + "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", + "dev": true, + "requires": { + "isarray": "1.0.0" + } + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "express": { + "version": "4.16.3", + "resolved": "https://registry.npmjs.org/express/-/express-4.16.3.tgz", + "integrity": "sha1-avilAjUNsyRuzEvs9rWjTSL37VM=", + "dev": true, + "requires": { + "accepts": "~1.3.5", + "array-flatten": "1.1.1", + "body-parser": "1.18.2", + "content-disposition": "0.5.2", + "content-type": "~1.0.4", + "cookie": "0.3.1", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "~1.1.2", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.1.1", + "fresh": "0.5.2", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "~2.3.0", + "parseurl": "~1.3.2", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.3", + "qs": "6.5.1", + "range-parser": "~1.2.0", + "safe-buffer": "5.1.1", + "send": "0.16.2", + "serve-static": "1.13.2", + "setprototypeof": "1.1.0", + "statuses": "~1.4.0", + "type-is": "~1.6.16", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "dependencies": { + "array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=", + "dev": true + }, + "qs": { + "version": "6.5.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.1.tgz", + "integrity": "sha512-eRzhrN1WSINYCDCbrz796z37LOe3m5tmW7RQf6oBntukAG1nmovJvhnwHHRMAfeoItc1m2Hk02WER2aQ/iqs+A==", + "dev": true + }, + "safe-buffer": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", + "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==", + "dev": true + } + } + }, + "extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "dev": true + }, + "extend-shallow": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-3.0.2.tgz", + "integrity": "sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=", + "dev": true, + "requires": { + "assign-symbols": "^1.0.0", + "is-extendable": "^1.0.1" + }, + "dependencies": { + "is-extendable": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", + "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", + "dev": true, + "requires": { + "is-plain-object": "^2.0.4" + } + } + } + }, + "extglob": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz", + "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==", + "dev": true, + "requires": { + "array-unique": "^0.3.2", + "define-property": "^1.0.0", + "expand-brackets": "^2.1.4", + "extend-shallow": "^2.0.1", + "fragment-cache": "^0.2.1", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "extsprintf": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", + "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=", + "dev": true + }, + "fast-deep-equal": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-1.1.0.tgz", + "integrity": "sha1-wFNHeBfIa1HaqFPIHgWbcz0CNhQ=", + "dev": true + }, + "fast-json-stable-stringify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz", + "integrity": "sha1-1RQsDK7msRifh9OnYREGT4bIu/I=", + "dev": true + }, + "fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "dev": true + }, + "fastparse": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/fastparse/-/fastparse-1.1.1.tgz", + "integrity": "sha1-0eJkOzipTXWDtHkGDmxK/8lAcfg=", + "dev": true + }, + "faye-websocket": { + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.10.0.tgz", + "integrity": "sha1-TkkvjQTftviQA1B/btvy1QHnxvQ=", + "dev": true, + "requires": { + "websocket-driver": ">=0.5.1" + } + }, + "file-loader": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/file-loader/-/file-loader-1.1.11.tgz", + "integrity": "sha512-TGR4HU7HUsGg6GCOPJnFk06RhWgEWFLAGWiT6rcD+GRC2keU3s9RGJ+b3Z6/U73jwwNb2gKLJ7YCrp+jvU4ALg==", + "dev": true, + "requires": { + "loader-utils": "^1.0.2", + "schema-utils": "^0.4.5" + } + }, + "filename-regex": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/filename-regex/-/filename-regex-2.0.1.tgz", + "integrity": "sha1-wcS5vuPglyXdsQa3XB4wH+LxiyY=", + "dev": true + }, + "fileset": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/fileset/-/fileset-2.0.3.tgz", + "integrity": "sha1-jnVIqW08wjJ+5eZ0FocjozO7oqA=", + "dev": true, + "requires": { + "glob": "^7.0.3", + "minimatch": "^3.0.3" + } + }, + "fill-range": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", + "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=", + "dev": true, + "requires": { + "extend-shallow": "^2.0.1", + "is-number": "^3.0.0", + "repeat-string": "^1.6.1", + "to-regex-range": "^2.1.0" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "finalhandler": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.1.tgz", + "integrity": "sha512-Y1GUDo39ez4aHAw7MysnUD5JzYX+WaIj8I57kO3aEPT1fFRL4sr7mjei97FgnwhAyyzRYmQZaTHb2+9uZ1dPtg==", + "dev": true, + "requires": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "parseurl": "~1.3.2", + "statuses": "~1.4.0", + "unpipe": "~1.0.0" + } + }, + "find-cache-dir": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-1.0.0.tgz", + "integrity": "sha1-kojj6ePMN0hxfTnq3hfPcfww7m8=", + "dev": true, + "requires": { + "commondir": "^1.0.1", + "make-dir": "^1.0.0", + "pkg-dir": "^2.0.0" + } + }, + "find-up": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", + "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", + "dev": true, + "requires": { + "locate-path": "^2.0.0" + } + }, + "flush-write-stream": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/flush-write-stream/-/flush-write-stream-1.0.3.tgz", + "integrity": "sha512-calZMC10u0FMUqoiunI2AiGIIUtUIvifNwkHhNupZH4cbNnW1Itkoh/Nf5HFYmDrwWPjrUxpkZT0KhuCq0jmGw==", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.4" + } + }, + "follow-redirects": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.5.1.tgz", + "integrity": "sha512-v9GI1hpaqq1ZZR6pBD1+kI7O24PhDvNGNodjS3MdcEqyrahCp8zbtpv+2B/krUnSmUH80lbAS7MrdeK5IylgKg==", + "dev": true, + "requires": { + "debug": "^3.1.0" + }, + "dependencies": { + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + } + } + }, + "for-in": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", + "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=", + "dev": true + }, + "for-own": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/for-own/-/for-own-1.0.0.tgz", + "integrity": "sha1-xjMy9BXO3EsE2/5wz4NklMU8tEs=", + "dev": true, + "requires": { + "for-in": "^1.0.1" + } + }, + "foreach": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/foreach/-/foreach-2.0.5.tgz", + "integrity": "sha1-C+4AUBiusmDQo6865ljdATbsG5k=", + "dev": true + }, + "forever-agent": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", + "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=", + "dev": true + }, + "form-data": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.2.tgz", + "integrity": "sha1-SXBJi+YEwgwAXU9cI67NIda0kJk=", + "dev": true, + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "1.0.6", + "mime-types": "^2.1.12" + } + }, + "forwarded": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz", + "integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ=", + "dev": true + }, + "fragment-cache": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", + "integrity": "sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=", + "dev": true, + "requires": { + "map-cache": "^0.2.2" + } + }, + "fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=", + "dev": true + }, + "from2": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/from2/-/from2-2.3.0.tgz", + "integrity": "sha1-i/tVAr3kpNNs/e6gB/zKIdfjgq8=", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.0" + } + }, + "fs-access": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/fs-access/-/fs-access-1.0.1.tgz", + "integrity": "sha1-1qh/JiJxzv6+wwxVNAf7mV2od3o=", + "dev": true, + "requires": { + "null-check": "^1.0.0" + } + }, + "fs-write-stream-atomic": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/fs-write-stream-atomic/-/fs-write-stream-atomic-1.0.10.tgz", + "integrity": "sha1-tH31NJPvkR33VzHnCp3tAYnbQMk=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "iferr": "^0.1.5", + "imurmurhash": "^0.1.4", + "readable-stream": "1 || 2" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "fsevents": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.4.tgz", + "integrity": "sha512-z8H8/diyk76B7q5wg+Ud0+CqzcAF3mBBI/bA5ne5zrRUUIvNkJY//D3BqyH571KuAC4Nr7Rw7CjWX4r0y9DvNg==", + "dev": true, + "optional": true, + "requires": { + "nan": "^2.9.2", + "node-pre-gyp": "^0.10.0" + }, + "dependencies": { + "abbrev": { + "version": "1.1.1", + "bundled": true, + "dev": true, + "optional": true + }, + "ansi-regex": { + "version": "2.1.1", + "bundled": true, + "dev": true + }, + "aproba": { + "version": "1.2.0", + "bundled": true, + "dev": true, + "optional": true + }, + "are-we-there-yet": { + "version": "1.1.4", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "delegates": "^1.0.0", + "readable-stream": "^2.0.6" + } + }, + "balanced-match": { + "version": "1.0.0", + "bundled": true, + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "bundled": true, + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "chownr": { + "version": "1.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "code-point-at": { + "version": "1.1.0", + "bundled": true, + "dev": true + }, + "concat-map": { + "version": "0.0.1", + "bundled": true, + "dev": true + }, + "console-control-strings": { + "version": "1.1.0", + "bundled": true, + "dev": true + }, + "core-util-is": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "debug": { + "version": "2.6.9", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "ms": "2.0.0" + } + }, + "deep-extend": { + "version": "0.5.1", + "bundled": true, + "dev": true, + "optional": true + }, + "delegates": { + "version": "1.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "detect-libc": { + "version": "1.0.3", + "bundled": true, + "dev": true, + "optional": true + }, + "fs-minipass": { + "version": "1.2.5", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "minipass": "^2.2.1" + } + }, + "fs.realpath": { + "version": "1.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "gauge": { + "version": "2.7.4", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "aproba": "^1.0.3", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.0", + "object-assign": "^4.1.0", + "signal-exit": "^3.0.0", + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wide-align": "^1.1.0" + } + }, + "glob": { + "version": "7.1.2", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "has-unicode": { + "version": "2.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "iconv-lite": { + "version": "0.4.21", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "safer-buffer": "^2.1.0" + } + }, + "ignore-walk": { + "version": "3.0.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "minimatch": "^3.0.4" + } + }, + "inflight": { + "version": "1.0.6", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.3", + "bundled": true, + "dev": true + }, + "ini": { + "version": "1.3.5", + "bundled": true, + "dev": true, + "optional": true + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "bundled": true, + "dev": true, + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "isarray": { + "version": "1.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "minimatch": { + "version": "3.0.4", + "bundled": true, + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.8", + "bundled": true, + "dev": true + }, + "minipass": { + "version": "2.2.4", + "bundled": true, + "dev": true, + "requires": { + "safe-buffer": "^5.1.1", + "yallist": "^3.0.0" + } + }, + "minizlib": { + "version": "1.1.0", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "minipass": "^2.2.1" + } + }, + "mkdirp": { + "version": "0.5.1", + "bundled": true, + "dev": true, + "requires": { + "minimist": "0.0.8" + } + }, + "ms": { + "version": "2.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "needle": { + "version": "2.2.0", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "debug": "^2.1.2", + "iconv-lite": "^0.4.4", + "sax": "^1.2.4" + } + }, + "node-pre-gyp": { + "version": "0.10.0", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "detect-libc": "^1.0.2", + "mkdirp": "^0.5.1", + "needle": "^2.2.0", + "nopt": "^4.0.1", + "npm-packlist": "^1.1.6", + "npmlog": "^4.0.2", + "rc": "^1.1.7", + "rimraf": "^2.6.1", + "semver": "^5.3.0", + "tar": "^4" + } + }, + "nopt": { + "version": "4.0.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "abbrev": "1", + "osenv": "^0.1.4" + } + }, + "npm-bundled": { + "version": "1.0.3", + "bundled": true, + "dev": true, + "optional": true + }, + "npm-packlist": { + "version": "1.1.10", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "ignore-walk": "^3.0.1", + "npm-bundled": "^1.0.1" + } + }, + "npmlog": { + "version": "4.1.2", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "are-we-there-yet": "~1.1.2", + "console-control-strings": "~1.1.0", + "gauge": "~2.7.3", + "set-blocking": "~2.0.0" + } + }, + "number-is-nan": { + "version": "1.0.1", + "bundled": true, + "dev": true + }, + "object-assign": { + "version": "4.1.1", + "bundled": true, + "dev": true, + "optional": true + }, + "once": { + "version": "1.4.0", + "bundled": true, + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "os-homedir": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "os-tmpdir": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "osenv": { + "version": "0.1.5", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "os-homedir": "^1.0.0", + "os-tmpdir": "^1.0.0" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "process-nextick-args": { + "version": "2.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "rc": { + "version": "1.2.7", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "deep-extend": "^0.5.1", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "bundled": true, + "dev": true, + "optional": true + } + } + }, + "readable-stream": { + "version": "2.3.6", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "rimraf": { + "version": "2.6.2", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "glob": "^7.0.5" + } + }, + "safe-buffer": { + "version": "5.1.1", + "bundled": true, + "dev": true + }, + "safer-buffer": { + "version": "2.1.2", + "bundled": true, + "dev": true, + "optional": true + }, + "sax": { + "version": "1.2.4", + "bundled": true, + "dev": true, + "optional": true + }, + "semver": { + "version": "5.5.0", + "bundled": true, + "dev": true, + "optional": true + }, + "set-blocking": { + "version": "2.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "signal-exit": { + "version": "3.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "string-width": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + }, + "string_decoder": { + "version": "1.1.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "bundled": true, + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "strip-json-comments": { + "version": "2.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "tar": { + "version": "4.4.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "chownr": "^1.0.1", + "fs-minipass": "^1.2.5", + "minipass": "^2.2.4", + "minizlib": "^1.1.0", + "mkdirp": "^0.5.0", + "safe-buffer": "^5.1.1", + "yallist": "^3.0.2" + } + }, + "util-deprecate": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "wide-align": { + "version": "1.1.2", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "string-width": "^1.0.2" + } + }, + "wrappy": { + "version": "1.0.2", + "bundled": true, + "dev": true + }, + "yallist": { + "version": "3.0.2", + "bundled": true, + "dev": true + } + } + }, + "fstream": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.11.tgz", + "integrity": "sha1-XB+x8RdHcRTwYyoOtLcbPLD9MXE=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "inherits": "~2.0.0", + "mkdirp": ">=0.5 0", + "rimraf": "2" + } + }, + "function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "dev": true + }, + "gauge": { + "version": "2.7.4", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-2.7.4.tgz", + "integrity": "sha1-LANAXHU4w51+s3sxcCLjJfsBi/c=", + "dev": true, + "requires": { + "aproba": "^1.0.3", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.0", + "object-assign": "^4.1.0", + "signal-exit": "^3.0.0", + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wide-align": "^1.1.0" + } + }, + "gaze": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/gaze/-/gaze-1.1.3.tgz", + "integrity": "sha512-BRdNm8hbWzFzWHERTrejLqwHDfS4GibPoq5wjTPIoJHoBtKGPg3xAFfxmM+9ztbXelxcf2hwQcaz1PtmFeue8g==", + "dev": true, + "optional": true, + "requires": { + "globule": "^1.0.0" + } + }, + "get-caller-file": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-1.0.3.tgz", + "integrity": "sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w==", + "dev": true + }, + "get-stdin": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz", + "integrity": "sha1-uWjGsKBDhDJJAui/Gl3zJXmkUP4=", + "dev": true + }, + "get-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-3.0.0.tgz", + "integrity": "sha1-jpQ9E1jcN1VQVOy+LtsFqhdO3hQ=", + "dev": true + }, + "get-value": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz", + "integrity": "sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=", + "dev": true + }, + "getpass": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", + "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", + "dev": true, + "requires": { + "assert-plus": "^1.0.0" + } + }, + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "glob-base": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/glob-base/-/glob-base-0.3.0.tgz", + "integrity": "sha1-27Fk9iIbHAscz4Kuoyi0l98Oo8Q=", + "dev": true, + "requires": { + "glob-parent": "^2.0.0", + "is-glob": "^2.0.0" + }, + "dependencies": { + "glob-parent": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-2.0.0.tgz", + "integrity": "sha1-gTg9ctsFT8zPUzbaqQLxgvbtuyg=", + "dev": true, + "requires": { + "is-glob": "^2.0.0" + } + }, + "is-extglob": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-1.0.0.tgz", + "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=", + "dev": true + }, + "is-glob": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-2.0.1.tgz", + "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", + "dev": true, + "requires": { + "is-extglob": "^1.0.0" + } + } + } + }, + "glob-parent": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-3.1.0.tgz", + "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", + "dev": true, + "requires": { + "is-glob": "^3.1.0", + "path-dirname": "^1.0.0" + }, + "dependencies": { + "is-glob": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", + "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", + "dev": true, + "requires": { + "is-extglob": "^2.1.0" + } + } + } + }, + "globals": { + "version": "9.18.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-9.18.0.tgz", + "integrity": "sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ==", + "dev": true + }, + "globby": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/globby/-/globby-7.1.1.tgz", + "integrity": "sha1-+yzP+UAfhgCUXfral0QMypcrhoA=", + "dev": true, + "requires": { + "array-union": "^1.0.1", + "dir-glob": "^2.0.0", + "glob": "^7.1.2", + "ignore": "^3.3.5", + "pify": "^3.0.0", + "slash": "^1.0.0" + } + }, + "globule": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/globule/-/globule-1.2.1.tgz", + "integrity": "sha512-g7QtgWF4uYSL5/dn71WxubOrS7JVGCnFPEnoeChJmBnyR9Mw8nGoEwOgJL/RC2Te0WhbsEUCejfH8SZNJ+adYQ==", + "dev": true, + "optional": true, + "requires": { + "glob": "~7.1.1", + "lodash": "~4.17.10", + "minimatch": "~3.0.2" + } + }, + "graceful-fs": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", + "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", + "dev": true + }, + "handle-thing": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/handle-thing/-/handle-thing-1.2.5.tgz", + "integrity": "sha1-/Xqtcmvxpf0W38KbL3pmAdJxOcQ=", + "dev": true + }, + "handlebars": { + "version": "4.0.11", + "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.0.11.tgz", + "integrity": "sha1-Ywo13+ApS8KB7a5v/F0yn8eYLcw=", + "dev": true, + "requires": { + "async": "^1.4.0", + "optimist": "^0.6.1", + "source-map": "^0.4.4", + "uglify-js": "^2.6" + }, + "dependencies": { + "source-map": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.4.4.tgz", + "integrity": "sha1-66T12pwNyZneaAMti092FzZSA2s=", + "dev": true, + "requires": { + "amdefine": ">=0.0.4" + } + }, + "uglify-js": { + "version": "2.8.29", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-2.8.29.tgz", + "integrity": "sha1-KcVzMUgFe7Th913zW3qcty5qWd0=", + "dev": true, + "optional": true, + "requires": { + "source-map": "~0.5.1", + "uglify-to-browserify": "~1.0.0", + "yargs": "~3.10.0" + }, + "dependencies": { + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true, + "optional": true + } + } + } + } + }, + "har-schema": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", + "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=", + "dev": true + }, + "har-validator": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.0.3.tgz", + "integrity": "sha1-ukAsJmGU8VlW7xXg/PJCmT9qff0=", + "dev": true, + "requires": { + "ajv": "^5.1.0", + "har-schema": "^2.0.0" + }, + "dependencies": { + "ajv": { + "version": "5.5.2", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-5.5.2.tgz", + "integrity": "sha1-c7Xuyj+rZT49P5Qis0GtQiBdyWU=", + "dev": true, + "requires": { + "co": "^4.6.0", + "fast-deep-equal": "^1.0.0", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.3.0" + } + } + } + }, + "has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1" + } + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "has-binary": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/has-binary/-/has-binary-0.1.7.tgz", + "integrity": "sha1-aOYesWIQyVRaClzOBqhzkS/h5ow=", + "dev": true, + "requires": { + "isarray": "0.0.1" + }, + "dependencies": { + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", + "dev": true + } + } + }, + "has-cors": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-cors/-/has-cors-1.1.0.tgz", + "integrity": "sha1-XkdHk/fqmEPRu5nCPu9J/xJv/zk=", + "dev": true + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true + }, + "has-symbols": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.0.tgz", + "integrity": "sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q=", + "dev": true + }, + "has-unicode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", + "integrity": "sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=", + "dev": true + }, + "has-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz", + "integrity": "sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=", + "dev": true, + "requires": { + "get-value": "^2.0.6", + "has-values": "^1.0.0", + "isobject": "^3.0.0" + } + }, + "has-values": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-values/-/has-values-1.0.0.tgz", + "integrity": "sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=", + "dev": true, + "requires": { + "is-number": "^3.0.0", + "kind-of": "^4.0.0" + }, + "dependencies": { + "kind-of": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-4.0.0.tgz", + "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "hash-base": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-3.0.4.tgz", + "integrity": "sha1-X8hoaEfs1zSZQDMZprCj8/auSRg=", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "hash.js": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.5.tgz", + "integrity": "sha512-eWI5HG9Np+eHV1KQhisXWwM+4EPPYe5dFX1UZZH7k/E3JzDEazVH+VGlZi6R94ZqImq+A3D1mCEtrFIfg/E7sA==", + "dev": true, + "requires": { + "inherits": "^2.0.3", + "minimalistic-assert": "^1.0.1" + } + }, + "hawk": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/hawk/-/hawk-3.1.3.tgz", + "integrity": "sha1-B4REvXwWQLD+VA0sm3PVlnjo4cQ=", + "dev": true, + "optional": true, + "requires": { + "boom": "2.x.x", + "cryptiles": "2.x.x", + "hoek": "2.x.x", + "sntp": "1.x.x" + } + }, + "he": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/he/-/he-1.1.1.tgz", + "integrity": "sha1-k0EP0hsAlzUVH4howvJx80J+I/0=", + "dev": true + }, + "hmac-drbg": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz", + "integrity": "sha1-0nRXAQJabHdabFRXk+1QL8DGSaE=", + "dev": true, + "requires": { + "hash.js": "^1.0.3", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.1" + } + }, + "hoek": { + "version": "2.16.3", + "resolved": "https://registry.npmjs.org/hoek/-/hoek-2.16.3.tgz", + "integrity": "sha1-ILt0A9POo5jpHcRxCo/xuCdKJe0=", + "dev": true + }, + "hosted-git-info": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.7.1.tgz", + "integrity": "sha512-7T/BxH19zbcCTa8XkMlbK5lTo1WtgkFi3GvdWEyNuc4Vex7/9Dqbnpsf4JMydcfj9HCg4zUWFTL3Za6lapg5/w==", + "dev": true + }, + "hpack.js": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/hpack.js/-/hpack.js-2.1.6.tgz", + "integrity": "sha1-h3dMCUnlE/QuhFdbPEVoH63ioLI=", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "obuf": "^1.0.0", + "readable-stream": "^2.0.1", + "wbuf": "^1.1.0" + } + }, + "html-entities": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/html-entities/-/html-entities-1.2.1.tgz", + "integrity": "sha1-DfKTUfByEWNRXfueVUPl9u7VFi8=", + "dev": true + }, + "html-minifier": { + "version": "3.5.19", + "resolved": "https://registry.npmjs.org/html-minifier/-/html-minifier-3.5.19.tgz", + "integrity": "sha512-Qr2JC9nsjK8oCrEmuB430ZIA8YWbF3D5LSjywD75FTuXmeqacwHgIM8wp3vHYzzPbklSjp53RdmDuzR4ub2HzA==", + "dev": true, + "requires": { + "camel-case": "3.0.x", + "clean-css": "4.1.x", + "commander": "2.16.x", + "he": "1.1.x", + "param-case": "2.1.x", + "relateurl": "0.2.x", + "uglify-js": "3.4.x" + } + }, + "html-webpack-plugin": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/html-webpack-plugin/-/html-webpack-plugin-3.2.0.tgz", + "integrity": "sha1-sBq71yOsqqeze2r0SS69oD2d03s=", + "dev": true, + "requires": { + "html-minifier": "^3.2.3", + "loader-utils": "^0.2.16", + "lodash": "^4.17.3", + "pretty-error": "^2.0.2", + "tapable": "^1.0.0", + "toposort": "^1.0.0", + "util.promisify": "1.0.0" + }, + "dependencies": { + "loader-utils": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-0.2.17.tgz", + "integrity": "sha1-+G5jdNQyBabmxg6RlvF8Apm/s0g=", + "dev": true, + "requires": { + "big.js": "^3.1.3", + "emojis-list": "^2.0.0", + "json5": "^0.5.0", + "object-assign": "^4.0.1" + } + } + } + }, + "htmlparser2": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.3.0.tgz", + "integrity": "sha1-zHDQWln2VC5D8OaFyYLhTJJKnv4=", + "dev": true, + "requires": { + "domelementtype": "1", + "domhandler": "2.1", + "domutils": "1.1", + "readable-stream": "1.0" + }, + "dependencies": { + "domutils": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.1.6.tgz", + "integrity": "sha1-vdw94Jm5ou+sxRxiPyj0FuzFdIU=", + "dev": true, + "requires": { + "domelementtype": "1" + } + }, + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", + "dev": true + }, + "readable-stream": { + "version": "1.0.34", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", + "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", + "dev": true + } + } + }, + "http-deceiver": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/http-deceiver/-/http-deceiver-1.2.7.tgz", + "integrity": "sha1-+nFolEq5pRnTN8sL7HKE3D5yPYc=", + "dev": true + }, + "http-errors": { + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.3.tgz", + "integrity": "sha1-i1VoC7S+KDoLW/TqLjhYC+HZMg0=", + "dev": true, + "requires": { + "depd": "~1.1.2", + "inherits": "2.0.3", + "setprototypeof": "1.1.0", + "statuses": ">= 1.4.0 < 2" + } + }, + "http-parser-js": { + "version": "0.4.13", + "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.4.13.tgz", + "integrity": "sha1-O9bW/ebjFyyTNMOzO2wZPYD+ETc=", + "dev": true + }, + "http-proxy": { + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.17.0.tgz", + "integrity": "sha512-Taqn+3nNvYRfJ3bGvKfBSRwy1v6eePlm3oc/aWVxZp57DQr5Eq3xhKJi7Z4hZpS8PC3H4qI+Yly5EmFacGuA/g==", + "dev": true, + "requires": { + "eventemitter3": "^3.0.0", + "follow-redirects": "^1.0.0", + "requires-port": "^1.0.0" + } + }, + "http-proxy-middleware": { + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-0.18.0.tgz", + "integrity": "sha512-Fs25KVMPAIIcgjMZkVHJoKg9VcXcC1C8yb9JUgeDvVXY0S/zgVIhMb+qVswDIgtJe2DfckMSY2d6TuTEutlk6Q==", + "dev": true, + "requires": { + "http-proxy": "^1.16.2", + "is-glob": "^4.0.0", + "lodash": "^4.17.5", + "micromatch": "^3.1.9" + } + }, + "http-signature": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", + "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", + "dev": true, + "requires": { + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" + } + }, + "https-browserify": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/https-browserify/-/https-browserify-1.0.0.tgz", + "integrity": "sha1-7AbBDgo0wPL68Zn3/X/Hj//QPHM=", + "dev": true + }, + "https-proxy-agent": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-2.2.1.tgz", + "integrity": "sha512-HPCTS1LW51bcyMYbxUIOO4HEOlQ1/1qRaFWcyxvwaqUS9TY88aoEuHUY33kuAh1YhVVaDQhLZsnPd+XNARWZlQ==", + "dev": true, + "requires": { + "agent-base": "^4.1.0", + "debug": "^3.1.0" + }, + "dependencies": { + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + } + } + }, + "iconv-lite": { + "version": "0.4.19", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.19.tgz", + "integrity": "sha512-oTZqweIP51xaGPI4uPa56/Pri/480R+mo7SeU+YETByQNhDG55ycFyNLIgta9vXhILrxXDmF7ZGhqZIcuN0gJQ==", + "dev": true + }, + "ieee754": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.12.tgz", + "integrity": "sha512-GguP+DRY+pJ3soyIiGPTvdiVXjZ+DbXOxGpXn3eMvNW4x4irjqXm4wHKscC+TfxSJ0yw/S1F24tqdMNsMZTiLA==", + "dev": true + }, + "iferr": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/iferr/-/iferr-0.1.5.tgz", + "integrity": "sha1-xg7taebY/bazEEofy8ocGS3FtQE=", + "dev": true + }, + "ignore": { + "version": "3.3.10", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-3.3.10.tgz", + "integrity": "sha512-Pgs951kaMm5GXP7MOvxERINe3gsaVjUWFm+UZPSq9xYriQAksyhg0csnS0KXSNRD5NmNdapXEpjxG49+AKh/ug==", + "dev": true + }, + "image-size": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/image-size/-/image-size-0.5.5.tgz", + "integrity": "sha1-Cd/Uq50g4p6xw+gLiZA3jfnjy5w=", + "dev": true, + "optional": true + }, + "immediate": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", + "integrity": "sha1-nbHb0Pr43m++D13V5Wu2BigN5ps=", + "dev": true + }, + "import-cwd": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/import-cwd/-/import-cwd-2.1.0.tgz", + "integrity": "sha1-qmzzbnInYShcs3HsZRn1PiQ1sKk=", + "dev": true, + "requires": { + "import-from": "^2.1.0" + } + }, + "import-from": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/import-from/-/import-from-2.1.0.tgz", + "integrity": "sha1-M1238qev/VOqpHHUuAId7ja387E=", + "dev": true, + "requires": { + "resolve-from": "^3.0.0" + } + }, + "import-local": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-1.0.0.tgz", + "integrity": "sha512-vAaZHieK9qjGo58agRBg+bhHX3hoTZU/Oa3GESWLz7t1U62fk63aHuDJJEteXoDeTCcPmUT+z38gkHPZkkmpmQ==", + "dev": true, + "requires": { + "pkg-dir": "^2.0.0", + "resolve-cwd": "^2.0.0" + } + }, + "imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", + "dev": true + }, + "in-publish": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/in-publish/-/in-publish-2.0.0.tgz", + "integrity": "sha1-4g/146KvwmkDILbcVSaCqcf631E=", + "dev": true, + "optional": true + }, + "indent-string": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-2.1.0.tgz", + "integrity": "sha1-ji1INIdCEhtKghi3oTfppSBJ3IA=", + "dev": true, + "requires": { + "repeating": "^2.0.0" + } + }, + "indexof": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/indexof/-/indexof-0.0.1.tgz", + "integrity": "sha1-gtwzbSMrkGIXnQWrMpOmYFn9Q10=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "ini": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.5.tgz", + "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==", + "dev": true + }, + "internal-ip": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/internal-ip/-/internal-ip-1.2.0.tgz", + "integrity": "sha1-rp+/k7mEh4eF1QqN4bNWlWBYz1w=", + "dev": true, + "requires": { + "meow": "^3.3.0" + } + }, + "invariant": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz", + "integrity": "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==", + "dev": true, + "requires": { + "loose-envify": "^1.0.0" + } + }, + "invert-kv": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-1.0.0.tgz", + "integrity": "sha1-EEqOSqym09jNFXqO+L+rLXo//bY=", + "dev": true + }, + "ip": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/ip/-/ip-1.1.5.tgz", + "integrity": "sha1-vd7XARQpCCjAoDnnLvJfWq7ENUo=", + "dev": true + }, + "ipaddr.js": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.6.0.tgz", + "integrity": "sha1-4/o1e3c9phnybpXwSdBVxyeW+Gs=", + "dev": true + }, + "is-accessor-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", + "dev": true + }, + "is-binary-path": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-1.0.1.tgz", + "integrity": "sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg=", + "dev": true, + "requires": { + "binary-extensions": "^1.0.0" + } + }, + "is-buffer": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", + "dev": true + }, + "is-builtin-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-builtin-module/-/is-builtin-module-1.0.0.tgz", + "integrity": "sha1-VAVy0096wxGfj3bDDLwbHgN6/74=", + "dev": true, + "requires": { + "builtin-modules": "^1.0.0" + } + }, + "is-callable": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.4.tgz", + "integrity": "sha512-r5p9sxJjYnArLjObpjA4xu5EKI3CuKHkJXMhT7kwbpUyIFD1n5PMAsoPvWnvtZiNz7LjkYDRZhd7FlI0eMijEA==", + "dev": true + }, + "is-data-descriptor": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-date-object": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.1.tgz", + "integrity": "sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY=", + "dev": true + }, + "is-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", + "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^0.1.6", + "is-data-descriptor": "^0.1.4", + "kind-of": "^5.0.0" + }, + "dependencies": { + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } + } + }, + "is-directory": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/is-directory/-/is-directory-0.3.1.tgz", + "integrity": "sha1-YTObbyR1/Hcv2cnYP1yFddwVSuE=", + "dev": true + }, + "is-dotfile": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/is-dotfile/-/is-dotfile-1.0.3.tgz", + "integrity": "sha1-pqLzL/0t+wT1yiXs0Pa4PPeYoeE=", + "dev": true + }, + "is-equal-shallow": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/is-equal-shallow/-/is-equal-shallow-0.1.3.tgz", + "integrity": "sha1-IjgJj8Ih3gvPpdnqxMRdY4qhxTQ=", + "dev": true, + "requires": { + "is-primitive": "^2.0.0" + } + }, + "is-extendable": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", + "integrity": "sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=", + "dev": true + }, + "is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", + "dev": true + }, + "is-finite": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", + "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", + "dev": true, + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", + "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", + "dev": true, + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "is-glob": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.0.tgz", + "integrity": "sha1-lSHHaEXMJhCoUgPd8ICpWML/q8A=", + "dev": true, + "requires": { + "is-extglob": "^2.1.1" + } + }, + "is-number": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", + "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-path-cwd": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-1.0.0.tgz", + "integrity": "sha1-0iXsIxMuie3Tj9p2dHLmLmXxEG0=", + "dev": true + }, + "is-path-in-cwd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-path-in-cwd/-/is-path-in-cwd-1.0.1.tgz", + "integrity": "sha512-FjV1RTW48E7CWM7eE/J2NJvAEEVektecDBVBE5Hh3nM1Jd0kvhHtX68Pr3xsDf857xt3Y4AkwVULK1Vku62aaQ==", + "dev": true, + "requires": { + "is-path-inside": "^1.0.0" + } + }, + "is-path-inside": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-1.0.1.tgz", + "integrity": "sha1-jvW33lBDej/cprToZe96pVy0gDY=", + "dev": true, + "requires": { + "path-is-inside": "^1.0.1" + } + }, + "is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "dev": true, + "requires": { + "isobject": "^3.0.1" + } + }, + "is-posix-bracket": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-posix-bracket/-/is-posix-bracket-0.1.1.tgz", + "integrity": "sha1-MzTceXdDaOkvAW5vvAqI9c1ua8Q=", + "dev": true + }, + "is-primitive": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-primitive/-/is-primitive-2.0.0.tgz", + "integrity": "sha1-IHurkWOEmcB7Kt8kCkGochADRXU=", + "dev": true + }, + "is-regex": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.4.tgz", + "integrity": "sha1-VRdIm1RwkbCTDglWVM7SXul+lJE=", + "dev": true, + "requires": { + "has": "^1.0.1" + } + }, + "is-stream": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", + "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=", + "dev": true + }, + "is-symbol": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.1.tgz", + "integrity": "sha1-PMWfAAJRlLarLjjbrmaJJWtmBXI=", + "dev": true + }, + "is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", + "dev": true + }, + "is-utf8": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", + "integrity": "sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI=", + "dev": true + }, + "is-windows": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", + "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", + "dev": true + }, + "is-wsl": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-1.1.0.tgz", + "integrity": "sha1-HxbkqiKwTRM2tmGIpmrzxgDDpm0=", + "dev": true + }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "dev": true + }, + "isbinaryfile": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-3.0.2.tgz", + "integrity": "sha1-Sj6XTsDLqQBNP8bN5yCeppNopiE=", + "dev": true + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", + "dev": true + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", + "dev": true + }, + "istanbul": { + "version": "0.4.5", + "resolved": "https://registry.npmjs.org/istanbul/-/istanbul-0.4.5.tgz", + "integrity": "sha1-ZcfXPUxNqE1POsMQuRj7C4Azczs=", + "dev": true, + "requires": { + "abbrev": "1.0.x", + "async": "1.x", + "escodegen": "1.8.x", + "esprima": "2.7.x", + "glob": "^5.0.15", + "handlebars": "^4.0.1", + "js-yaml": "3.x", + "mkdirp": "0.5.x", + "nopt": "3.x", + "once": "1.x", + "resolve": "1.1.x", + "supports-color": "^3.1.0", + "which": "^1.1.1", + "wordwrap": "^1.0.0" + }, + "dependencies": { + "glob": { + "version": "5.0.15", + "resolved": "https://registry.npmjs.org/glob/-/glob-5.0.15.tgz", + "integrity": "sha1-G8k2ueAvSmA/zCIuz3Yz0wuLk7E=", + "dev": true, + "requires": { + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "2 || 3", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=", + "dev": true + }, + "resolve": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.1.7.tgz", + "integrity": "sha1-IDEU2CrSxe2ejgQRs5ModeiJ6Xs=", + "dev": true + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "dev": true, + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "istanbul-api": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/istanbul-api/-/istanbul-api-1.3.1.tgz", + "integrity": "sha512-duj6AlLcsWNwUpfyfHt0nWIeRiZpuShnP40YTxOGQgtaN8fd6JYSxsvxUphTDy8V5MfDXo4s/xVCIIvVCO808g==", + "dev": true, + "requires": { + "async": "^2.1.4", + "compare-versions": "^3.1.0", + "fileset": "^2.0.2", + "istanbul-lib-coverage": "^1.2.0", + "istanbul-lib-hook": "^1.2.0", + "istanbul-lib-instrument": "^1.10.1", + "istanbul-lib-report": "^1.1.4", + "istanbul-lib-source-maps": "^1.2.4", + "istanbul-reports": "^1.3.0", + "js-yaml": "^3.7.0", + "mkdirp": "^0.5.1", + "once": "^1.4.0" + }, + "dependencies": { + "async": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.1.tgz", + "integrity": "sha512-fNEiL2+AZt6AlAw/29Cr0UDe4sRAHCpEHh54WMz+Bb7QfNcFw4h3loofyJpLeQs4Yx7yuqu/2dLgM5hKOs6HlQ==", + "dev": true, + "requires": { + "lodash": "^4.17.10" + } + } + } + }, + "istanbul-instrumenter-loader": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-instrumenter-loader/-/istanbul-instrumenter-loader-3.0.1.tgz", + "integrity": "sha512-a5SPObZgS0jB/ixaKSMdn6n/gXSrK2S6q/UfRJBT3e6gQmVjwZROTODQsYW5ZNwOu78hG62Y3fWlebaVOL0C+w==", + "dev": true, + "requires": { + "convert-source-map": "^1.5.0", + "istanbul-lib-instrument": "^1.7.3", + "loader-utils": "^1.1.0", + "schema-utils": "^0.3.0" + }, + "dependencies": { + "ajv": { + "version": "5.5.2", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-5.5.2.tgz", + "integrity": "sha1-c7Xuyj+rZT49P5Qis0GtQiBdyWU=", + "dev": true, + "requires": { + "co": "^4.6.0", + "fast-deep-equal": "^1.0.0", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.3.0" + } + }, + "schema-utils": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-0.3.0.tgz", + "integrity": "sha1-9YdyIs4+kx7a4DnxfrNxbnE3+M8=", + "dev": true, + "requires": { + "ajv": "^5.0.0" + } + } + } + }, + "istanbul-lib-coverage": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-1.2.0.tgz", + "integrity": "sha512-GvgM/uXRwm+gLlvkWHTjDAvwynZkL9ns15calTrmhGgowlwJBbWMYzWbKqE2DT6JDP1AFXKa+Zi0EkqNCUqY0A==", + "dev": true + }, + "istanbul-lib-hook": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-hook/-/istanbul-lib-hook-1.2.1.tgz", + "integrity": "sha512-eLAMkPG9FU0v5L02lIkcj/2/Zlz9OuluaXikdr5iStk8FDbSwAixTK9TkYxbF0eNnzAJTwM2fkV2A1tpsIp4Jg==", + "dev": true, + "requires": { + "append-transform": "^1.0.0" + } + }, + "istanbul-lib-instrument": { + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-1.10.1.tgz", + "integrity": "sha512-1dYuzkOCbuR5GRJqySuZdsmsNKPL3PTuyPevQfoCXJePT9C8y1ga75neU+Tuy9+yS3G/dgx8wgOmp2KLpgdoeQ==", + "dev": true, + "requires": { + "babel-generator": "^6.18.0", + "babel-template": "^6.16.0", + "babel-traverse": "^6.18.0", + "babel-types": "^6.18.0", + "babylon": "^6.18.0", + "istanbul-lib-coverage": "^1.2.0", + "semver": "^5.3.0" + } + }, + "istanbul-lib-report": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-1.1.4.tgz", + "integrity": "sha512-Azqvq5tT0U09nrncK3q82e/Zjkxa4tkFZv7E6VcqP0QCPn6oNljDPfrZEC/umNXds2t7b8sRJfs6Kmpzt8m2kA==", + "dev": true, + "requires": { + "istanbul-lib-coverage": "^1.2.0", + "mkdirp": "^0.5.1", + "path-parse": "^1.0.5", + "supports-color": "^3.1.2" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=", + "dev": true + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "dev": true, + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "istanbul-lib-source-maps": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-1.2.5.tgz", + "integrity": "sha512-8O2T/3VhrQHn0XcJbP1/GN7kXMiRAlPi+fj3uEHrjBD8Oz7Py0prSC25C09NuAZS6bgW1NNKAvCSHZXB0irSGA==", + "dev": true, + "requires": { + "debug": "^3.1.0", + "istanbul-lib-coverage": "^1.2.0", + "mkdirp": "^0.5.1", + "rimraf": "^2.6.1", + "source-map": "^0.5.3" + }, + "dependencies": { + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + } + } + }, + "istanbul-reports": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-1.3.0.tgz", + "integrity": "sha512-y2Z2IMqE1gefWUaVjrBm0mSKvUkaBy9Vqz8iwr/r40Y9hBbIteH5wqHG/9DLTfJ9xUnUT2j7A3+VVJ6EaYBllA==", + "dev": true, + "requires": { + "handlebars": "^4.0.3" + } + }, + "jasmine": { + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/jasmine/-/jasmine-2.8.0.tgz", + "integrity": "sha1-awicChFXax8W3xG4AUbZHU6Lij4=", + "dev": true, + "requires": { + "exit": "^0.1.2", + "glob": "^7.0.6", + "jasmine-core": "~2.8.0" + }, + "dependencies": { + "jasmine-core": { + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/jasmine-core/-/jasmine-core-2.8.0.tgz", + "integrity": "sha1-vMl5rh+f0FcB5F5S5l06XWPxok4=", + "dev": true + } + } + }, + "jasmine-core": { + "version": "2.99.1", + "resolved": "https://registry.npmjs.org/jasmine-core/-/jasmine-core-2.99.1.tgz", + "integrity": "sha1-5kAN8ea1bhMLYcS80JPap/boyhU=", + "dev": true + }, + "jasmine-spec-reporter": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/jasmine-spec-reporter/-/jasmine-spec-reporter-4.2.1.tgz", + "integrity": "sha512-FZBoZu7VE5nR7Nilzy+Np8KuVIOxF4oXDPDknehCYBDE080EnlPu0afdZNmpGDBRCUBv3mj5qgqCRmk6W/K8vg==", + "dev": true, + "requires": { + "colors": "1.1.2" + } + }, + "jasminewd2": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/jasminewd2/-/jasminewd2-2.2.0.tgz", + "integrity": "sha1-43zwsX8ZnM4jvqcbIDk5Uka07E4=", + "dev": true + }, + "js-base64": { + "version": "2.4.8", + "resolved": "https://registry.npmjs.org/js-base64/-/js-base64-2.4.8.tgz", + "integrity": "sha512-hm2nYpDrwoO/OzBhdcqs/XGT6XjSuSSCVEpia+Kl2J6x4CYt5hISlVL/AYU1khoDXv0AQVgxtdJySb9gjAn56Q==", + "dev": true, + "optional": true + }, + "js-tokens": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", + "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=", + "dev": true + }, + "js-yaml": { + "version": "3.12.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", + "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "dev": true, + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "dependencies": { + "esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true + } + } + }, + "jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", + "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=", + "dev": true, + "optional": true + }, + "jsesc": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-1.3.0.tgz", + "integrity": "sha1-RsP+yMGJKxKwgz25vHYiF226s0s=", + "dev": true + }, + "json-parse-better-errors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", + "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", + "dev": true + }, + "json-schema": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", + "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=", + "dev": true + }, + "json-schema-traverse": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz", + "integrity": "sha1-NJptRMU6Ud6JtAgFxdXlm0F9M0A=", + "dev": true + }, + "json-stable-stringify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify/-/json-stable-stringify-1.0.1.tgz", + "integrity": "sha1-mnWdOcXy/1A/1TAGRu1EX4jE+a8=", + "dev": true, + "optional": true, + "requires": { + "jsonify": "~0.0.0" + } + }, + "json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=", + "dev": true + }, + "json3": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/json3/-/json3-3.3.2.tgz", + "integrity": "sha1-PAQ0dD35Pi9cQq7nsZvLSDV19OE=", + "dev": true + }, + "json5": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-0.5.1.tgz", + "integrity": "sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE=", + "dev": true + }, + "jsonify": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/jsonify/-/jsonify-0.0.0.tgz", + "integrity": "sha1-LHS27kHZPKUbe1qu6PUDYx0lKnM=", + "dev": true, + "optional": true + }, + "jsprim": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", + "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", + "dev": true, + "requires": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.2.3", + "verror": "1.10.0" + } + }, + "jszip": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.1.5.tgz", + "integrity": "sha512-5W8NUaFRFRqTOL7ZDDrx5qWHJyBXy6velVudIzQUSoqAAYqzSh2Z7/m0Rf1QbmQJccegD0r+YZxBjzqoBiEeJQ==", + "dev": true, + "requires": { + "core-js": "~2.3.0", + "es6-promise": "~3.0.2", + "lie": "~3.1.0", + "pako": "~1.0.2", + "readable-stream": "~2.0.6" + }, + "dependencies": { + "core-js": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.3.0.tgz", + "integrity": "sha1-+rg/uwstjchfpjbEudNMdUIMbWU=", + "dev": true + }, + "es6-promise": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.0.2.tgz", + "integrity": "sha1-AQ1YWEI6XxGJeWZfRkhqlcbuK7Y=", + "dev": true + }, + "process-nextick-args": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.7.tgz", + "integrity": "sha1-FQ4gt1ZZCtP5EJPyWk8q2L/zC6M=", + "dev": true + }, + "readable-stream": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.0.6.tgz", + "integrity": "sha1-j5A0HmilPMySh4jaz80Rs265t44=", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "~1.0.0", + "process-nextick-args": "~1.0.6", + "string_decoder": "~0.10.x", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", + "dev": true + } + } + }, + "karma": { + "version": "1.7.1", + "resolved": "https://registry.npmjs.org/karma/-/karma-1.7.1.tgz", + "integrity": "sha512-k5pBjHDhmkdaUccnC7gE3mBzZjcxyxYsYVaqiL2G5AqlfLyBO5nw2VdNK+O16cveEPd/gIOWULH7gkiYYwVNHg==", + "dev": true, + "requires": { + "bluebird": "^3.3.0", + "body-parser": "^1.16.1", + "chokidar": "^1.4.1", + "colors": "^1.1.0", + "combine-lists": "^1.0.0", + "connect": "^3.6.0", + "core-js": "^2.2.0", + "di": "^0.0.1", + "dom-serialize": "^2.2.0", + "expand-braces": "^0.1.1", + "glob": "^7.1.1", + "graceful-fs": "^4.1.2", + "http-proxy": "^1.13.0", + "isbinaryfile": "^3.0.0", + "lodash": "^3.8.0", + "log4js": "^0.6.31", + "mime": "^1.3.4", + "minimatch": "^3.0.2", + "optimist": "^0.6.1", + "qjobs": "^1.1.4", + "range-parser": "^1.2.0", + "rimraf": "^2.6.0", + "safe-buffer": "^5.0.1", + "socket.io": "1.7.3", + "source-map": "^0.5.3", + "tmp": "0.0.31", + "useragent": "^2.1.12" + }, + "dependencies": { + "anymatch": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-1.3.2.tgz", + "integrity": "sha512-0XNayC8lTHQ2OI8aljNCN3sSx6hsr/1+rlcDAotXJR7C1oZZHCNsfpbKwMjRA3Uqb5tF1Rae2oloTr4xpq+WjA==", + "dev": true, + "requires": { + "micromatch": "^2.1.5", + "normalize-path": "^2.0.0" + } + }, + "arr-diff": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-2.0.0.tgz", + "integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=", + "dev": true, + "requires": { + "arr-flatten": "^1.0.1" + } + }, + "array-unique": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.2.1.tgz", + "integrity": "sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=", + "dev": true + }, + "braces": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/braces/-/braces-1.8.5.tgz", + "integrity": "sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=", + "dev": true, + "requires": { + "expand-range": "^1.8.1", + "preserve": "^0.2.0", + "repeat-element": "^1.1.2" + } + }, + "chokidar": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-1.7.0.tgz", + "integrity": "sha1-eY5ol3gVHIB2tLNg5e3SjNortGg=", + "dev": true, + "requires": { + "anymatch": "^1.3.0", + "async-each": "^1.0.0", + "fsevents": "^1.0.0", + "glob-parent": "^2.0.0", + "inherits": "^2.0.1", + "is-binary-path": "^1.0.0", + "is-glob": "^2.0.0", + "path-is-absolute": "^1.0.0", + "readdirp": "^2.0.0" + } + }, + "expand-brackets": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-0.1.5.tgz", + "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=", + "dev": true, + "requires": { + "is-posix-bracket": "^0.1.0" + } + }, + "extglob": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-0.3.2.tgz", + "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=", + "dev": true, + "requires": { + "is-extglob": "^1.0.0" + } + }, + "glob-parent": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-2.0.0.tgz", + "integrity": "sha1-gTg9ctsFT8zPUzbaqQLxgvbtuyg=", + "dev": true, + "requires": { + "is-glob": "^2.0.0" + } + }, + "is-extglob": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-1.0.0.tgz", + "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=", + "dev": true + }, + "is-glob": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-2.0.1.tgz", + "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", + "dev": true, + "requires": { + "is-extglob": "^1.0.0" + } + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + }, + "lodash": { + "version": "3.10.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-3.10.1.tgz", + "integrity": "sha1-W/Rejkm6QYnhfUgnid/RW9FAt7Y=", + "dev": true + }, + "micromatch": { + "version": "2.3.11", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-2.3.11.tgz", + "integrity": "sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=", + "dev": true, + "requires": { + "arr-diff": "^2.0.0", + "array-unique": "^0.2.1", + "braces": "^1.8.2", + "expand-brackets": "^0.1.4", + "extglob": "^0.3.1", + "filename-regex": "^2.0.0", + "is-extglob": "^1.0.0", + "is-glob": "^2.0.1", + "kind-of": "^3.0.2", + "normalize-path": "^2.0.1", + "object.omit": "^2.0.0", + "parse-glob": "^3.0.4", + "regex-cache": "^0.4.2" + } + } + } + }, + "karma-chrome-launcher": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/karma-chrome-launcher/-/karma-chrome-launcher-2.2.0.tgz", + "integrity": "sha512-uf/ZVpAabDBPvdPdveyk1EPgbnloPvFFGgmRhYLTDH7gEB4nZdSBk8yTU47w1g/drLSx5uMOkjKk7IWKfWg/+w==", + "dev": true, + "requires": { + "fs-access": "^1.0.0", + "which": "^1.2.1" + } + }, + "karma-coverage-istanbul-reporter": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/karma-coverage-istanbul-reporter/-/karma-coverage-istanbul-reporter-2.0.1.tgz", + "integrity": "sha512-UcgrHkFehI5+ivMouD8NH/UOHiX4oCAtwaANylzPFdcAuD52fnCUuelacq2gh8tZ4ydhU3+xiXofSq7j5Ehygw==", + "dev": true, + "requires": { + "istanbul-api": "^1.3.1", + "minimatch": "^3.0.4" + } + }, + "karma-jasmine": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/karma-jasmine/-/karma-jasmine-1.1.2.tgz", + "integrity": "sha1-OU8rJf+0pkS5rabyLUQ+L9CIhsM=", + "dev": true + }, + "karma-jasmine-html-reporter": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/karma-jasmine-html-reporter/-/karma-jasmine-html-reporter-0.2.2.tgz", + "integrity": "sha1-SKjl7xiAdhfuK14zwRlMNbQ5Ukw=", + "dev": true, + "requires": { + "karma-jasmine": "^1.0.2" + } + }, + "karma-source-map-support": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/karma-source-map-support/-/karma-source-map-support-1.3.0.tgz", + "integrity": "sha512-HcPqdAusNez/ywa+biN4EphGz62MmQyPggUsDfsHqa7tSe4jdsxgvTKuDfIazjL+IOxpVWyT7Pr4dhAV+sxX5Q==", + "dev": true, + "requires": { + "source-map-support": "^0.5.5" + } + }, + "killable": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/killable/-/killable-1.0.0.tgz", + "integrity": "sha1-2ouEvUfeU5WHj5XWTQLyRJ/gXms=", + "dev": true + }, + "kind-of": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "dev": true + }, + "lazy-cache": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/lazy-cache/-/lazy-cache-1.0.4.tgz", + "integrity": "sha1-odePw6UEdMuAhF07O24dpJpEbo4=", + "dev": true, + "optional": true + }, + "lcid": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/lcid/-/lcid-1.0.0.tgz", + "integrity": "sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU=", + "dev": true, + "requires": { + "invert-kv": "^1.0.0" + } + }, + "leb": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/leb/-/leb-0.3.0.tgz", + "integrity": "sha1-Mr7p+tFoMo1q6oUi2DP0GA7tHaM=", + "dev": true + }, + "less": { + "version": "3.7.1", + "resolved": "https://registry.npmjs.org/less/-/less-3.7.1.tgz", + "integrity": "sha512-Cmf5XJlzNklkBC8eAa+Ef16AHUBAkApHNAw3x9Vmn84h2BvGrri5Id7kf6H1n6SN74Fc0WdHIRPlFMxsl0eJkA==", + "dev": true, + "requires": { + "errno": "^0.1.1", + "graceful-fs": "^4.1.2", + "image-size": "~0.5.0", + "mime": "^1.4.1", + "mkdirp": "^0.5.0", + "promise": "^7.1.1", + "request": "^2.83.0", + "source-map": "~0.6.0" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "optional": true + } + } + }, + "less-loader": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/less-loader/-/less-loader-4.1.0.tgz", + "integrity": "sha512-KNTsgCE9tMOM70+ddxp9yyt9iHqgmSs0yTZc5XH5Wo+g80RWRIYNqE58QJKm/yMud5wZEvz50ugRDuzVIkyahg==", + "dev": true, + "requires": { + "clone": "^2.1.1", + "loader-utils": "^1.1.0", + "pify": "^3.0.0" + } + }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "dev": true, + "requires": { + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" + } + }, + "license-webpack-plugin": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/license-webpack-plugin/-/license-webpack-plugin-1.3.1.tgz", + "integrity": "sha512-NqAFodJdpBUuf1iD+Ij8hQvF0rCFKlO2KaieoQzAPhFgzLCtJnC7Z7x5gQbGNjoe++wOKAtAmwVEIBLqq2Yp1A==", + "dev": true, + "requires": { + "ejs": "^2.5.7" + } + }, + "lie": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/lie/-/lie-3.1.1.tgz", + "integrity": "sha1-mkNrLMd0bKWd56QfpGmz77dr2H4=", + "dev": true, + "requires": { + "immediate": "~3.0.5" + } + }, + "load-json-file": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", + "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "parse-json": "^2.2.0", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0", + "strip-bom": "^2.0.0" + }, + "dependencies": { + "pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", + "dev": true + } + } + }, + "loader-runner": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-2.3.0.tgz", + "integrity": "sha1-9IKuqC1UPgeSFwDVpG7yb9rGuKI=", + "dev": true + }, + "loader-utils": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.1.0.tgz", + "integrity": "sha1-yYrvSIvM7aL/teLeZG1qdUQp9c0=", + "dev": true, + "requires": { + "big.js": "^3.1.3", + "emojis-list": "^2.0.0", + "json5": "^0.5.0" + } + }, + "locate-path": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", + "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", + "dev": true, + "requires": { + "p-locate": "^2.0.0", + "path-exists": "^3.0.0" + } + }, + "lodash": { + "version": "4.17.10", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.10.tgz", + "integrity": "sha512-UejweD1pDoXu+AD825lWwp4ZGtSwgnpZxb3JDViD7StjQz+Nb/6l093lx4OQ0foGWNRoc19mWy7BzL+UAK2iVg==", + "dev": true + }, + "lodash.assign": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/lodash.assign/-/lodash.assign-4.2.0.tgz", + "integrity": "sha1-DZnzzNem0mHRm9rrkkUAXShYCOc=", + "dev": true, + "optional": true + }, + "lodash.clonedeep": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", + "integrity": "sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8=", + "dev": true + }, + "lodash.debounce": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", + "integrity": "sha1-gteb/zCmfEAF/9XiUVMArZyk168=", + "dev": true + }, + "lodash.mergewith": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/lodash.mergewith/-/lodash.mergewith-4.6.1.tgz", + "integrity": "sha512-eWw5r+PYICtEBgrBE5hhlT6aAa75f411bgDz/ZL2KZqYV03USvucsxcHUIlGTDTECs1eunpI7HOV7U+WLDvNdQ==", + "dev": true, + "optional": true + }, + "lodash.tail": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.tail/-/lodash.tail-4.1.1.tgz", + "integrity": "sha1-0jM6NtnncXyK0vfKyv7HwytERmQ=", + "dev": true + }, + "log-symbols": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-2.2.0.tgz", + "integrity": "sha512-VeIAFslyIerEJLXHziedo2basKbMKtTw3vfn5IzG0XTjhAVEJyNHnL2p7vc+wBDSdQuUpNw3M2u6xb9QsAY5Eg==", + "dev": true, + "requires": { + "chalk": "^2.0.1" + } + }, + "log4js": { + "version": "0.6.38", + "resolved": "https://registry.npmjs.org/log4js/-/log4js-0.6.38.tgz", + "integrity": "sha1-LElBFmldb7JUgJQ9P8hy5mKlIv0=", + "dev": true, + "requires": { + "readable-stream": "~1.0.2", + "semver": "~4.3.3" + }, + "dependencies": { + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", + "dev": true + }, + "readable-stream": { + "version": "1.0.34", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", + "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "semver": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-4.3.6.tgz", + "integrity": "sha1-MAvG4OhjdPe6YQaLWx7NV/xlMto=", + "dev": true + }, + "string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", + "dev": true + } + } + }, + "loglevel": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/loglevel/-/loglevel-1.6.1.tgz", + "integrity": "sha1-4PyVEztu8nbNyIh82vJKpvFW+Po=", + "dev": true + }, + "loglevelnext": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/loglevelnext/-/loglevelnext-1.0.5.tgz", + "integrity": "sha512-V/73qkPuJmx4BcBF19xPBr+0ZRVBhc4POxvZTZdMeXpJ4NItXSJ/MSwuFT0kQJlCbXvdlZoQQ/418bS1y9Jh6A==", + "dev": true, + "requires": { + "es6-symbol": "^3.1.1", + "object.assign": "^4.1.0" + } + }, + "long": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/long/-/long-3.2.0.tgz", + "integrity": "sha1-2CG3E4yhy1gcFymQ7xTbIAtcR0s=", + "dev": true + }, + "longest": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/longest/-/longest-1.0.1.tgz", + "integrity": "sha1-MKCy2jj3N3DoKUoNIuZiXtd9AJc=", + "dev": true + }, + "loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "dev": true, + "requires": { + "js-tokens": "^3.0.0 || ^4.0.0" + } + }, + "loud-rejection": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/loud-rejection/-/loud-rejection-1.6.0.tgz", + "integrity": "sha1-W0b4AUft7leIcPCG0Eghz5mOVR8=", + "dev": true, + "requires": { + "currently-unhandled": "^0.4.1", + "signal-exit": "^3.0.0" + } + }, + "lower-case": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/lower-case/-/lower-case-1.1.4.tgz", + "integrity": "sha1-miyr0bno4K6ZOkv31YdcOcQujqw=", + "dev": true + }, + "lru-cache": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.3.tgz", + "integrity": "sha512-fFEhvcgzuIoJVUF8fYr5KR0YqxD238zgObTps31YdADwPPAp82a4M8TrckkWyx7ekNlf9aBcVn81cFwwXngrJA==", + "dev": true, + "requires": { + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" + } + }, + "make-dir": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.3.0.tgz", + "integrity": "sha512-2w31R7SJtieJJnQtGc7RVL2StM2vGYVfqUOvUDxH6bC6aJTxPxTF0GnIgCyu7tjockiUWAYQRbxa7vKn34s5sQ==", + "dev": true, + "requires": { + "pify": "^3.0.0" + } + }, + "make-error": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.4.tgz", + "integrity": "sha512-0Dab5btKVPhibSalc9QGXb559ED7G7iLjFXBaj9Wq8O3vorueR5K5jaE3hkG6ZQINyhA/JgG6Qk4qdFQjsYV6g==", + "dev": true + }, + "map-cache": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", + "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=", + "dev": true + }, + "map-obj": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz", + "integrity": "sha1-2TPOuSBdgr3PSIb2dCvcK03qFG0=", + "dev": true + }, + "map-visit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/map-visit/-/map-visit-1.0.0.tgz", + "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=", + "dev": true, + "requires": { + "object-visit": "^1.0.0" + } + }, + "math-random": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/math-random/-/math-random-1.0.1.tgz", + "integrity": "sha1-izqsWIuKZuSXXjzepn97sylgH6w=", + "dev": true + }, + "md5.js": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.4.tgz", + "integrity": "sha1-6b296UogpawYsENA/Fdk1bCdkB0=", + "dev": true, + "requires": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1" + } + }, + "media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=", + "dev": true + }, + "mem": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/mem/-/mem-1.1.0.tgz", + "integrity": "sha1-Xt1StIXKHZAP5kiVUFOZoN+kX3Y=", + "dev": true, + "requires": { + "mimic-fn": "^1.0.0" + } + }, + "memory-fs": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/memory-fs/-/memory-fs-0.4.1.tgz", + "integrity": "sha1-OpoguEYlI+RHz7x+i7gO1me/xVI=", + "dev": true, + "requires": { + "errno": "^0.1.3", + "readable-stream": "^2.0.1" + } + }, + "meow": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/meow/-/meow-3.7.0.tgz", + "integrity": "sha1-cstmi0JSKCkKu/qFaJJYcwioAfs=", + "dev": true, + "requires": { + "camelcase-keys": "^2.0.0", + "decamelize": "^1.1.2", + "loud-rejection": "^1.0.0", + "map-obj": "^1.0.1", + "minimist": "^1.1.3", + "normalize-package-data": "^2.3.4", + "object-assign": "^4.0.1", + "read-pkg-up": "^1.0.1", + "redent": "^1.0.0", + "trim-newlines": "^1.0.0" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + } + } + }, + "merge-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=", + "dev": true + }, + "methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=", + "dev": true + }, + "micromatch": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz", + "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==", + "dev": true, + "requires": { + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "braces": "^2.3.1", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "extglob": "^2.0.4", + "fragment-cache": "^0.2.1", + "kind-of": "^6.0.2", + "nanomatch": "^1.2.9", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.2" + } + }, + "miller-rabin": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/miller-rabin/-/miller-rabin-4.0.1.tgz", + "integrity": "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA==", + "dev": true, + "requires": { + "bn.js": "^4.0.0", + "brorand": "^1.0.1" + } + }, + "mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "dev": true + }, + "mime-db": { + "version": "1.35.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.35.0.tgz", + "integrity": "sha512-JWT/IcCTsB0Io3AhWUMjRqucrHSPsSf2xKLaRldJVULioggvkJvggZ3VXNNSRkCddE6D+BUI4HEIZIA2OjwIvg==", + "dev": true + }, + "mime-types": { + "version": "2.1.19", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.19.tgz", + "integrity": "sha512-P1tKYHVSZ6uFo26mtnve4HQFE3koh1UWVkp8YUC+ESBHe945xWSoXuHHiGarDqcEZ+whpCDnlNw5LON0kLo+sw==", + "dev": true, + "requires": { + "mime-db": "~1.35.0" + } + }, + "mimic-fn": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz", + "integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==", + "dev": true + }, + "mini-css-extract-plugin": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/mini-css-extract-plugin/-/mini-css-extract-plugin-0.4.1.tgz", + "integrity": "sha512-XWuB3G61Rtasq/gLe7cp5cuozehE6hN+E4sxCamRR/WDiHTg+f7ZIAS024r8UJQffY+e2gGELXQZgQoFDfNDCg==", + "dev": true, + "requires": { + "@webpack-contrib/schema-utils": "^1.0.0-beta.0", + "loader-utils": "^1.1.0", + "webpack-sources": "^1.1.0" + } + }, + "minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", + "dev": true + }, + "minimalistic-crypto-utils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz", + "integrity": "sha1-9sAMHAsIIkblxNmd+4x8CDsrWCo=", + "dev": true + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "dev": true + }, + "mississippi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mississippi/-/mississippi-2.0.0.tgz", + "integrity": "sha512-zHo8v+otD1J10j/tC+VNoGK9keCuByhKovAvdn74dmxJl9+mWHnx6EMsDN4lgRoMI/eYo2nchAxniIbUPb5onw==", + "dev": true, + "requires": { + "concat-stream": "^1.5.0", + "duplexify": "^3.4.2", + "end-of-stream": "^1.1.0", + "flush-write-stream": "^1.0.0", + "from2": "^2.1.0", + "parallel-transform": "^1.1.0", + "pump": "^2.0.1", + "pumpify": "^1.3.3", + "stream-each": "^1.1.0", + "through2": "^2.0.0" + } + }, + "mixin-deep": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.1.tgz", + "integrity": "sha512-8ZItLHeEgaqEvd5lYBXfm4EZSFCX29Jb9K+lAHhDKzReKBQKj3R+7NOF6tjqYi9t4oI8VUfaWITJQm86wnXGNQ==", + "dev": true, + "requires": { + "for-in": "^1.0.2", + "is-extendable": "^1.0.1" + }, + "dependencies": { + "is-extendable": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", + "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", + "dev": true, + "requires": { + "is-plain-object": "^2.0.4" + } + } + } + }, + "mixin-object": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mixin-object/-/mixin-object-2.0.1.tgz", + "integrity": "sha1-T7lJRB2rGCVA8f4DW6YOGUel5X4=", + "dev": true, + "requires": { + "for-in": "^0.1.3", + "is-extendable": "^0.1.1" + }, + "dependencies": { + "for-in": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/for-in/-/for-in-0.1.8.tgz", + "integrity": "sha1-2Hc5COMSVhCZUrH9ubP6hn0ndeE=", + "dev": true + } + } + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "dev": true, + "requires": { + "minimist": "0.0.8" + } + }, + "move-concurrently": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/move-concurrently/-/move-concurrently-1.0.1.tgz", + "integrity": "sha1-viwAX9oy4LKa8fBdfEszIUxwH5I=", + "dev": true, + "requires": { + "aproba": "^1.1.1", + "copy-concurrently": "^1.0.0", + "fs-write-stream-atomic": "^1.0.8", + "mkdirp": "^0.5.1", + "rimraf": "^2.5.4", + "run-queue": "^1.0.3" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "multicast-dns": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/multicast-dns/-/multicast-dns-6.2.3.tgz", + "integrity": "sha512-ji6J5enbMyGRHIAkAOu3WdV8nggqviKCEKtXcOqfphZZtQrmHKycfynJ2V7eVPUA4NhJ6V7Wf4TmGbTwKE9B6g==", + "dev": true, + "requires": { + "dns-packet": "^1.3.1", + "thunky": "^1.0.2" + } + }, + "multicast-dns-service-types": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/multicast-dns-service-types/-/multicast-dns-service-types-1.1.0.tgz", + "integrity": "sha1-iZ8R2WhuXgXLkbNdXw5jt3PPyQE=", + "dev": true + }, + "nan": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.10.0.tgz", + "integrity": "sha512-bAdJv7fBLhWC+/Bls0Oza+mvTaNQtP+1RyhhhvD95pgUJz6XM5IzgmxOkItJ9tkoCiplvAnXI1tNmmUD/eScyA==", + "dev": true, + "optional": true + }, + "nanomatch": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz", + "integrity": "sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA==", + "dev": true, + "requires": { + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "fragment-cache": "^0.2.1", + "is-windows": "^1.0.2", + "kind-of": "^6.0.2", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + } + }, + "negotiator": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.1.tgz", + "integrity": "sha1-KzJxhOiZIQEXeyhWP7XnECrNDKk=", + "dev": true + }, + "neo-async": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.5.1.tgz", + "integrity": "sha512-3KL3fvuRkZ7s4IFOMfztb7zJp3QaVWnBeGoJlgB38XnCRPj/0tLzzLG5IB8NYOHbJ8g8UGrgZv44GLDk6CxTxA==", + "dev": true + }, + "next-tick": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.0.0.tgz", + "integrity": "sha1-yobR/ogoFpsBICCOPchCS524NCw=", + "dev": true + }, + "no-case": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/no-case/-/no-case-2.3.2.tgz", + "integrity": "sha512-rmTZ9kz+f3rCvK2TD1Ue/oZlns7OGoIWP4fc3llxxRXlOkHKoWPPWJOfFYpITabSow43QJbRIoHQXtt10VldyQ==", + "dev": true, + "requires": { + "lower-case": "^1.1.1" + } + }, + "node-forge": { + "version": "0.7.5", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-0.7.5.tgz", + "integrity": "sha512-MmbQJ2MTESTjt3Gi/3yG1wGpIMhUfcIypUCGtTizFR9IiccFwxSpfp0vtIZlkFclEqERemxfnSdZEMR9VqqEFQ==", + "dev": true + }, + "node-gyp": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-3.7.0.tgz", + "integrity": "sha512-qDQE/Ft9xXP6zphwx4sD0t+VhwV7yFaloMpfbL2QnnDZcyaiakWlLdtFGGQfTAwpFHdpbRhRxVhIHN1OKAjgbg==", + "dev": true, + "optional": true, + "requires": { + "fstream": "^1.0.0", + "glob": "^7.0.3", + "graceful-fs": "^4.1.2", + "mkdirp": "^0.5.0", + "nopt": "2 || 3", + "npmlog": "0 || 1 || 2 || 3 || 4", + "osenv": "0", + "request": ">=2.9.0 <2.82.0", + "rimraf": "2", + "semver": "~5.3.0", + "tar": "^2.0.0", + "which": "1" + }, + "dependencies": { + "ajv": { + "version": "4.11.8", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-4.11.8.tgz", + "integrity": "sha1-gv+wKynmYq5TvcIK8VlHcGc5xTY=", + "dev": true, + "optional": true, + "requires": { + "co": "^4.6.0", + "json-stable-stringify": "^1.0.1" + } + }, + "assert-plus": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-0.2.0.tgz", + "integrity": "sha1-104bh+ev/A24qttwIfP+SBAasjQ=", + "dev": true, + "optional": true + }, + "aws-sign2": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.6.0.tgz", + "integrity": "sha1-FDQt0428yU0OW4fXY81jYSwOeU8=", + "dev": true, + "optional": true + }, + "form-data": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.1.4.tgz", + "integrity": "sha1-M8GDrPGTJ27KqYFDpp6Uv+4XUNE=", + "dev": true, + "optional": true, + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.5", + "mime-types": "^2.1.12" + } + }, + "har-schema": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-1.0.5.tgz", + "integrity": "sha1-0mMTX0MwfALGAq/I/pWXDAFRNp4=", + "dev": true, + "optional": true + }, + "har-validator": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-4.2.1.tgz", + "integrity": "sha1-M0gdDxu/9gDdID11gSpqX7oALio=", + "dev": true, + "optional": true, + "requires": { + "ajv": "^4.9.1", + "har-schema": "^1.0.5" + } + }, + "http-signature": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.1.1.tgz", + "integrity": "sha1-33LiZwZs0Kxn+3at+OE0qPvPkb8=", + "dev": true, + "optional": true, + "requires": { + "assert-plus": "^0.2.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" + } + }, + "performance-now": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-0.2.0.tgz", + "integrity": "sha1-M+8wxcd9TqIcWlOGnZG1bY8lVeU=", + "dev": true, + "optional": true + }, + "qs": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.4.0.tgz", + "integrity": "sha1-E+JtKK1rD/qpExLNO/cI7TUecjM=", + "dev": true, + "optional": true + }, + "request": { + "version": "2.81.0", + "resolved": "https://registry.npmjs.org/request/-/request-2.81.0.tgz", + "integrity": "sha1-xpKJRqDgbF+Nb4qTM0af/aRimKA=", + "dev": true, + "optional": true, + "requires": { + "aws-sign2": "~0.6.0", + "aws4": "^1.2.1", + "caseless": "~0.12.0", + "combined-stream": "~1.0.5", + "extend": "~3.0.0", + "forever-agent": "~0.6.1", + "form-data": "~2.1.1", + "har-validator": "~4.2.1", + "hawk": "~3.1.3", + "http-signature": "~1.1.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.7", + "oauth-sign": "~0.8.1", + "performance-now": "^0.2.0", + "qs": "~6.4.0", + "safe-buffer": "^5.0.1", + "stringstream": "~0.0.4", + "tough-cookie": "~2.3.0", + "tunnel-agent": "^0.6.0", + "uuid": "^3.0.0" + } + }, + "semver": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.3.0.tgz", + "integrity": "sha1-myzl094C0XxgEq0yaqa00M9U+U8=", + "dev": true, + "optional": true + } + } + }, + "node-libs-browser": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/node-libs-browser/-/node-libs-browser-2.1.0.tgz", + "integrity": "sha512-5AzFzdoIMb89hBGMZglEegffzgRg+ZFoUmisQ8HI4j1KDdpx13J0taNp2y9xPbur6W61gepGDDotGBVQ7mfUCg==", + "dev": true, + "requires": { + "assert": "^1.1.1", + "browserify-zlib": "^0.2.0", + "buffer": "^4.3.0", + "console-browserify": "^1.1.0", + "constants-browserify": "^1.0.0", + "crypto-browserify": "^3.11.0", + "domain-browser": "^1.1.1", + "events": "^1.0.0", + "https-browserify": "^1.0.0", + "os-browserify": "^0.3.0", + "path-browserify": "0.0.0", + "process": "^0.11.10", + "punycode": "^1.2.4", + "querystring-es3": "^0.2.0", + "readable-stream": "^2.3.3", + "stream-browserify": "^2.0.1", + "stream-http": "^2.7.2", + "string_decoder": "^1.0.0", + "timers-browserify": "^2.0.4", + "tty-browserify": "0.0.0", + "url": "^0.11.0", + "util": "^0.10.3", + "vm-browserify": "0.0.4" + }, + "dependencies": { + "punycode": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", + "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=", + "dev": true + } + } + }, + "node-sass": { + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/node-sass/-/node-sass-4.9.2.tgz", + "integrity": "sha512-LdxoJLZutx0aQXHtWIYwJKMj+9pTjneTcLWJgzf2XbGu0q5pRNqW5QvFCEdm3mc5rJOdru/mzln5d0EZLacf6g==", + "dev": true, + "optional": true, + "requires": { + "async-foreach": "^0.1.3", + "chalk": "^1.1.1", + "cross-spawn": "^3.0.0", + "gaze": "^1.0.0", + "get-stdin": "^4.0.1", + "glob": "^7.0.3", + "in-publish": "^2.0.0", + "lodash.assign": "^4.2.0", + "lodash.clonedeep": "^4.3.2", + "lodash.mergewith": "^4.6.0", + "meow": "^3.7.0", + "mkdirp": "^0.5.1", + "nan": "^2.10.0", + "node-gyp": "^3.3.1", + "npmlog": "^4.0.0", + "request": "2.87.0", + "sass-graph": "^2.2.4", + "stdout-stream": "^1.4.0", + "true-case-path": "^1.0.2" + }, + "dependencies": { + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true, + "optional": true + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "optional": true, + "requires": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + } + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true, + "optional": true + } + } + }, + "nopt": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-3.0.6.tgz", + "integrity": "sha1-xkZdvwirzU2zWTF/eaxopkayj/k=", + "dev": true, + "requires": { + "abbrev": "1" + } + }, + "normalize-package-data": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.4.0.tgz", + "integrity": "sha512-9jjUFbTPfEy3R/ad/2oNbKtW9Hgovl5O1FvFWKkKblNXoN/Oou6+9+KKohPK13Yc3/TyunyWhJp6gvRNR/PPAw==", + "dev": true, + "requires": { + "hosted-git-info": "^2.1.4", + "is-builtin-module": "^1.0.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" + } + }, + "normalize-path": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz", + "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", + "dev": true, + "requires": { + "remove-trailing-separator": "^1.0.1" + } + }, + "normalize-range": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/normalize-range/-/normalize-range-0.1.2.tgz", + "integrity": "sha1-LRDAa9/TEuqXd2laTShDlFa3WUI=", + "dev": true + }, + "npm-package-arg": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-6.1.0.tgz", + "integrity": "sha512-zYbhP2k9DbJhA0Z3HKUePUgdB1x7MfIfKssC+WLPFMKTBZKpZh5m13PgexJjCq6KW7j17r0jHWcCpxEqnnncSA==", + "dev": true, + "requires": { + "hosted-git-info": "^2.6.0", + "osenv": "^0.1.5", + "semver": "^5.5.0", + "validate-npm-package-name": "^3.0.0" + } + }, + "npm-registry-client": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/npm-registry-client/-/npm-registry-client-8.6.0.tgz", + "integrity": "sha512-Qs6P6nnopig+Y8gbzpeN/dkt+n7IyVd8f45NTMotGk6Qo7GfBmzwYx6jRLoOOgKiMnaQfYxsuyQlD8Mc3guBhg==", + "dev": true, + "requires": { + "concat-stream": "^1.5.2", + "graceful-fs": "^4.1.6", + "normalize-package-data": "~1.0.1 || ^2.0.0", + "npm-package-arg": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0", + "npmlog": "2 || ^3.1.0 || ^4.0.0", + "once": "^1.3.3", + "request": "^2.74.0", + "retry": "^0.10.0", + "safe-buffer": "^5.1.1", + "semver": "2 >=2.2.1 || 3.x || 4 || 5", + "slide": "^1.1.3", + "ssri": "^5.2.4" + } + }, + "npm-run-path": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz", + "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", + "dev": true, + "requires": { + "path-key": "^2.0.0" + } + }, + "npmlog": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-4.1.2.tgz", + "integrity": "sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg==", + "dev": true, + "requires": { + "are-we-there-yet": "~1.1.2", + "console-control-strings": "~1.1.0", + "gauge": "~2.7.3", + "set-blocking": "~2.0.0" + } + }, + "nth-check": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-1.0.1.tgz", + "integrity": "sha1-mSms32KPwsQQmN6rgqxYDPFJquQ=", + "dev": true, + "requires": { + "boolbase": "~1.0.0" + } + }, + "null-check": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/null-check/-/null-check-1.0.0.tgz", + "integrity": "sha1-l33/1xdgErnsMNKjnbXPcqBDnt0=", + "dev": true + }, + "num2fraction": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/num2fraction/-/num2fraction-1.2.2.tgz", + "integrity": "sha1-b2gragJ6Tp3fpFZM0lidHU5mnt4=", + "dev": true + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", + "dev": true + }, + "oauth-sign": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.8.2.tgz", + "integrity": "sha1-Rqarfwrq2N6unsBWV4C31O/rnUM=", + "dev": true + }, + "object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", + "dev": true + }, + "object-component": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/object-component/-/object-component-0.0.3.tgz", + "integrity": "sha1-8MaapQ78lbhmwYb0AKM3acsvEpE=", + "dev": true + }, + "object-copy": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/object-copy/-/object-copy-0.1.0.tgz", + "integrity": "sha1-fn2Fi3gb18mRpBupde04EnVOmYw=", + "dev": true, + "requires": { + "copy-descriptor": "^0.1.0", + "define-property": "^0.2.5", + "kind-of": "^3.0.3" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "object-keys": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.0.12.tgz", + "integrity": "sha512-FTMyFUm2wBcGHnH2eXmz7tC6IwlqQZ6mVZ+6dm6vZ4IQIHjs6FdNsQBuKGPuUUUY6NfJw2PshC08Tn6LzLDOag==", + "dev": true + }, + "object-visit": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/object-visit/-/object-visit-1.0.1.tgz", + "integrity": "sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=", + "dev": true, + "requires": { + "isobject": "^3.0.0" + } + }, + "object.assign": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.0.tgz", + "integrity": "sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w==", + "dev": true, + "requires": { + "define-properties": "^1.1.2", + "function-bind": "^1.1.1", + "has-symbols": "^1.0.0", + "object-keys": "^1.0.11" + } + }, + "object.getownpropertydescriptors": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/object.getownpropertydescriptors/-/object.getownpropertydescriptors-2.0.3.tgz", + "integrity": "sha1-h1jIRvW0B62rDyNuCYbxSwUcqhY=", + "dev": true, + "requires": { + "define-properties": "^1.1.2", + "es-abstract": "^1.5.1" + } + }, + "object.omit": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/object.omit/-/object.omit-2.0.1.tgz", + "integrity": "sha1-Gpx0SCnznbuFjHbKNXmuKlTr0fo=", + "dev": true, + "requires": { + "for-own": "^0.1.4", + "is-extendable": "^0.1.1" + }, + "dependencies": { + "for-own": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/for-own/-/for-own-0.1.5.tgz", + "integrity": "sha1-UmXGgaTylNq78XyVCbZ2OqhFEM4=", + "dev": true, + "requires": { + "for-in": "^1.0.1" + } + } + } + }, + "object.pick": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz", + "integrity": "sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=", + "dev": true, + "requires": { + "isobject": "^3.0.1" + } + }, + "obuf": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/obuf/-/obuf-1.1.2.tgz", + "integrity": "sha512-PX1wu0AmAdPqOL1mWhqmlOd8kOIZQwGZw6rh7uby9fTc5lhaOWFLX3I6R1hrF9k3zUY40e6igsLGkDXK92LJNg==", + "dev": true + }, + "on-finished": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "dev": true, + "requires": { + "ee-first": "1.1.1" + } + }, + "on-headers": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.1.tgz", + "integrity": "sha1-ko9dD0cNSTQmUepnlLCFfBAGk/c=", + "dev": true + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "opn": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/opn/-/opn-5.3.0.tgz", + "integrity": "sha512-bYJHo/LOmoTd+pfiYhfZDnf9zekVJrY+cnS2a5F2x+w5ppvTqObojTP7WiFG+kVZs9Inw+qQ/lw7TroWwhdd2g==", + "dev": true, + "requires": { + "is-wsl": "^1.1.0" + } + }, + "optimist": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/optimist/-/optimist-0.6.1.tgz", + "integrity": "sha1-2j6nRob6IaGaERwybpDrFaAZZoY=", + "dev": true, + "requires": { + "minimist": "~0.0.1", + "wordwrap": "~0.0.2" + }, + "dependencies": { + "wordwrap": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.3.tgz", + "integrity": "sha1-o9XabNXAvAAI03I0u68b7WMFkQc=", + "dev": true + } + } + }, + "optionator": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", + "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", + "dev": true, + "requires": { + "deep-is": "~0.1.3", + "fast-levenshtein": "~2.0.4", + "levn": "~0.3.0", + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2", + "wordwrap": "~1.0.0" + } + }, + "options": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/options/-/options-0.0.6.tgz", + "integrity": "sha1-7CLTEoBrtT5zF3Pnza788cZDEo8=", + "dev": true + }, + "original": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/original/-/original-1.0.1.tgz", + "integrity": "sha512-IEvtB5vM5ULvwnqMxWBLxkS13JIEXbakizMSo3yoPNPCIWzg8TG3Usn/UhXoZFM/m+FuEA20KdzPSFq/0rS+UA==", + "dev": true, + "requires": { + "url-parse": "~1.4.0" + } + }, + "os-browserify": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/os-browserify/-/os-browserify-0.3.0.tgz", + "integrity": "sha1-hUNzx/XCMVkU/Jv8a9gjj92h7Cc=", + "dev": true + }, + "os-homedir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", + "integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M=", + "dev": true + }, + "os-locale": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-1.4.0.tgz", + "integrity": "sha1-IPnxeuKe00XoveWDsT0gCYA8FNk=", + "dev": true, + "optional": true, + "requires": { + "lcid": "^1.0.0" + } + }, + "os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", + "dev": true + }, + "osenv": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/osenv/-/osenv-0.1.5.tgz", + "integrity": "sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g==", + "dev": true, + "requires": { + "os-homedir": "^1.0.0", + "os-tmpdir": "^1.0.0" + } + }, + "p-finally": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=", + "dev": true + }, + "p-limit": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", + "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", + "dev": true, + "requires": { + "p-try": "^1.0.0" + } + }, + "p-locate": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", + "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", + "dev": true, + "requires": { + "p-limit": "^1.1.0" + } + }, + "p-map": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-1.2.0.tgz", + "integrity": "sha512-r6zKACMNhjPJMTl8KcFH4li//gkrXWfbD6feV8l6doRHlzljFWGJ2AP6iKaCJXyZmAUMOPtvbW7EXkbWO/pLEA==", + "dev": true + }, + "p-try": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", + "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=", + "dev": true + }, + "pako": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.6.tgz", + "integrity": "sha512-lQe48YPsMJAig+yngZ87Lus+NF+3mtu7DVOBu6b/gHO1YpKwIj5AWjZ/TOS7i46HD/UixzWb1zeWDZfGZ3iYcg==", + "dev": true + }, + "parallel-transform": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/parallel-transform/-/parallel-transform-1.1.0.tgz", + "integrity": "sha1-1BDwZbBdojCB/NEPKIVMKb2jOwY=", + "dev": true, + "requires": { + "cyclist": "~0.2.2", + "inherits": "^2.0.3", + "readable-stream": "^2.1.5" + } + }, + "param-case": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/param-case/-/param-case-2.1.1.tgz", + "integrity": "sha1-35T9jPZTHs915r75oIWPvHK+Ikc=", + "dev": true, + "requires": { + "no-case": "^2.2.0" + } + }, + "parse-asn1": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.1.tgz", + "integrity": "sha512-KPx7flKXg775zZpnp9SxJlz00gTd4BmJ2yJufSc44gMCRrRQ7NSzAcSJQfifuOLgW6bEi+ftrALtsgALeB2Adw==", + "dev": true, + "requires": { + "asn1.js": "^4.0.0", + "browserify-aes": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.0", + "pbkdf2": "^3.0.3" + } + }, + "parse-glob": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/parse-glob/-/parse-glob-3.0.4.tgz", + "integrity": "sha1-ssN2z7EfNVE7rdFz7wu246OIORw=", + "dev": true, + "requires": { + "glob-base": "^0.3.0", + "is-dotfile": "^1.0.0", + "is-extglob": "^1.0.0", + "is-glob": "^2.0.0" + }, + "dependencies": { + "is-extglob": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-1.0.0.tgz", + "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=", + "dev": true + }, + "is-glob": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-2.0.1.tgz", + "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", + "dev": true, + "requires": { + "is-extglob": "^1.0.0" + } + } + } + }, + "parse-json": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-2.2.0.tgz", + "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", + "dev": true, + "requires": { + "error-ex": "^1.2.0" + } + }, + "parse5": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-4.0.0.tgz", + "integrity": "sha512-VrZ7eOd3T1Fk4XWNXMgiGBK/z0MG48BWG2uQNU4I72fkQuKUTZpl+u9k+CxEG0twMVzSmXEEz12z5Fnw1jIQFA==", + "dev": true + }, + "parsejson": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/parsejson/-/parsejson-0.0.3.tgz", + "integrity": "sha1-q343WfIJ7OmUN5c/fQ8fZK4OZKs=", + "dev": true, + "requires": { + "better-assert": "~1.0.0" + } + }, + "parseqs": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/parseqs/-/parseqs-0.0.5.tgz", + "integrity": "sha1-1SCKNzjkZ2bikbouoXNoSSGouJ0=", + "dev": true, + "requires": { + "better-assert": "~1.0.0" + } + }, + "parseuri": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/parseuri/-/parseuri-0.0.5.tgz", + "integrity": "sha1-gCBKUNTbt3m/3G6+J3jZDkvOMgo=", + "dev": true, + "requires": { + "better-assert": "~1.0.0" + } + }, + "parseurl": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.2.tgz", + "integrity": "sha1-/CidTtiZMRlGDBViUyYs3I3mW/M=", + "dev": true + }, + "pascalcase": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/pascalcase/-/pascalcase-0.1.1.tgz", + "integrity": "sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=", + "dev": true + }, + "path-browserify": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-0.0.0.tgz", + "integrity": "sha1-oLhwcpquIUAFt9UDLsLLuw+0RRo=", + "dev": true + }, + "path-dirname": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/path-dirname/-/path-dirname-1.0.2.tgz", + "integrity": "sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA=", + "dev": true + }, + "path-exists": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", + "dev": true + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "path-is-inside": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/path-is-inside/-/path-is-inside-1.0.2.tgz", + "integrity": "sha1-NlQX3t5EQw0cEa9hAn+s8HS9/FM=", + "dev": true + }, + "path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", + "dev": true + }, + "path-parse": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.5.tgz", + "integrity": "sha1-PBrfhx6pzWyUMbbqK9dKD/BVxME=", + "dev": true + }, + "path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=", + "dev": true + }, + "path-type": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-3.0.0.tgz", + "integrity": "sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==", + "dev": true, + "requires": { + "pify": "^3.0.0" + } + }, + "pbkdf2": { + "version": "3.0.16", + "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.0.16.tgz", + "integrity": "sha512-y4CXP3thSxqf7c0qmOF+9UeOTrifiVTIM+u7NWlq+PRsHbr7r7dpCmvzrZxa96JJUNi0Y5w9VqG5ZNeCVMoDcA==", + "dev": true, + "requires": { + "create-hash": "^1.1.2", + "create-hmac": "^1.1.4", + "ripemd160": "^2.0.1", + "safe-buffer": "^5.0.1", + "sha.js": "^2.4.8" + } + }, + "performance-now": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", + "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=", + "dev": true + }, + "pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", + "dev": true + }, + "pinkie": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", + "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", + "dev": true + }, + "pinkie-promise": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", + "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", + "dev": true, + "requires": { + "pinkie": "^2.0.0" + } + }, + "pkg-dir": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-2.0.0.tgz", + "integrity": "sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s=", + "dev": true, + "requires": { + "find-up": "^2.1.0" + } + }, + "portfinder": { + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/portfinder/-/portfinder-1.0.13.tgz", + "integrity": "sha1-uzLs2HwnEErm7kS1o8y/Drsa7ek=", + "dev": true, + "requires": { + "async": "^1.5.2", + "debug": "^2.2.0", + "mkdirp": "0.5.x" + } + }, + "posix-character-classes": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz", + "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=", + "dev": true + }, + "postcss": { + "version": "6.0.23", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-6.0.23.tgz", + "integrity": "sha512-soOk1h6J3VMTZtVeVpv15/Hpdl2cBLX3CAw4TAbkpTJiNPk9YP/zWcD1ND+xEtvyuuvKzbxliTOIyvkSeSJ6ag==", + "dev": true, + "requires": { + "chalk": "^2.4.1", + "source-map": "^0.6.1", + "supports-color": "^5.4.0" + }, + "dependencies": { + "chalk": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", + "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "postcss-import": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-11.1.0.tgz", + "integrity": "sha512-5l327iI75POonjxkXgdRCUS+AlzAdBx4pOvMEhTKTCjb1p8IEeVR9yx3cPbmN7LIWJLbfnIXxAhoB4jpD0c/Cw==", + "dev": true, + "requires": { + "postcss": "^6.0.1", + "postcss-value-parser": "^3.2.3", + "read-cache": "^1.0.0", + "resolve": "^1.1.7" + } + }, + "postcss-load-config": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-2.0.0.tgz", + "integrity": "sha512-V5JBLzw406BB8UIfsAWSK2KSwIJ5yoEIVFb4gVkXci0QdKgA24jLmHZ/ghe/GgX0lJ0/D1uUK1ejhzEY94MChQ==", + "dev": true, + "requires": { + "cosmiconfig": "^4.0.0", + "import-cwd": "^2.0.0" + } + }, + "postcss-loader": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/postcss-loader/-/postcss-loader-2.1.6.tgz", + "integrity": "sha512-hgiWSc13xVQAq25cVw80CH0l49ZKlAnU1hKPOdRrNj89bokRr/bZF2nT+hebPPF9c9xs8c3gw3Fr2nxtmXYnNg==", + "dev": true, + "requires": { + "loader-utils": "^1.1.0", + "postcss": "^6.0.0", + "postcss-load-config": "^2.0.0", + "schema-utils": "^0.4.0" + } + }, + "postcss-url": { + "version": "7.3.2", + "resolved": "https://registry.npmjs.org/postcss-url/-/postcss-url-7.3.2.tgz", + "integrity": "sha512-QMV5mA+pCYZQcUEPQkmor9vcPQ2MT+Ipuu8qdi1gVxbNiIiErEGft+eny1ak19qALoBkccS5AHaCaCDzh7b9MA==", + "dev": true, + "requires": { + "mime": "^1.4.1", + "minimatch": "^3.0.4", + "mkdirp": "^0.5.0", + "postcss": "^6.0.1", + "xxhashjs": "^0.2.1" + } + }, + "postcss-value-parser": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-3.3.0.tgz", + "integrity": "sha1-h/OPnxj3dKSrTIojL1xc6IcqnRU=", + "dev": true + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "dev": true + }, + "preserve": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/preserve/-/preserve-0.2.0.tgz", + "integrity": "sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks=", + "dev": true + }, + "pretty-error": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/pretty-error/-/pretty-error-2.1.1.tgz", + "integrity": "sha1-X0+HyPkeWuPzuoerTPXgOxoX8aM=", + "dev": true, + "requires": { + "renderkid": "^2.0.1", + "utila": "~0.4" + } + }, + "process": { + "version": "0.11.10", + "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", + "integrity": "sha1-czIwDoQBYb2j5podHZGn1LwW8YI=", + "dev": true + }, + "process-nextick-args": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz", + "integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==", + "dev": true + }, + "promise": { + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/promise/-/promise-7.3.1.tgz", + "integrity": "sha512-nolQXZ/4L+bP/UGlkfaIujX9BKxGwmQ9OT4mOt5yvy8iK1h3wqTEJCijzGANTCCl9nWjY41juyAn2K3Q1hLLTg==", + "dev": true, + "optional": true, + "requires": { + "asap": "~2.0.3" + } + }, + "promise-inflight": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/promise-inflight/-/promise-inflight-1.0.1.tgz", + "integrity": "sha1-mEcocL8igTL8vdhoEputEsPAKeM=", + "dev": true + }, + "protractor": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/protractor/-/protractor-5.3.2.tgz", + "integrity": "sha512-pw4uwwiy5lHZjIguxNpkEwJJa7hVz+bJsvaTI+IbXlfn2qXwzbF8eghW/RmrZwE2sGx82I8etb8lVjQ+JrjejA==", + "dev": true, + "requires": { + "@types/node": "^6.0.46", + "@types/q": "^0.0.32", + "@types/selenium-webdriver": "~2.53.39", + "blocking-proxy": "^1.0.0", + "chalk": "^1.1.3", + "glob": "^7.0.3", + "jasmine": "2.8.0", + "jasminewd2": "^2.1.0", + "optimist": "~0.6.0", + "q": "1.4.1", + "saucelabs": "^1.5.0", + "selenium-webdriver": "3.6.0", + "source-map-support": "~0.4.0", + "webdriver-js-extender": "^1.0.0", + "webdriver-manager": "^12.0.6" + }, + "dependencies": { + "@types/node": { + "version": "6.0.114", + "resolved": "https://registry.npmjs.org/@types/node/-/node-6.0.114.tgz", + "integrity": "sha512-5ViC9dwf1VIAtrOFTvOuN04lJgw28eKjuy0Vg2Bd/fSlxKP2feCSkIw04ZgOENL2ywdWrtbkthp1XVLEjJmouw==", + "dev": true + }, + "adm-zip": { + "version": "0.4.11", + "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.4.11.tgz", + "integrity": "sha512-L8vcjDTCOIJk7wFvmlEUN7AsSb8T+2JrdP7KINBjzr24TJ5Mwj590sLu3BC7zNZowvJWa/JtPmD8eJCzdtDWjA==", + "dev": true + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + } + }, + "del": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/del/-/del-2.2.2.tgz", + "integrity": "sha1-wSyYHQZ4RshLyvhiz/kw2Qf/0ag=", + "dev": true, + "requires": { + "globby": "^5.0.0", + "is-path-cwd": "^1.0.0", + "is-path-in-cwd": "^1.0.0", + "object-assign": "^4.0.1", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0", + "rimraf": "^2.2.8" + } + }, + "globby": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-5.0.0.tgz", + "integrity": "sha1-69hGZ8oNuzMLmbz8aOrCvFQ3Dg0=", + "dev": true, + "requires": { + "array-union": "^1.0.1", + "arrify": "^1.0.0", + "glob": "^7.0.3", + "object-assign": "^4.0.1", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" + } + }, + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + }, + "pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", + "dev": true + }, + "source-map-support": { + "version": "0.4.18", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.4.18.tgz", + "integrity": "sha512-try0/JqxPLF9nOjvSta7tVondkP5dwgyLDjVoyMDlmjugT2lRZ1OfsrYTkCd2hkDnJTKRbO/Rl3orm8vlsUzbA==", + "dev": true, + "requires": { + "source-map": "^0.5.6" + } + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + }, + "webdriver-manager": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/webdriver-manager/-/webdriver-manager-12.1.0.tgz", + "integrity": "sha512-oEc5fmkpz6Yh6udhwir5m0eN5mgRPq9P/NU5YWuT3Up5slt6Zz+znhLU7q4+8rwCZz/Qq3Fgpr/4oao7NPCm2A==", + "dev": true, + "requires": { + "adm-zip": "^0.4.9", + "chalk": "^1.1.1", + "del": "^2.2.0", + "glob": "^7.0.3", + "ini": "^1.3.4", + "minimist": "^1.2.0", + "q": "^1.4.1", + "request": "^2.87.0", + "rimraf": "^2.5.2", + "semver": "^5.3.0", + "xml2js": "^0.4.17" + } + } + } + }, + "proxy-addr": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.3.tgz", + "integrity": "sha512-jQTChiCJteusULxjBp8+jftSQE5Obdl3k4cnmLA6WXtK6XFuWRnvVL7aCiBqaLPM8c4ph0S4tKna8XvmIwEnXQ==", + "dev": true, + "requires": { + "forwarded": "~0.1.2", + "ipaddr.js": "1.6.0" + } + }, + "prr": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz", + "integrity": "sha1-0/wRS6BplaRexok/SEzrHXj19HY=", + "dev": true + }, + "pseudomap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", + "integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM=", + "dev": true + }, + "public-encrypt": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/public-encrypt/-/public-encrypt-4.0.2.tgz", + "integrity": "sha512-4kJ5Esocg8X3h8YgJsKAuoesBgB7mqH3eowiDzMUPKiRDDE7E/BqqZD1hnTByIaAFiwAw246YEltSq7tdrOH0Q==", + "dev": true, + "requires": { + "bn.js": "^4.1.0", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "parse-asn1": "^5.0.0", + "randombytes": "^2.0.1" + } + }, + "pump": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pump/-/pump-2.0.1.tgz", + "integrity": "sha512-ruPMNRkN3MHP1cWJc9OWr+T/xDP0jhXYCLfJcBuX54hhfIBnaQmAUMfDcG4DM5UMWByBbJY69QSphm3jtDKIkA==", + "dev": true, + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "pumpify": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/pumpify/-/pumpify-1.5.1.tgz", + "integrity": "sha512-oClZI37HvuUJJxSKKrC17bZ9Cu0ZYhEAGPsPUy9KlMUmv9dKX2o77RUmq7f3XjIxbwyGwYzbzQ1L2Ks8sIradQ==", + "dev": true, + "requires": { + "duplexify": "^3.6.0", + "inherits": "^2.0.3", + "pump": "^2.0.0" + } + }, + "punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "dev": true + }, + "q": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/q/-/q-1.4.1.tgz", + "integrity": "sha1-VXBbzZPF82c1MMLCy8DCs63cKG4=", + "dev": true + }, + "qjobs": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/qjobs/-/qjobs-1.2.0.tgz", + "integrity": "sha512-8YOJEHtxpySA3fFDyCRxA+UUV+fA+rTWnuWvylOK/NCjhY+b4ocCtmu8TtsWb+mYeU+GCHf/S66KZF/AsteKHg==", + "dev": true + }, + "qs": { + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz", + "integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==", + "dev": true + }, + "querystring": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz", + "integrity": "sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA=", + "dev": true + }, + "querystring-es3": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/querystring-es3/-/querystring-es3-0.2.1.tgz", + "integrity": "sha1-nsYfeQSYdXB9aUFFlv2Qek1xHnM=", + "dev": true + }, + "querystringify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.0.0.tgz", + "integrity": "sha512-eTPo5t/4bgaMNZxyjWx6N2a6AuE0mq51KWvpc7nU/MAqixcI6v6KrGUKES0HaomdnolQBBXU/++X6/QQ9KL4tw==", + "dev": true + }, + "randomatic": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/randomatic/-/randomatic-3.0.0.tgz", + "integrity": "sha512-VdxFOIEY3mNO5PtSRkkle/hPJDHvQhK21oa73K4yAc9qmp6N429gAyF1gZMOTMeS0/AYzaV/2Trcef+NaIonSA==", + "dev": true, + "requires": { + "is-number": "^4.0.0", + "kind-of": "^6.0.0", + "math-random": "^1.0.1" + }, + "dependencies": { + "is-number": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-4.0.0.tgz", + "integrity": "sha512-rSklcAIlf1OmFdyAqbnWTLVelsQ58uvZ66S/ZyawjWqIviTWCjg2PzVGw8WUA+nNuPTqb4wgA+NszrJ+08LlgQ==", + "dev": true + } + } + }, + "randombytes": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.0.6.tgz", + "integrity": "sha512-CIQ5OFxf4Jou6uOKe9t1AOgqpeU5fd70A8NPdHSGeYXqXsPe6peOwI0cUl88RWZ6sP1vPMV3avd/R6cZ5/sP1A==", + "dev": true, + "requires": { + "safe-buffer": "^5.1.0" + } + }, + "randomfill": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/randomfill/-/randomfill-1.0.4.tgz", + "integrity": "sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw==", + "dev": true, + "requires": { + "randombytes": "^2.0.5", + "safe-buffer": "^5.1.0" + } + }, + "range-parser": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.0.tgz", + "integrity": "sha1-9JvmtIeJTdxA3MlKMi9hEJLgDV4=", + "dev": true + }, + "raw-body": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.3.2.tgz", + "integrity": "sha1-vNYMd9Prk83gBQKVw/N5OJvIj4k=", + "dev": true, + "requires": { + "bytes": "3.0.0", + "http-errors": "1.6.2", + "iconv-lite": "0.4.19", + "unpipe": "1.0.0" + }, + "dependencies": { + "depd": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.1.tgz", + "integrity": "sha1-V4O04cRZ8G+lyif5kfPQbnoxA1k=", + "dev": true + }, + "http-errors": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.2.tgz", + "integrity": "sha1-CgAsyFcHGSp+eUbO7cERVfYOxzY=", + "dev": true, + "requires": { + "depd": "1.1.1", + "inherits": "2.0.3", + "setprototypeof": "1.0.3", + "statuses": ">= 1.3.1 < 2" + } + }, + "setprototypeof": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.0.3.tgz", + "integrity": "sha1-ZlZ+NwQ+608E2RvWWMDL77VbjgQ=", + "dev": true + } + } + }, + "raw-loader": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/raw-loader/-/raw-loader-0.5.1.tgz", + "integrity": "sha1-DD0L6u2KAclm2Xh793goElKpeao=", + "dev": true + }, + "read-cache": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", + "integrity": "sha1-5mTvMRYRZsl1HNvo28+GtftY93Q=", + "dev": true, + "requires": { + "pify": "^2.3.0" + }, + "dependencies": { + "pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", + "dev": true + } + } + }, + "read-pkg": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-1.1.0.tgz", + "integrity": "sha1-9f+qXs0pyzHAR0vKfXVra7KePyg=", + "dev": true, + "requires": { + "load-json-file": "^1.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^1.0.0" + }, + "dependencies": { + "path-type": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-1.1.0.tgz", + "integrity": "sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" + } + }, + "pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", + "dev": true + } + } + }, + "read-pkg-up": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-1.0.1.tgz", + "integrity": "sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI=", + "dev": true, + "requires": { + "find-up": "^1.0.0", + "read-pkg": "^1.0.0" + }, + "dependencies": { + "find-up": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz", + "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", + "dev": true, + "requires": { + "path-exists": "^2.0.0", + "pinkie-promise": "^2.0.0" + } + }, + "path-exists": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz", + "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", + "dev": true, + "requires": { + "pinkie-promise": "^2.0.0" + } + } + } + }, + "readable-stream": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "readdirp": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-2.1.0.tgz", + "integrity": "sha1-TtCtBg3zBzMAxIRANz9y0cxkLXg=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "minimatch": "^3.0.2", + "readable-stream": "^2.0.2", + "set-immediate-shim": "^1.0.1" + } + }, + "redent": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/redent/-/redent-1.0.0.tgz", + "integrity": "sha1-z5Fqsf1fHxbfsggi3W7H9zDCr94=", + "dev": true, + "requires": { + "indent-string": "^2.1.0", + "strip-indent": "^1.0.1" + } + }, + "reflect-metadata": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.12.tgz", + "integrity": "sha512-n+IyV+nGz3+0q3/Yf1ra12KpCyi001bi4XFxSjbiWWjfqb52iTTtpGXmCCAOWWIAn9KEuFZKGqBERHmrtScZ3A==", + "dev": true + }, + "regenerate": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.4.0.tgz", + "integrity": "sha512-1G6jJVDWrt0rK99kBjvEtziZNCICAuvIPkSiUFIQxVP06RCVpq3dmDo2oi6ABpYaDYaTRr67BEhL8r1wgEZZKg==", + "dev": true + }, + "regenerator-runtime": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", + "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==", + "dev": true + }, + "regex-cache": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/regex-cache/-/regex-cache-0.4.4.tgz", + "integrity": "sha512-nVIZwtCjkC9YgvWkpM55B5rBhBYRZhAaJbgcFYXXsHnbZ9UZI9nnVWYZpBlCqv9ho2eZryPnWrZGsOdPwVWXWQ==", + "dev": true, + "requires": { + "is-equal-shallow": "^0.1.3" + } + }, + "regex-not": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/regex-not/-/regex-not-1.0.2.tgz", + "integrity": "sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A==", + "dev": true, + "requires": { + "extend-shallow": "^3.0.2", + "safe-regex": "^1.1.0" + } + }, + "regexpu-core": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-1.0.0.tgz", + "integrity": "sha1-hqdj9Y7k18L2sQLkdkBQ3n7ZDGs=", + "dev": true, + "requires": { + "regenerate": "^1.2.1", + "regjsgen": "^0.2.0", + "regjsparser": "^0.1.4" + } + }, + "regjsgen": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/regjsgen/-/regjsgen-0.2.0.tgz", + "integrity": "sha1-bAFq3qxVT3WCP+N6wFuS1aTtsfc=", + "dev": true + }, + "regjsparser": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.1.5.tgz", + "integrity": "sha1-fuj4Tcb6eS0/0K4ijSS9lJ6tIFw=", + "dev": true, + "requires": { + "jsesc": "~0.5.0" + }, + "dependencies": { + "jsesc": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz", + "integrity": "sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=", + "dev": true + } + } + }, + "relateurl": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/relateurl/-/relateurl-0.2.7.tgz", + "integrity": "sha1-VNvzd+UUQKypCkzSdGANP/LYiKk=", + "dev": true + }, + "remove-trailing-separator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz", + "integrity": "sha1-wkvOKig62tW8P1jg1IJJuSN52O8=", + "dev": true + }, + "renderkid": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/renderkid/-/renderkid-2.0.1.tgz", + "integrity": "sha1-iYyr/Ivt5Le5ETWj/9Mj5YwNsxk=", + "dev": true, + "requires": { + "css-select": "^1.1.0", + "dom-converter": "~0.1", + "htmlparser2": "~3.3.0", + "strip-ansi": "^3.0.0", + "utila": "~0.3" + }, + "dependencies": { + "utila": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/utila/-/utila-0.3.3.tgz", + "integrity": "sha1-1+jn1+MJEHCSsF+NloiCTWM6QiY=", + "dev": true + } + } + }, + "repeat-element": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/repeat-element/-/repeat-element-1.1.2.tgz", + "integrity": "sha1-7wiaF40Ug7quTZPrmLT55OEdmQo=", + "dev": true + }, + "repeat-string": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=", + "dev": true + }, + "repeating": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", + "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", + "dev": true, + "requires": { + "is-finite": "^1.0.0" + } + }, + "request": { + "version": "2.87.0", + "resolved": "https://registry.npmjs.org/request/-/request-2.87.0.tgz", + "integrity": "sha512-fcogkm7Az5bsS6Sl0sibkbhcKsnyon/jV1kF3ajGmF0c8HrttdKTPRT9hieOaQHA5HEq6r8OyWOo/o781C1tNw==", + "dev": true, + "requires": { + "aws-sign2": "~0.7.0", + "aws4": "^1.6.0", + "caseless": "~0.12.0", + "combined-stream": "~1.0.5", + "extend": "~3.0.1", + "forever-agent": "~0.6.1", + "form-data": "~2.3.1", + "har-validator": "~5.0.3", + "http-signature": "~1.2.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.17", + "oauth-sign": "~0.8.2", + "performance-now": "^2.1.0", + "qs": "~6.5.1", + "safe-buffer": "^5.1.1", + "tough-cookie": "~2.3.3", + "tunnel-agent": "^0.6.0", + "uuid": "^3.1.0" + } + }, + "require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", + "dev": true + }, + "require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true + }, + "require-main-filename": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-1.0.1.tgz", + "integrity": "sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE=", + "dev": true + }, + "requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=", + "dev": true + }, + "resolve": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", + "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "dev": true, + "requires": { + "path-parse": "^1.0.5" + } + }, + "resolve-cwd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-2.0.0.tgz", + "integrity": "sha1-AKn3OHVW4nA46uIyyqNypqWbZlo=", + "dev": true, + "requires": { + "resolve-from": "^3.0.0" + } + }, + "resolve-from": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-3.0.0.tgz", + "integrity": "sha1-six699nWiBvItuZTM17rywoYh0g=", + "dev": true + }, + "resolve-url": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz", + "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=", + "dev": true + }, + "ret": { + "version": "0.1.15", + "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", + "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==", + "dev": true + }, + "retry": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.10.1.tgz", + "integrity": "sha1-52OI0heZLCUnUCQdPTlW/tmNj/Q=", + "dev": true + }, + "right-align": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/right-align/-/right-align-0.1.3.tgz", + "integrity": "sha1-YTObci/mo1FWiSENJOFMlhSGE+8=", + "dev": true, + "optional": true, + "requires": { + "align-text": "^0.1.1" + } + }, + "rimraf": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.2.tgz", + "integrity": "sha512-lreewLK/BlghmxtfH36YYVg1i8IAce4TI7oao75I1g245+6BctqTVQiBP3YUJ9C6DQOXJmkYR9X9fCLtCOJc5w==", + "dev": true, + "requires": { + "glob": "^7.0.5" + } + }, + "ripemd160": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.2.tgz", + "integrity": "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA==", + "dev": true, + "requires": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1" + } + }, + "run-queue": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/run-queue/-/run-queue-1.0.3.tgz", + "integrity": "sha1-6Eg5bwV9Ij8kOGkkYY4laUFh7Ec=", + "dev": true, + "requires": { + "aproba": "^1.1.1" + } + }, + "rxjs": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.2.2.tgz", + "integrity": "sha512-0MI8+mkKAXZUF9vMrEoPnaoHkfzBPP4IGwUYRJhIRJF6/w3uByO1e91bEHn8zd43RdkTMKiooYKmwz7RH6zfOQ==", + "requires": { + "tslib": "^1.9.0" + } + }, + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true + }, + "safe-regex": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", + "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", + "dev": true, + "requires": { + "ret": "~0.1.10" + } + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true + }, + "sass-graph": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/sass-graph/-/sass-graph-2.2.4.tgz", + "integrity": "sha1-E/vWPNHK8JCLn9k0dq1DpR0eC0k=", + "dev": true, + "optional": true, + "requires": { + "glob": "^7.0.0", + "lodash": "^4.0.0", + "scss-tokenizer": "^0.2.3", + "yargs": "^7.0.0" + }, + "dependencies": { + "camelcase": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-3.0.0.tgz", + "integrity": "sha1-MvxLn82vhF/N9+c7uXysImHwqwo=", + "dev": true, + "optional": true + }, + "cliui": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz", + "integrity": "sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0=", + "dev": true, + "optional": true, + "requires": { + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wrap-ansi": "^2.0.0" + } + }, + "y18n": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-3.2.1.tgz", + "integrity": "sha1-bRX7qITAhnnA136I53WegR4H+kE=", + "dev": true, + "optional": true + }, + "yargs": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-7.1.0.tgz", + "integrity": "sha1-a6MY6xaWFyf10oT46gA+jWFU0Mg=", + "dev": true, + "optional": true, + "requires": { + "camelcase": "^3.0.0", + "cliui": "^3.2.0", + "decamelize": "^1.1.1", + "get-caller-file": "^1.0.1", + "os-locale": "^1.4.0", + "read-pkg-up": "^1.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^1.0.1", + "set-blocking": "^2.0.0", + "string-width": "^1.0.2", + "which-module": "^1.0.0", + "y18n": "^3.2.1", + "yargs-parser": "^5.0.0" + } + } + } + }, + "sass-loader": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/sass-loader/-/sass-loader-7.0.3.tgz", + "integrity": "sha512-iaSFtQcGo4SSgDw5Aes5p4VTrA5jCGSA7sGmhPIcOloBlgI1VktM2MUrk2IHHjbNagckXlPz+HWq1vAAPrcYxA==", + "dev": true, + "requires": { + "clone-deep": "^2.0.1", + "loader-utils": "^1.0.1", + "lodash.tail": "^4.1.1", + "neo-async": "^2.5.0", + "pify": "^3.0.0" + } + }, + "saucelabs": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/saucelabs/-/saucelabs-1.5.0.tgz", + "integrity": "sha512-jlX3FGdWvYf4Q3LFfFWS1QvPg3IGCGWxIc8QBFdPTbpTJnt/v17FHXYVAn7C8sHf1yUXo2c7yIM0isDryfYtHQ==", + "dev": true, + "requires": { + "https-proxy-agent": "^2.2.1" + } + }, + "sax": { + "version": "0.5.8", + "resolved": "https://registry.npmjs.org/sax/-/sax-0.5.8.tgz", + "integrity": "sha1-1HLbIo6zMcJQaw6MFVJK25OdEsE=", + "dev": true + }, + "schema-utils": { + "version": "0.4.5", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-0.4.5.tgz", + "integrity": "sha512-yYrjb9TX2k/J1Y5UNy3KYdZq10xhYcF8nMpAW6o3hy6Q8WSIEf9lJHG/ePnOBfziPM3fvQwfOwa13U/Fh8qTfA==", + "dev": true, + "requires": { + "ajv": "^6.1.0", + "ajv-keywords": "^3.1.0" + } + }, + "scss-tokenizer": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/scss-tokenizer/-/scss-tokenizer-0.2.3.tgz", + "integrity": "sha1-jrBtualyMzOCTT9VMGQRSYR85dE=", + "dev": true, + "optional": true, + "requires": { + "js-base64": "^2.1.8", + "source-map": "^0.4.2" + }, + "dependencies": { + "source-map": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.4.4.tgz", + "integrity": "sha1-66T12pwNyZneaAMti092FzZSA2s=", + "dev": true, + "optional": true, + "requires": { + "amdefine": ">=0.0.4" + } + } + } + }, + "select-hose": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/select-hose/-/select-hose-2.0.0.tgz", + "integrity": "sha1-Yl2GWPhlr0Psliv8N2o3NZpJlMo=", + "dev": true + }, + "selenium-webdriver": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/selenium-webdriver/-/selenium-webdriver-3.6.0.tgz", + "integrity": "sha512-WH7Aldse+2P5bbFBO4Gle/nuQOdVwpHMTL6raL3uuBj/vPG07k6uzt3aiahu352ONBr5xXh0hDlM3LhtXPOC4Q==", + "dev": true, + "requires": { + "jszip": "^3.1.3", + "rimraf": "^2.5.4", + "tmp": "0.0.30", + "xml2js": "^0.4.17" + }, + "dependencies": { + "tmp": { + "version": "0.0.30", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.30.tgz", + "integrity": "sha1-ckGdSovn1s51FI/YsyTlk6cRwu0=", + "dev": true, + "requires": { + "os-tmpdir": "~1.0.1" + } + } + } + }, + "selfsigned": { + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/selfsigned/-/selfsigned-1.10.3.tgz", + "integrity": "sha512-vmZenZ+8Al3NLHkWnhBQ0x6BkML1eCP2xEi3JE+f3D9wW9fipD9NNJHYtE9XJM4TsPaHGZJIamrSI6MTg1dU2Q==", + "dev": true, + "requires": { + "node-forge": "0.7.5" + } + }, + "semver": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.5.0.tgz", + "integrity": "sha512-4SJ3dm0WAwWy/NVeioZh5AntkdJoWKxHxcmyP622fOkgHa4z3R0TdBJICINyaSDE6uNwVc8gZr+ZinwZAH4xIA==", + "dev": true + }, + "semver-dsl": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/semver-dsl/-/semver-dsl-1.0.1.tgz", + "integrity": "sha1-02eN5VVeimH2Ke7QJTZq5fJzQKA=", + "dev": true, + "requires": { + "semver": "^5.3.0" + } + }, + "semver-intersect": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/semver-intersect/-/semver-intersect-1.3.1.tgz", + "integrity": "sha1-j6hKnhAovSOeRTDRo+GB5pjYhLo=", + "dev": true, + "requires": { + "semver": "^5.0.0" + } + }, + "send": { + "version": "0.16.2", + "resolved": "https://registry.npmjs.org/send/-/send-0.16.2.tgz", + "integrity": "sha512-E64YFPUssFHEFBvpbbjr44NCLtI1AohxQ8ZSiJjQLskAdKuriYEP6VyGEsRDH8ScozGpkaX1BGvhanqCwkcEZw==", + "dev": true, + "requires": { + "debug": "2.6.9", + "depd": "~1.1.2", + "destroy": "~1.0.4", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "~1.6.2", + "mime": "1.4.1", + "ms": "2.0.0", + "on-finished": "~2.3.0", + "range-parser": "~1.2.0", + "statuses": "~1.4.0" + }, + "dependencies": { + "mime": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.4.1.tgz", + "integrity": "sha512-KI1+qOZu5DcW6wayYHSzR/tXKCDC5Om4s1z2QJjDULzLcmf3DvzS7oluY4HCTrc+9FiKmWUgeNLg7W3uIQvxtQ==", + "dev": true + } + } + }, + "serialize-javascript": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-1.5.0.tgz", + "integrity": "sha512-Ga8c8NjAAp46Br4+0oZ2WxJCwIzwP60Gq1YPgU+39PiTVxyed/iKE/zyZI6+UlVYH5Q4PaQdHhcegIFPZTUfoQ==", + "dev": true + }, + "serve-index": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/serve-index/-/serve-index-1.9.1.tgz", + "integrity": "sha1-03aNabHn2C5c4FD/9bRTvqEqkjk=", + "dev": true, + "requires": { + "accepts": "~1.3.4", + "batch": "0.6.1", + "debug": "2.6.9", + "escape-html": "~1.0.3", + "http-errors": "~1.6.2", + "mime-types": "~2.1.17", + "parseurl": "~1.3.2" + } + }, + "serve-static": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.13.2.tgz", + "integrity": "sha512-p/tdJrO4U387R9oMjb1oj7qSMaMfmOyd4j9hOFoxZe2baQszgHcSWjuya/CiT5kgZZKRudHNOA0pYXOl8rQ5nw==", + "dev": true, + "requires": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.2", + "send": "0.16.2" + } + }, + "set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", + "dev": true + }, + "set-immediate-shim": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/set-immediate-shim/-/set-immediate-shim-1.0.1.tgz", + "integrity": "sha1-SysbJ+uAip+NzEgaWOXlb1mfP2E=", + "dev": true + }, + "set-value": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.0.tgz", + "integrity": "sha512-hw0yxk9GT/Hr5yJEYnHNKYXkIA8mVJgd9ditYZCe16ZczcaELYYcfvaXesNACk2O8O0nTiPQcQhGUQj8JLzeeg==", + "dev": true, + "requires": { + "extend-shallow": "^2.0.1", + "is-extendable": "^0.1.1", + "is-plain-object": "^2.0.3", + "split-string": "^3.0.1" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "setimmediate": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", + "integrity": "sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU=", + "dev": true + }, + "setprototypeof": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz", + "integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==", + "dev": true + }, + "sha.js": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", + "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "shallow-clone": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shallow-clone/-/shallow-clone-1.0.0.tgz", + "integrity": "sha512-oeXreoKR/SyNJtRJMAKPDSvd28OqEwG4eR/xc856cRGBII7gX9lvAqDxusPm0846z/w/hWYjI1NpKwJ00NHzRA==", + "dev": true, + "requires": { + "is-extendable": "^0.1.1", + "kind-of": "^5.0.0", + "mixin-object": "^2.0.1" + }, + "dependencies": { + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } + } + }, + "shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "dev": true, + "requires": { + "shebang-regex": "^1.0.0" + } + }, + "shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", + "dev": true + }, + "signal-exit": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", + "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", + "dev": true + }, + "silent-error": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/silent-error/-/silent-error-1.1.0.tgz", + "integrity": "sha1-IglwbxyFCp8dENDYQJGLRvJuG8k=", + "dev": true, + "requires": { + "debug": "^2.2.0" + } + }, + "slash": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-1.0.0.tgz", + "integrity": "sha1-xB8vbDn8FtHNF61LXYlhFK5HDVU=", + "dev": true + }, + "slide": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/slide/-/slide-1.1.6.tgz", + "integrity": "sha1-VusCfWW00tzmyy4tMsTUr8nh1wc=", + "dev": true + }, + "snapdragon": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz", + "integrity": "sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg==", + "dev": true, + "requires": { + "base": "^0.11.1", + "debug": "^2.2.0", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "map-cache": "^0.2.2", + "source-map": "^0.5.6", + "source-map-resolve": "^0.5.0", + "use": "^3.1.0" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "snapdragon-node": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/snapdragon-node/-/snapdragon-node-2.1.1.tgz", + "integrity": "sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw==", + "dev": true, + "requires": { + "define-property": "^1.0.0", + "isobject": "^3.0.0", + "snapdragon-util": "^3.0.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "snapdragon-util": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/snapdragon-util/-/snapdragon-util-3.0.1.tgz", + "integrity": "sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ==", + "dev": true, + "requires": { + "kind-of": "^3.2.0" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "sntp": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/sntp/-/sntp-1.0.9.tgz", + "integrity": "sha1-ZUEYTMkK7qbG57NeJlkIJEPGYZg=", + "dev": true, + "optional": true, + "requires": { + "hoek": "2.x.x" + } + }, + "socket.io": { + "version": "1.7.3", + "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-1.7.3.tgz", + "integrity": "sha1-uK+cq6AJSeVo42nxMn6pvp6iRhs=", + "dev": true, + "requires": { + "debug": "2.3.3", + "engine.io": "1.8.3", + "has-binary": "0.1.7", + "object-assign": "4.1.0", + "socket.io-adapter": "0.5.0", + "socket.io-client": "1.7.3", + "socket.io-parser": "2.3.1" + }, + "dependencies": { + "debug": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.3.3.tgz", + "integrity": "sha1-QMRT5n5uE8kB3ewxeviYbNqe/4w=", + "dev": true, + "requires": { + "ms": "0.7.2" + } + }, + "ms": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.2.tgz", + "integrity": "sha1-riXPJRKziFodldfwN4aNhDESR2U=", + "dev": true + }, + "object-assign": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.0.tgz", + "integrity": "sha1-ejs9DpgGPUP0wD8uiubNUahog6A=", + "dev": true + } + } + }, + "socket.io-adapter": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-0.5.0.tgz", + "integrity": "sha1-y21LuL7IHhB4uZZ3+c7QBGBmu4s=", + "dev": true, + "requires": { + "debug": "2.3.3", + "socket.io-parser": "2.3.1" + }, + "dependencies": { + "debug": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.3.3.tgz", + "integrity": "sha1-QMRT5n5uE8kB3ewxeviYbNqe/4w=", + "dev": true, + "requires": { + "ms": "0.7.2" + } + }, + "ms": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.2.tgz", + "integrity": "sha1-riXPJRKziFodldfwN4aNhDESR2U=", + "dev": true + } + } + }, + "socket.io-client": { + "version": "1.7.3", + "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-1.7.3.tgz", + "integrity": "sha1-sw6GqhDV7zVGYBwJzeR2Xjgdo3c=", + "dev": true, + "requires": { + "backo2": "1.0.2", + "component-bind": "1.0.0", + "component-emitter": "1.2.1", + "debug": "2.3.3", + "engine.io-client": "1.8.3", + "has-binary": "0.1.7", + "indexof": "0.0.1", + "object-component": "0.0.3", + "parseuri": "0.0.5", + "socket.io-parser": "2.3.1", + "to-array": "0.1.4" + }, + "dependencies": { + "debug": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.3.3.tgz", + "integrity": "sha1-QMRT5n5uE8kB3ewxeviYbNqe/4w=", + "dev": true, + "requires": { + "ms": "0.7.2" + } + }, + "ms": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.2.tgz", + "integrity": "sha1-riXPJRKziFodldfwN4aNhDESR2U=", + "dev": true + } + } + }, + "socket.io-parser": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-2.3.1.tgz", + "integrity": "sha1-3VMgJRA85Clpcya+/WQAX8/ltKA=", + "dev": true, + "requires": { + "component-emitter": "1.1.2", + "debug": "2.2.0", + "isarray": "0.0.1", + "json3": "3.3.2" + }, + "dependencies": { + "component-emitter": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.1.2.tgz", + "integrity": "sha1-KWWU8nU9qmOZbSrwjRWpURbJrsM=", + "dev": true + }, + "debug": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "integrity": "sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=", + "dev": true, + "requires": { + "ms": "0.7.1" + } + }, + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", + "dev": true + }, + "ms": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "integrity": "sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=", + "dev": true + } + } + }, + "sockjs": { + "version": "0.3.19", + "resolved": "https://registry.npmjs.org/sockjs/-/sockjs-0.3.19.tgz", + "integrity": "sha512-V48klKZl8T6MzatbLlzzRNhMepEys9Y4oGFpypBFFn1gLI/QQ9HtLLyWJNbPlwGLelOVOEijUbTTJeLLI59jLw==", + "dev": true, + "requires": { + "faye-websocket": "^0.10.0", + "uuid": "^3.0.1" + } + }, + "sockjs-client": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/sockjs-client/-/sockjs-client-1.1.5.tgz", + "integrity": "sha1-G7fA9yIsQPQq3xT0RCy9Eml3GoM=", + "dev": true, + "requires": { + "debug": "^2.6.6", + "eventsource": "0.1.6", + "faye-websocket": "~0.11.0", + "inherits": "^2.0.1", + "json3": "^3.3.2", + "url-parse": "^1.1.8" + }, + "dependencies": { + "faye-websocket": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.1.tgz", + "integrity": "sha1-8O/hjE9W5PQK/H4Gxxn9XuYYjzg=", + "dev": true, + "requires": { + "websocket-driver": ">=0.5.1" + } + } + } + }, + "source-list-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/source-list-map/-/source-list-map-2.0.0.tgz", + "integrity": "sha512-I2UmuJSRr/T8jisiROLU3A3ltr+swpniSmNPI4Ml3ZCX6tVnDsuZzK7F2hl5jTqbZBWCEKlj5HRQiPExXLgE8A==", + "dev": true + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + }, + "source-map-resolve": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.2.tgz", + "integrity": "sha512-MjqsvNwyz1s0k81Goz/9vRBe9SZdB09Bdw+/zYyO+3CuPk6fouTaxscHkgtE8jKvf01kVfl8riHzERQ/kefaSA==", + "dev": true, + "requires": { + "atob": "^2.1.1", + "decode-uri-component": "^0.2.0", + "resolve-url": "^0.2.1", + "source-map-url": "^0.4.0", + "urix": "^0.1.0" + } + }, + "source-map-support": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.6.tgz", + "integrity": "sha512-N4KXEz7jcKqPf2b2vZF11lQIz9W5ZMuUcIOGj243lduidkf2fjkVKJS9vNxVWn3u/uxX38AcE8U9nnH9FPcq+g==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "source-map-url": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/source-map-url/-/source-map-url-0.4.0.tgz", + "integrity": "sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=", + "dev": true + }, + "spdx-correct": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.0.0.tgz", + "integrity": "sha512-N19o9z5cEyc8yQQPukRCZ9EUmb4HUpnrmaL/fxS2pBo2jbfcFRVuFZ/oFC+vZz0MNNk0h80iMn5/S6qGZOL5+g==", + "dev": true, + "requires": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-exceptions": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.1.0.tgz", + "integrity": "sha512-4K1NsmrlCU1JJgUrtgEeTVyfx8VaYea9J9LvARxhbHtVtohPs/gFGG5yy49beySjlIMhhXZ4QqujIZEfS4l6Cg==", + "dev": true + }, + "spdx-expression-parse": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.0.tgz", + "integrity": "sha512-Yg6D3XpRD4kkOmTpdgbUiEJFKghJH03fiC1OPll5h/0sO6neh2jqRDVHOQ4o/LMea0tgCkbMgea5ip/e+MkWyg==", + "dev": true, + "requires": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-license-ids": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.0.tgz", + "integrity": "sha512-2+EPwgbnmOIl8HjGBXXMd9NAu02vLjOO1nWw4kmeRDFyHn+M/ETfHxQUK0oXg8ctgVnl9t3rosNVsZ1jG61nDA==", + "dev": true + }, + "spdy": { + "version": "3.4.7", + "resolved": "https://registry.npmjs.org/spdy/-/spdy-3.4.7.tgz", + "integrity": "sha1-Qv9B7OXMD5mjpsKKq7c/XDsDrLw=", + "dev": true, + "requires": { + "debug": "^2.6.8", + "handle-thing": "^1.2.5", + "http-deceiver": "^1.2.7", + "safe-buffer": "^5.0.1", + "select-hose": "^2.0.0", + "spdy-transport": "^2.0.18" + } + }, + "spdy-transport": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/spdy-transport/-/spdy-transport-2.1.0.tgz", + "integrity": "sha512-bpUeGpZcmZ692rrTiqf9/2EUakI6/kXX1Rpe0ib/DyOzbiexVfXkw6GnvI9hVGvIwVaUhkaBojjCZwLNRGQg1g==", + "dev": true, + "requires": { + "debug": "^2.6.8", + "detect-node": "^2.0.3", + "hpack.js": "^2.1.6", + "obuf": "^1.1.1", + "readable-stream": "^2.2.9", + "safe-buffer": "^5.0.1", + "wbuf": "^1.7.2" + } + }, + "split-string": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/split-string/-/split-string-3.1.0.tgz", + "integrity": "sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==", + "dev": true, + "requires": { + "extend-shallow": "^3.0.0" + } + }, + "sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", + "dev": true + }, + "sshpk": { + "version": "1.14.2", + "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.14.2.tgz", + "integrity": "sha1-xvxhZIo9nE52T9P8306hBeSSupg=", + "dev": true, + "requires": { + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "safer-buffer": "^2.0.2", + "tweetnacl": "~0.14.0" + } + }, + "ssri": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-5.3.0.tgz", + "integrity": "sha512-XRSIPqLij52MtgoQavH/x/dU1qVKtWUAAZeOHsR9c2Ddi4XerFy3mc1alf+dLJKl9EUIm/Ht+EowFkTUOA6GAQ==", + "dev": true, + "requires": { + "safe-buffer": "^5.1.1" + } + }, + "static-extend": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz", + "integrity": "sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY=", + "dev": true, + "requires": { + "define-property": "^0.2.5", + "object-copy": "^0.1.0" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + } + } + }, + "stats-webpack-plugin": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/stats-webpack-plugin/-/stats-webpack-plugin-0.6.2.tgz", + "integrity": "sha1-LFlJtTHgf4eojm6k3PrFOqjHWis=", + "dev": true, + "requires": { + "lodash": "^4.17.4" + } + }, + "statuses": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.4.0.tgz", + "integrity": "sha512-zhSCtt8v2NDrRlPQpCNtw/heZLtfUDqxBM1udqikb/Hbk52LK4nQSwr10u77iopCW5LsyHpuXS0GnEc48mLeew==", + "dev": true + }, + "stdout-stream": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/stdout-stream/-/stdout-stream-1.4.0.tgz", + "integrity": "sha1-osfIWH5U2UJ+qe2zrD8s1SLfN4s=", + "dev": true, + "optional": true, + "requires": { + "readable-stream": "^2.0.1" + } + }, + "stream-browserify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-2.0.1.tgz", + "integrity": "sha1-ZiZu5fm9uZQKTkUUyvtDu3Hlyds=", + "dev": true, + "requires": { + "inherits": "~2.0.1", + "readable-stream": "^2.0.2" + } + }, + "stream-each": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/stream-each/-/stream-each-1.2.2.tgz", + "integrity": "sha512-mc1dbFhGBxvTM3bIWmAAINbqiuAk9TATcfIQC8P+/+HJefgaiTlMn2dHvkX8qlI12KeYKSQ1Ua9RrIqrn1VPoA==", + "dev": true, + "requires": { + "end-of-stream": "^1.1.0", + "stream-shift": "^1.0.0" + } + }, + "stream-http": { + "version": "2.8.3", + "resolved": "https://registry.npmjs.org/stream-http/-/stream-http-2.8.3.tgz", + "integrity": "sha512-+TSkfINHDo4J+ZobQLWiMouQYB+UVYFttRA94FpEzzJ7ZdqcL4uUUQ7WkdkI4DSozGmgBUE/a47L+38PenXhUw==", + "dev": true, + "requires": { + "builtin-status-codes": "^3.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.3.6", + "to-arraybuffer": "^1.0.0", + "xtend": "^4.0.0" + } + }, + "stream-shift": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.0.tgz", + "integrity": "sha1-1cdSgl5TZ+eG944Y5EXqIjoVWVI=", + "dev": true + }, + "string-width": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", + "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", + "dev": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "stringstream": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/stringstream/-/stringstream-0.0.6.tgz", + "integrity": "sha512-87GEBAkegbBcweToUrdzf3eLhWNg06FJTebl4BVJz/JgWy8CvEr9dRtX5qWphiynMSQlxxi+QqN0z5T32SLlhA==", + "dev": true, + "optional": true + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "strip-bom": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz", + "integrity": "sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4=", + "dev": true, + "requires": { + "is-utf8": "^0.2.0" + } + }, + "strip-eof": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", + "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=", + "dev": true + }, + "strip-indent": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-1.0.1.tgz", + "integrity": "sha1-DHlipq3vp7vUrDZkYKY4VSrhoKI=", + "dev": true, + "requires": { + "get-stdin": "^4.0.1" + } + }, + "style-loader": { + "version": "0.21.0", + "resolved": "https://registry.npmjs.org/style-loader/-/style-loader-0.21.0.tgz", + "integrity": "sha512-T+UNsAcl3Yg+BsPKs1vd22Fr8sVT+CJMtzqc6LEw9bbJZb43lm9GoeIfUcDEefBSWC0BhYbcdupV1GtI4DGzxg==", + "dev": true, + "requires": { + "loader-utils": "^1.1.0", + "schema-utils": "^0.4.5" + } + }, + "stylus": { + "version": "0.54.5", + "resolved": "https://registry.npmjs.org/stylus/-/stylus-0.54.5.tgz", + "integrity": "sha1-QrlWCTHKcJDOhRWnmLqeaqPW3Hk=", + "dev": true, + "requires": { + "css-parse": "1.7.x", + "debug": "*", + "glob": "7.0.x", + "mkdirp": "0.5.x", + "sax": "0.5.x", + "source-map": "0.1.x" + }, + "dependencies": { + "glob": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.0.6.tgz", + "integrity": "sha1-IRuvr0nlJbjNkyYNFKsTYVKz9Xo=", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.2", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "source-map": { + "version": "0.1.43", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.1.43.tgz", + "integrity": "sha1-wkvBRspRfBRx9drL4lcbK3+eM0Y=", + "dev": true, + "requires": { + "amdefine": ">=0.0.4" + } + } + } + }, + "stylus-loader": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/stylus-loader/-/stylus-loader-3.0.2.tgz", + "integrity": "sha512-+VomPdZ6a0razP+zinir61yZgpw2NfljeSsdUF5kJuEzlo3khXhY19Fn6l8QQz1GRJGtMCo8nG5C04ePyV7SUA==", + "dev": true, + "requires": { + "loader-utils": "^1.0.2", + "lodash.clonedeep": "^4.5.0", + "when": "~3.6.x" + } + }, + "supports-color": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.4.0.tgz", + "integrity": "sha512-zjaXglF5nnWpsq470jSv6P9DwPvgLkuapYmfDm3JWOm0vkNTVF2tI4UrN2r6jH1qM/uc/WtxYY1hYoA2dOKj5w==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + }, + "symbol-observable": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/symbol-observable/-/symbol-observable-1.2.0.tgz", + "integrity": "sha512-e900nM8RRtGhlV36KGEU9k65K3mPb1WV70OdjfxlG2EAuM1noi/E/BaW/uMhL7bPEssK8QV57vN3esixjUvcXQ==", + "dev": true + }, + "tapable": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-1.0.0.tgz", + "integrity": "sha512-dQRhbNQkRnaqauC7WqSJ21EEksgT0fYZX2lqXzGkpo8JNig9zGZTYoMGvyI2nWmXlE2VSVXVDu7wLVGu/mQEsg==", + "dev": true + }, + "tar": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/tar/-/tar-2.2.1.tgz", + "integrity": "sha1-jk0qJWwOIYXGsYrWlK7JaLg8sdE=", + "dev": true, + "optional": true, + "requires": { + "block-stream": "*", + "fstream": "^1.0.2", + "inherits": "2" + } + }, + "text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", + "dev": true + }, + "through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", + "dev": true + }, + "through2": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.3.tgz", + "integrity": "sha1-AARWmzfHx0ujnEPzzteNGtlBQL4=", + "dev": true, + "requires": { + "readable-stream": "^2.1.5", + "xtend": "~4.0.1" + } + }, + "thunky": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/thunky/-/thunky-1.0.2.tgz", + "integrity": "sha1-qGLgGOP7HqLsP85dVWBc9X8kc3E=", + "dev": true + }, + "timers-browserify": { + "version": "2.0.10", + "resolved": "https://registry.npmjs.org/timers-browserify/-/timers-browserify-2.0.10.tgz", + "integrity": "sha512-YvC1SV1XdOUaL6gx5CoGroT3Gu49pK9+TZ38ErPldOWW4j49GI1HKs9DV+KGq/w6y+LZ72W1c8cKz2vzY+qpzg==", + "dev": true, + "requires": { + "setimmediate": "^1.0.4" + } + }, + "tmp": { + "version": "0.0.31", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.31.tgz", + "integrity": "sha1-jzirlDjhcxXl29izZX6L+yd65Kc=", + "dev": true, + "requires": { + "os-tmpdir": "~1.0.1" + } + }, + "to-array": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/to-array/-/to-array-0.1.4.tgz", + "integrity": "sha1-F+bBH3PdTz10zaek/zI46a2b+JA=", + "dev": true + }, + "to-arraybuffer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz", + "integrity": "sha1-fSKbH8xjfkZsoIEYCDanqr/4P0M=", + "dev": true + }, + "to-fast-properties": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-1.0.3.tgz", + "integrity": "sha1-uDVx+k2MJbguIxsG46MFXeTKGkc=", + "dev": true + }, + "to-object-path": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/to-object-path/-/to-object-path-0.3.0.tgz", + "integrity": "sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "to-regex": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/to-regex/-/to-regex-3.0.2.tgz", + "integrity": "sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw==", + "dev": true, + "requires": { + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "regex-not": "^1.0.2", + "safe-regex": "^1.1.0" + } + }, + "to-regex-range": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-2.1.1.tgz", + "integrity": "sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=", + "dev": true, + "requires": { + "is-number": "^3.0.0", + "repeat-string": "^1.6.1" + } + }, + "toposort": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/toposort/-/toposort-1.0.7.tgz", + "integrity": "sha1-LmhELZ9k7HILjMieZEOsbKqVACk=", + "dev": true + }, + "tough-cookie": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.3.4.tgz", + "integrity": "sha512-TZ6TTfI5NtZnuyy/Kecv+CnoROnyXn2DN97LontgQpCwsX2XyLYCC0ENhYkehSOwAp8rTQKc/NUIF7BkQ5rKLA==", + "dev": true, + "requires": { + "punycode": "^1.4.1" + }, + "dependencies": { + "punycode": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", + "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=", + "dev": true + } + } + }, + "tree-kill": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.0.tgz", + "integrity": "sha512-DlX6dR0lOIRDFxI0mjL9IYg6OTncLm/Zt+JiBhE5OlFcAR8yc9S7FFXU9so0oda47frdM/JFsk7UjNt9vscKcg==", + "dev": true + }, + "trim-newlines": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-1.0.0.tgz", + "integrity": "sha1-WIeWa7WCpFA6QetST301ARgVphM=", + "dev": true + }, + "trim-right": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", + "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=", + "dev": true + }, + "true-case-path": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/true-case-path/-/true-case-path-1.0.2.tgz", + "integrity": "sha1-fskRMJJHZsf1c74wIMNPj9/QDWI=", + "dev": true, + "optional": true, + "requires": { + "glob": "^6.0.4" + }, + "dependencies": { + "glob": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-6.0.4.tgz", + "integrity": "sha1-DwiGD2oVUSey+t1PnOJLGqtuTSI=", + "dev": true, + "optional": true, + "requires": { + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "2 || 3", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + } + } + }, + "ts-node": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-5.0.1.tgz", + "integrity": "sha512-XK7QmDcNHVmZkVtkiwNDWiERRHPyU8nBqZB1+iv2UhOG0q3RQ9HsZ2CMqISlFbxjrYFGfG2mX7bW4dAyxBVzUw==", + "dev": true, + "requires": { + "arrify": "^1.0.0", + "chalk": "^2.3.0", + "diff": "^3.1.0", + "make-error": "^1.1.1", + "minimist": "^1.2.0", + "mkdirp": "^0.5.1", + "source-map-support": "^0.5.3", + "yn": "^2.0.0" + }, + "dependencies": { + "chalk": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", + "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + } + } + }, + "tsickle": { + "version": "0.29.0", + "resolved": "https://registry.npmjs.org/tsickle/-/tsickle-0.29.0.tgz", + "integrity": "sha512-JpID0Lv8/irRtPmqJJxb5fCwfZhjZeKmav9Zna7UjqVuJoSbI49Wue/c2PPybX1SbRrjl7bbI/JsCl0dSUJygA==", + "dev": true, + "requires": { + "minimist": "^1.2.0", + "mkdirp": "^0.5.1", + "source-map": "^0.6.0", + "source-map-support": "^0.5.0" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "tslib": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.9.3.tgz", + "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" + }, + "tslint": { + "version": "5.9.1", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.9.1.tgz", + "integrity": "sha1-ElX4ej/1frCw4fDmEKi0dIBGya4=", + "dev": true, + "requires": { + "babel-code-frame": "^6.22.0", + "builtin-modules": "^1.1.1", + "chalk": "^2.3.0", + "commander": "^2.12.1", + "diff": "^3.2.0", + "glob": "^7.1.1", + "js-yaml": "^3.7.0", + "minimatch": "^3.0.4", + "resolve": "^1.3.2", + "semver": "^5.3.0", + "tslib": "^1.8.0", + "tsutils": "^2.12.1" + }, + "dependencies": { + "chalk": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", + "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + } + } + }, + "tsutils": { + "version": "2.28.0", + "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-2.28.0.tgz", + "integrity": "sha512-bh5nAtW0tuhvOJnx1GLRn5ScraRLICGyJV5wJhtRWOLsxW70Kk5tZtpK3O/hW6LDnqKS9mlUMPZj9fEMJ0gxqA==", + "dev": true, + "requires": { + "tslib": "^1.8.1" + } + }, + "tty-browserify": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.0.tgz", + "integrity": "sha1-oVe6QC2iTpv5V/mqadUk7tQpAaY=", + "dev": true + }, + "tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", + "dev": true, + "requires": { + "safe-buffer": "^5.0.1" + } + }, + "tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=", + "dev": true, + "optional": true + }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "dev": true, + "requires": { + "prelude-ls": "~1.1.2" + } + }, + "type-is": { + "version": "1.6.16", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.16.tgz", + "integrity": "sha512-HRkVv/5qY2G6I8iab9cI7v1bOIdhm94dVjQCPFElW9W+3GeDOSHmy2EBYe4VTApuzolPcmgFTN3ftVJRKR2J9Q==", + "dev": true, + "requires": { + "media-typer": "0.3.0", + "mime-types": "~2.1.18" + } + }, + "typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", + "dev": true + }, + "typescript": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-2.7.2.tgz", + "integrity": "sha512-p5TCYZDAO0m4G344hD+wx/LATebLWZNkkh2asWUFqSsD2OrDNhbAHuSjobrmsUmdzjJjEeZVU9g1h3O6vpstnw==", + "dev": true + }, + "uglify-js": { + "version": "3.4.5", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.4.5.tgz", + "integrity": "sha512-Fm52gLqJqFBnT+Sn411NPDnsgaWiYeRLw42x7Va/mS8TKgaepwoGY7JLXHSEef3d3PmdFXSz1Zx7KMLL89E2QA==", + "dev": true, + "requires": { + "commander": "~2.16.0", + "source-map": "~0.6.1" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "uglify-to-browserify": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz", + "integrity": "sha1-bgkk1r2mta/jSeOabWMoUKD4grc=", + "dev": true, + "optional": true + }, + "uglifyjs-webpack-plugin": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/uglifyjs-webpack-plugin/-/uglifyjs-webpack-plugin-1.2.7.tgz", + "integrity": "sha512-1VicfKhCYHLS8m1DCApqBhoulnASsEoJ/BvpUpP4zoNAPpKzdH+ghk0olGJMmwX2/jprK2j3hAHdUbczBSy2FA==", + "dev": true, + "requires": { + "cacache": "^10.0.4", + "find-cache-dir": "^1.0.0", + "schema-utils": "^0.4.5", + "serialize-javascript": "^1.4.0", + "source-map": "^0.6.1", + "uglify-es": "^3.3.4", + "webpack-sources": "^1.1.0", + "worker-farm": "^1.5.2" + }, + "dependencies": { + "commander": { + "version": "2.13.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.13.0.tgz", + "integrity": "sha512-MVuS359B+YzaWqjCL/c+22gfryv+mCBPHAv3zyVI2GN8EY6IRP8VwtasXn8jyyhvvq84R4ImN1OKRtcbIasjYA==", + "dev": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + }, + "uglify-es": { + "version": "3.3.9", + "resolved": "https://registry.npmjs.org/uglify-es/-/uglify-es-3.3.9.tgz", + "integrity": "sha512-r+MU0rfv4L/0eeW3xZrd16t4NZfK8Ld4SWVglYBb7ez5uXFWHuVRs6xCTrf1yirs9a4j4Y27nn7SRfO6v67XsQ==", + "dev": true, + "requires": { + "commander": "~2.13.0", + "source-map": "~0.6.1" + } + } + } + }, + "ultron": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/ultron/-/ultron-1.0.2.tgz", + "integrity": "sha1-rOEWq1V80Zc4ak6I9GhTeMiy5Po=", + "dev": true + }, + "union-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.0.tgz", + "integrity": "sha1-XHHDTLW61dzr4+oM0IIHulqhrqQ=", + "dev": true, + "requires": { + "arr-union": "^3.1.0", + "get-value": "^2.0.6", + "is-extendable": "^0.1.1", + "set-value": "^0.4.3" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + }, + "set-value": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-0.4.3.tgz", + "integrity": "sha1-fbCPnT0i3H945Trzw79GZuzfzPE=", + "dev": true, + "requires": { + "extend-shallow": "^2.0.1", + "is-extendable": "^0.1.1", + "is-plain-object": "^2.0.1", + "to-object-path": "^0.3.0" + } + } + } + }, + "unique-filename": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-1.1.0.tgz", + "integrity": "sha1-0F8v5AMlYIcfMOk8vnNe6iAVFPM=", + "dev": true, + "requires": { + "unique-slug": "^2.0.0" + } + }, + "unique-slug": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-2.0.0.tgz", + "integrity": "sha1-22Z258fMBimHj/GWCXx4hVrp9Ks=", + "dev": true, + "requires": { + "imurmurhash": "^0.1.4" + } + }, + "unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=", + "dev": true + }, + "unset-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unset-value/-/unset-value-1.0.0.tgz", + "integrity": "sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=", + "dev": true, + "requires": { + "has-value": "^0.3.1", + "isobject": "^3.0.0" + }, + "dependencies": { + "has-value": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/has-value/-/has-value-0.3.1.tgz", + "integrity": "sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=", + "dev": true, + "requires": { + "get-value": "^2.0.3", + "has-values": "^0.1.4", + "isobject": "^2.0.0" + }, + "dependencies": { + "isobject": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", + "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", + "dev": true, + "requires": { + "isarray": "1.0.0" + } + } + } + }, + "has-values": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/has-values/-/has-values-0.1.4.tgz", + "integrity": "sha1-bWHeldkd/Km5oCCJrThL/49it3E=", + "dev": true + } + } + }, + "upath": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/upath/-/upath-1.1.0.tgz", + "integrity": "sha512-bzpH/oBhoS/QI/YtbkqCg6VEiPYjSZtrHQM6/QnJS6OL9pKUFLqb3aFh4Scvwm45+7iAgiMkLhSbaZxUqmrprw==", + "dev": true + }, + "upper-case": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/upper-case/-/upper-case-1.1.3.tgz", + "integrity": "sha1-9rRQHC7EzdJrp4vnIilh3ndiFZg=", + "dev": true + }, + "uri-js": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-3.0.2.tgz", + "integrity": "sha1-+QuFhQf4HepNz7s8TD2/orVX+qo=", + "dev": true, + "requires": { + "punycode": "^2.1.0" + } + }, + "urix": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/urix/-/urix-0.1.0.tgz", + "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=", + "dev": true + }, + "url": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/url/-/url-0.11.0.tgz", + "integrity": "sha1-ODjpfPxgUh63PFJajlW/3Z4uKPE=", + "dev": true, + "requires": { + "punycode": "1.3.2", + "querystring": "0.2.0" + }, + "dependencies": { + "punycode": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz", + "integrity": "sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0=", + "dev": true + } + } + }, + "url-join": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/url-join/-/url-join-4.0.0.tgz", + "integrity": "sha1-TTNA6AfTdzvamZH4MFrNzCpmXSo=", + "dev": true + }, + "url-loader": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/url-loader/-/url-loader-1.0.1.tgz", + "integrity": "sha512-rAonpHy7231fmweBKUFe0bYnlGDty77E+fm53NZdij7j/YOpyGzc7ttqG1nAXl3aRs0k41o0PC3TvGXQiw2Zvw==", + "dev": true, + "requires": { + "loader-utils": "^1.1.0", + "mime": "^2.0.3", + "schema-utils": "^0.4.3" + }, + "dependencies": { + "mime": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.3.1.tgz", + "integrity": "sha512-OEUllcVoydBHGN1z84yfQDimn58pZNNNXgZlHXSboxMlFvgI6MXSWpWKpFRra7H1HxpVhHTkrghfRW49k6yjeg==", + "dev": true + } + } + }, + "url-parse": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.4.1.tgz", + "integrity": "sha512-x95Td74QcvICAA0+qERaVkRpTGKyBHHYdwL2LXZm5t/gBtCB9KQSO/0zQgSTYEV1p0WcvSg79TLNPSvd5IDJMQ==", + "dev": true, + "requires": { + "querystringify": "^2.0.0", + "requires-port": "^1.0.0" + } + }, + "use": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/use/-/use-3.1.1.tgz", + "integrity": "sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==", + "dev": true + }, + "useragent": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/useragent/-/useragent-2.3.0.tgz", + "integrity": "sha512-4AoH4pxuSvHCjqLO04sU6U/uE65BYza8l/KKBS0b0hnUPWi+cQ2BpeTEwejCSx9SPV5/U03nniDTrWx5NrmKdw==", + "dev": true, + "requires": { + "lru-cache": "4.1.x", + "tmp": "0.0.x" + } + }, + "util": { + "version": "0.10.4", + "resolved": "https://registry.npmjs.org/util/-/util-0.10.4.tgz", + "integrity": "sha512-0Pm9hTQ3se5ll1XihRic3FDIku70C+iHUdT/W926rSgHV5QgXsYbKZN8MSC3tJtSkhuROzvsQjAaFENRXr+19A==", + "dev": true, + "requires": { + "inherits": "2.0.3" + } + }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", + "dev": true + }, + "util.promisify": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/util.promisify/-/util.promisify-1.0.0.tgz", + "integrity": "sha512-i+6qA2MPhvoKLuxnJNpXAGhg7HphQOSUq2LKMZD0m15EiskXUkMvKdF4Uui0WYeCUGea+o2cw/ZuwehtfsrNkA==", + "dev": true, + "requires": { + "define-properties": "^1.1.2", + "object.getownpropertydescriptors": "^2.0.3" + } + }, + "utila": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/utila/-/utila-0.4.0.tgz", + "integrity": "sha1-ihagXURWV6Oupe7MWxKk+lN5dyw=", + "dev": true + }, + "utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=", + "dev": true + }, + "uuid": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.2.tgz", + "integrity": "sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==", + "dev": true + }, + "validate-npm-package-license": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.3.tgz", + "integrity": "sha512-63ZOUnL4SIXj4L0NixR3L1lcjO38crAbgrTpl28t8jjrfuiOBL5Iygm+60qPs/KsZGzPNg6Smnc/oY16QTjF0g==", + "dev": true, + "requires": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "validate-npm-package-name": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-3.0.0.tgz", + "integrity": "sha1-X6kS2B630MdK/BQN5zF/DKffQ34=", + "dev": true, + "requires": { + "builtins": "^1.0.3" + } + }, + "vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=", + "dev": true + }, + "verror": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", + "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", + "dev": true, + "requires": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + } + }, + "vm-browserify": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-0.0.4.tgz", + "integrity": "sha1-XX6kW7755Kb/ZflUOOCofDV9WnM=", + "dev": true, + "requires": { + "indexof": "0.0.1" + } + }, + "void-elements": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/void-elements/-/void-elements-2.0.1.tgz", + "integrity": "sha1-wGavtYK7HLQSjWDqkjkulNXp2+w=", + "dev": true + }, + "watchpack": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-1.6.0.tgz", + "integrity": "sha512-i6dHe3EyLjMmDlU1/bGQpEw25XSjkJULPuAVKCbNRefQVq48yXKUpwg538F7AZTf9kyr57zj++pQFltUa5H7yA==", + "dev": true, + "requires": { + "chokidar": "^2.0.2", + "graceful-fs": "^4.1.2", + "neo-async": "^2.5.0" + } + }, + "wbuf": { + "version": "1.7.3", + "resolved": "https://registry.npmjs.org/wbuf/-/wbuf-1.7.3.tgz", + "integrity": "sha512-O84QOnr0icsbFGLS0O3bI5FswxzRr8/gHwWkDlQFskhSPryQXvrTMxjxGP4+iWYoauLoBvfDpkrOauZ+0iZpDA==", + "dev": true, + "requires": { + "minimalistic-assert": "^1.0.0" + } + }, + "webassemblyjs": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/webassemblyjs/-/webassemblyjs-1.4.3.tgz", + "integrity": "sha512-4lOV1Lv6olz0PJkDGQEp82HempAn147e6BXijWDzz9g7/2nSebVP9GVg62Fz5ZAs55mxq13GA0XLyvY8XkyDjg==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.4.3", + "@webassemblyjs/validation": "1.4.3", + "@webassemblyjs/wasm-parser": "1.4.3", + "@webassemblyjs/wast-parser": "1.4.3", + "long": "^3.2.0" + } + }, + "webdriver-js-extender": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/webdriver-js-extender/-/webdriver-js-extender-1.0.0.tgz", + "integrity": "sha1-gcUzqeM9W/tZe05j4s2yW1R3dRU=", + "dev": true, + "requires": { + "@types/selenium-webdriver": "^2.53.35", + "selenium-webdriver": "^2.53.2" + }, + "dependencies": { + "sax": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/sax/-/sax-0.6.1.tgz", + "integrity": "sha1-VjsZx8HeiS4Jv8Ty/DDjwn8JUrk=", + "dev": true + }, + "selenium-webdriver": { + "version": "2.53.3", + "resolved": "https://registry.npmjs.org/selenium-webdriver/-/selenium-webdriver-2.53.3.tgz", + "integrity": "sha1-0p/1qVff8aG0ncRXdW5OS/vc4IU=", + "dev": true, + "requires": { + "adm-zip": "0.4.4", + "rimraf": "^2.2.8", + "tmp": "0.0.24", + "ws": "^1.0.1", + "xml2js": "0.4.4" + } + }, + "tmp": { + "version": "0.0.24", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.24.tgz", + "integrity": "sha1-1qXhmNFKmDXMby18PZ4wJCjIzxI=", + "dev": true + }, + "xml2js": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.4.tgz", + "integrity": "sha1-MREBAAMAiuGSQOuhdJe1fHKcVV0=", + "dev": true, + "requires": { + "sax": "0.6.x", + "xmlbuilder": ">=1.0.0" + } + } + } + }, + "webpack": { + "version": "4.8.3", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-4.8.3.tgz", + "integrity": "sha512-/hfAjBISycdK597lxONjKEFX7dSIU1PsYwC3XlXUXoykWBlv9QV5HnO+ql3HvrrgfBJ7WXdnjO9iGPR2aAc5sw==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.4.3", + "@webassemblyjs/wasm-edit": "1.4.3", + "@webassemblyjs/wasm-parser": "1.4.3", + "acorn": "^5.0.0", + "acorn-dynamic-import": "^3.0.0", + "ajv": "^6.1.0", + "ajv-keywords": "^3.1.0", + "chrome-trace-event": "^0.1.1", + "enhanced-resolve": "^4.0.0", + "eslint-scope": "^3.7.1", + "loader-runner": "^2.3.0", + "loader-utils": "^1.1.0", + "memory-fs": "~0.4.1", + "micromatch": "^3.1.8", + "mkdirp": "~0.5.0", + "neo-async": "^2.5.0", + "node-libs-browser": "^2.0.0", + "schema-utils": "^0.4.4", + "tapable": "^1.0.0", + "uglifyjs-webpack-plugin": "^1.2.4", + "watchpack": "^1.5.0", + "webpack-sources": "^1.0.1" + } + }, + "webpack-core": { + "version": "0.6.9", + "resolved": "https://registry.npmjs.org/webpack-core/-/webpack-core-0.6.9.tgz", + "integrity": "sha1-/FcViMhVjad76e+23r3Fo7FyvcI=", + "dev": true, + "requires": { + "source-list-map": "~0.1.7", + "source-map": "~0.4.1" + }, + "dependencies": { + "source-list-map": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/source-list-map/-/source-list-map-0.1.8.tgz", + "integrity": "sha1-xVCyq1Qn9rPyH1r+rYjE9Vh7IQY=", + "dev": true + }, + "source-map": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.4.4.tgz", + "integrity": "sha1-66T12pwNyZneaAMti092FzZSA2s=", + "dev": true, + "requires": { + "amdefine": ">=0.0.4" + } + } + } + }, + "webpack-dev-middleware": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-3.1.3.tgz", + "integrity": "sha512-I6Mmy/QjWU/kXwCSFGaiOoL5YEQIVmbb0o45xMoCyQAg/mClqZVTcsX327sPfekDyJWpCxb+04whNyLOIxpJdQ==", + "dev": true, + "requires": { + "loud-rejection": "^1.6.0", + "memory-fs": "~0.4.1", + "mime": "^2.1.0", + "path-is-absolute": "^1.0.0", + "range-parser": "^1.0.3", + "url-join": "^4.0.0", + "webpack-log": "^1.0.1" + }, + "dependencies": { + "mime": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.3.1.tgz", + "integrity": "sha512-OEUllcVoydBHGN1z84yfQDimn58pZNNNXgZlHXSboxMlFvgI6MXSWpWKpFRra7H1HxpVhHTkrghfRW49k6yjeg==", + "dev": true + } + } + }, + "webpack-dev-server": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-3.1.5.tgz", + "integrity": "sha512-LVHg+EPwZLHIlfvokSTgtJqO/vI5CQi89fASb5JEDtVMDjY0yuIEqPPdMiKaBJIB/Ab7v/UN/sYZ7WsZvntQKw==", + "dev": true, + "requires": { + "ansi-html": "0.0.7", + "array-includes": "^3.0.3", + "bonjour": "^3.5.0", + "chokidar": "^2.0.0", + "compression": "^1.5.2", + "connect-history-api-fallback": "^1.3.0", + "debug": "^3.1.0", + "del": "^3.0.0", + "express": "^4.16.2", + "html-entities": "^1.2.0", + "http-proxy-middleware": "~0.18.0", + "import-local": "^1.0.0", + "internal-ip": "1.2.0", + "ip": "^1.1.5", + "killable": "^1.0.0", + "loglevel": "^1.4.1", + "opn": "^5.1.0", + "portfinder": "^1.0.9", + "selfsigned": "^1.9.1", + "serve-index": "^1.7.2", + "sockjs": "0.3.19", + "sockjs-client": "1.1.5", + "spdy": "^3.4.1", + "strip-ansi": "^3.0.0", + "supports-color": "^5.1.0", + "webpack-dev-middleware": "3.1.3", + "webpack-log": "^1.1.2", + "yargs": "11.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", + "dev": true + }, + "camelcase": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-4.1.0.tgz", + "integrity": "sha1-1UVjW+HjPFQmScaRc+Xeas+uNN0=", + "dev": true + }, + "cliui": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-4.1.0.tgz", + "integrity": "sha512-4FG+RSG9DL7uEwRUZXZn3SS34DiDPfzP0VOiEwtUWlE+AR2EIg+hSyvrIgUUfhdgR/UkAeW2QHgeP+hWrXs7jQ==", + "dev": true, + "requires": { + "string-width": "^2.1.1", + "strip-ansi": "^4.0.0", + "wrap-ansi": "^2.0.0" + }, + "dependencies": { + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "dev": true, + "requires": { + "ansi-regex": "^3.0.0" + } + } + } + }, + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", + "dev": true + }, + "os-locale": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-2.1.0.tgz", + "integrity": "sha512-3sslG3zJbEYcaC4YVAvDorjGxc7tv6KVATnLPZONiljsUncvihe9BQoVCEs0RZ1kmf4Hk9OBqlZfJZWI4GanKA==", + "dev": true, + "requires": { + "execa": "^0.7.0", + "lcid": "^1.0.0", + "mem": "^1.1.0" + } + }, + "string-width": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", + "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", + "dev": true, + "requires": { + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^4.0.0" + }, + "dependencies": { + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "dev": true, + "requires": { + "ansi-regex": "^3.0.0" + } + } + } + }, + "which-module": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", + "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", + "dev": true + }, + "y18n": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-3.2.1.tgz", + "integrity": "sha1-bRX7qITAhnnA136I53WegR4H+kE=", + "dev": true + }, + "yargs": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-11.0.0.tgz", + "integrity": "sha512-Rjp+lMYQOWtgqojx1dEWorjCofi1YN7AoFvYV7b1gx/7dAAeuI4kN5SZiEvr0ZmsZTOpDRcCqrpI10L31tFkBw==", + "dev": true, + "requires": { + "cliui": "^4.0.0", + "decamelize": "^1.1.1", + "find-up": "^2.1.0", + "get-caller-file": "^1.0.1", + "os-locale": "^2.0.0", + "require-directory": "^2.1.1", + "require-main-filename": "^1.0.1", + "set-blocking": "^2.0.0", + "string-width": "^2.0.0", + "which-module": "^2.0.0", + "y18n": "^3.2.1", + "yargs-parser": "^9.0.2" + } + }, + "yargs-parser": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-9.0.2.tgz", + "integrity": "sha1-nM9qQ0YP5O1Aqbto9I1DuKaMwHc=", + "dev": true, + "requires": { + "camelcase": "^4.1.0" + } + } + } + }, + "webpack-log": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/webpack-log/-/webpack-log-1.2.0.tgz", + "integrity": "sha512-U9AnICnu50HXtiqiDxuli5gLB5PGBo7VvcHx36jRZHwK4vzOYLbImqT4lwWwoMHdQWwEKw736fCHEekokTEKHA==", + "dev": true, + "requires": { + "chalk": "^2.1.0", + "log-symbols": "^2.1.0", + "loglevelnext": "^1.0.1", + "uuid": "^3.1.0" + } + }, + "webpack-merge": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-4.1.3.tgz", + "integrity": "sha512-zxwAIGK7nKdu5CIZL0BjTQoq3elV0t0MfB7rUC1zj668geid52abs6hN/ACwZdK6LeMS8dC9B6WmtF978zH5mg==", + "dev": true, + "requires": { + "lodash": "^4.17.5" + } + }, + "webpack-sources": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-1.1.0.tgz", + "integrity": "sha512-aqYp18kPphgoO5c/+NaUvEeACtZjMESmDChuD3NBciVpah3XpMEU9VAAtIaB1BsfJWWTSdv8Vv1m3T0aRk2dUw==", + "dev": true, + "requires": { + "source-list-map": "^2.0.0", + "source-map": "~0.6.1" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "webpack-subresource-integrity": { + "version": "1.1.0-rc.4", + "resolved": "https://registry.npmjs.org/webpack-subresource-integrity/-/webpack-subresource-integrity-1.1.0-rc.4.tgz", + "integrity": "sha1-xcTj1pD50vZKlVDgeodn+Xlqpdg=", + "dev": true, + "requires": { + "webpack-core": "^0.6.8" + } + }, + "websocket-driver": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.0.tgz", + "integrity": "sha1-DK+dLXVdk67gSdS90NP+LMoqJOs=", + "dev": true, + "requires": { + "http-parser-js": ">=0.4.0", + "websocket-extensions": ">=0.1.1" + } + }, + "websocket-extensions": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.3.tgz", + "integrity": "sha512-nqHUnMXmBzT0w570r2JpJxfiSD1IzoI+HGVdd3aZ0yNi3ngvQ4jv1dtHt5VGxfI2yj5yqImPhOK4vmIh2xMbGg==", + "dev": true + }, + "when": { + "version": "3.6.4", + "resolved": "https://registry.npmjs.org/when/-/when-3.6.4.tgz", + "integrity": "sha1-RztRfsFZ4rhQBUl6E5g/CVQS404=", + "dev": true + }, + "which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + }, + "which-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-1.0.0.tgz", + "integrity": "sha1-u6Y8qGGUiZT/MHc2CJ47lgJsKk8=", + "dev": true, + "optional": true + }, + "wide-align": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.3.tgz", + "integrity": "sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA==", + "dev": true, + "requires": { + "string-width": "^1.0.2 || 2" + } + }, + "window-size": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/window-size/-/window-size-0.1.0.tgz", + "integrity": "sha1-VDjNLqk7IC76Ohn+iIeu58lPnJ0=", + "dev": true, + "optional": true + }, + "wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", + "dev": true + }, + "worker-farm": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/worker-farm/-/worker-farm-1.6.0.tgz", + "integrity": "sha512-6w+3tHbM87WnSWnENBUvA2pxJPLhQUg5LKwUQHq3r+XPhIM+Gh2R5ycbwPCyuGbNg+lPgdcnQUhuC02kJCvffQ==", + "dev": true, + "requires": { + "errno": "~0.1.7" + } + }, + "wrap-ansi": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", + "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=", + "dev": true, + "requires": { + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + }, + "ws": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-1.1.2.tgz", + "integrity": "sha1-iiRPoFJAHgjJiGz0SoUYnh/UBn8=", + "dev": true, + "requires": { + "options": ">=0.0.5", + "ultron": "1.0.x" + } + }, + "wtf-8": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wtf-8/-/wtf-8-1.0.0.tgz", + "integrity": "sha1-OS2LotDxw00e4tYw8V0O+2jhBIo=", + "dev": true + }, + "xml2js": { + "version": "0.4.19", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.19.tgz", + "integrity": "sha512-esZnJZJOiJR9wWKMyuvSE1y6Dq5LCuJanqhxslH2bxM6duahNZ+HMpCLhBQGZkbX6xRf8x1Y2eJlgt2q3qo49Q==", + "dev": true, + "requires": { + "sax": ">=0.6.0", + "xmlbuilder": "~9.0.1" + }, + "dependencies": { + "sax": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", + "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==", + "dev": true + } + } + }, + "xmlbuilder": { + "version": "9.0.7", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-9.0.7.tgz", + "integrity": "sha1-Ey7mPS7FVlxVfiD0wi35rKaGsQ0=", + "dev": true + }, + "xmlhttprequest-ssl": { + "version": "1.5.3", + "resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-1.5.3.tgz", + "integrity": "sha1-GFqIjATspGw+QHDZn3tJ3jUomS0=", + "dev": true + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + }, + "xxhashjs": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/xxhashjs/-/xxhashjs-0.2.2.tgz", + "integrity": "sha512-AkTuIuVTET12tpsVIQo+ZU6f/qDmKuRUcjaqR+OIvm+aCBsZ95i7UVY5WJ9TMsSaZ0DA2WxoZ4acu0sPH+OKAw==", + "dev": true, + "requires": { + "cuint": "^0.2.2" + } + }, + "y18n": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz", + "integrity": "sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==", + "dev": true + }, + "yallist": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", + "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", + "dev": true + }, + "yargs": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-3.10.0.tgz", + "integrity": "sha1-9+572FfdfB0tOMDnTvvWgdFDH9E=", + "dev": true, + "optional": true, + "requires": { + "camelcase": "^1.0.2", + "cliui": "^2.1.0", + "decamelize": "^1.0.0", + "window-size": "0.1.0" + } + }, + "yargs-parser": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-5.0.0.tgz", + "integrity": "sha1-J17PDX/+Bcd+ZOfIbkzZS/DhIoo=", + "dev": true, + "optional": true, + "requires": { + "camelcase": "^3.0.0" + }, + "dependencies": { + "camelcase": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-3.0.0.tgz", + "integrity": "sha1-MvxLn82vhF/N9+c7uXysImHwqwo=", + "dev": true, + "optional": true + } + } + }, + "yeast": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/yeast/-/yeast-0.1.2.tgz", + "integrity": "sha1-AI4G2AlDIMNy28L47XagymyKxBk=", + "dev": true + }, + "yn": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/yn/-/yn-2.0.0.tgz", + "integrity": "sha1-5a2ryKz0CPY4X8dklWhMiOavaJo=", + "dev": true + }, + "zone.js": { + "version": "0.8.26", + "resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.8.26.tgz", + "integrity": "sha512-W9Nj+UmBJG251wkCacIkETgra4QgBo/vgoEkb4a2uoLzpQG7qF9nzwoLXWU5xj3Fg2mxGvEDh47mg24vXccYjA==" + } + } +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/package.json b/spring-boot-angular-ecommerce/src/main/frontend/package.json new file mode 100644 index 0000000000..958e9f1023 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/package.json @@ -0,0 +1,52 @@ +{ + "name": "frontend", + "version": "0.0.0", + "scripts": { + "ng": "ng", + "start": "ng serve --proxy-config proxy-conf.json", + "build": "ng build", + "postbuild": "npm run deploy", + "predeploy": "rimraf ../resources/static/ && mkdirp ../resources/static", + "deploy": "copyfiles -f dist/** ../resources/static", + "test": "ng test", + "lint": "ng lint", + "e2e": "ng e2e" + }, + "private": true, + "dependencies": { + "@angular/animations": "^6.0.3", + "@angular/common": "^6.0.3", + "@angular/compiler": "^6.0.3", + "@angular/core": "^6.0.3", + "@angular/forms": "^6.0.3", + "@angular/http": "^6.0.3", + "@angular/platform-browser": "^6.0.3", + "@angular/platform-browser-dynamic": "^6.0.3", + "@angular/router": "^6.0.3", + "bootstrap": "^4.1.2", + "core-js": "^2.5.4", + "rxjs": "^6.0.0", + "zone.js": "^0.8.26" + }, + "devDependencies": { + "@angular/compiler-cli": "^6.0.3", + "@angular-devkit/build-angular": "~0.6.8", + "typescript": "~2.7.2", + "@angular/cli": "~6.0.8", + "@angular/language-service": "^6.0.3", + "@types/jasmine": "~2.8.6", + "@types/jasminewd2": "~2.0.3", + "@types/node": "~8.9.4", + "codelyzer": "~4.2.1", + "jasmine-core": "~2.99.1", + "jasmine-spec-reporter": "~4.2.1", + "karma": "~1.7.1", + "karma-chrome-launcher": "~2.2.0", + "karma-coverage-istanbul-reporter": "~2.0.0", + "karma-jasmine": "~1.1.1", + "karma-jasmine-html-reporter": "^0.2.2", + "protractor": "~5.3.0", + "ts-node": "~5.0.1", + "tslint": "~5.9.1" + } +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/proxy-conf.json b/spring-boot-angular-ecommerce/src/main/frontend/proxy-conf.json new file mode 100644 index 0000000000..534224beb5 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/proxy-conf.json @@ -0,0 +1,6 @@ +{ + "/api": { + "target": "http://localhost:8080", + "secure": false + } +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/app.component.css b/spring-boot-angular-ecommerce/src/main/frontend/src/app/app.component.css new file mode 100644 index 0000000000..f8fb0a460e --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/app.component.css @@ -0,0 +1,3 @@ +.container { + padding-top: 65px; +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/app.component.html b/spring-boot-angular-ecommerce/src/main/frontend/src/app/app.component.html new file mode 100644 index 0000000000..1b0ca2464f --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/app.component.html @@ -0,0 +1,3 @@ +
    + +
    diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/app.component.spec.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/app/app.component.spec.ts new file mode 100644 index 0000000000..decc558568 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/app.component.spec.ts @@ -0,0 +1,27 @@ +import { TestBed, async } from '@angular/core/testing'; +import { AppComponent } from './app.component'; +describe('AppComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [ + AppComponent + ], + }).compileComponents(); + })); + it('should create the app', async(() => { + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.debugElement.componentInstance; + expect(app).toBeTruthy(); + })); + it(`should have as title 'app'`, async(() => { + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.debugElement.componentInstance; + expect(app.title).toEqual('app'); + })); + it('should render title in a h1 tag', async(() => { + const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); + const compiled = fixture.debugElement.nativeElement; + expect(compiled.querySelector('h1').textContent).toContain('Welcome to frontend!'); + })); +}); diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/app.component.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/app/app.component.ts new file mode 100644 index 0000000000..6840b14af1 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/app.component.ts @@ -0,0 +1,12 @@ +import {Component} from '@angular/core'; +import {EcommerceService} from "./ecommerce/services/EcommerceService"; + +@Component({ + selector: 'app-root', + templateUrl: './app.component.html', + styleUrls: ['./app.component.css'], + providers: [EcommerceService] +}) +export class AppComponent { + +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/app.module.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/app/app.module.ts new file mode 100644 index 0000000000..279d2eb2d5 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/app.module.ts @@ -0,0 +1,31 @@ +import {BrowserModule} from '@angular/platform-browser'; +import {NgModule} from '@angular/core'; +import {FormsModule, ReactiveFormsModule} from '@angular/forms'; +import {HttpClientModule} from '@angular/common/http'; + +import {AppComponent} from './app.component'; +import {EcommerceComponent} from './ecommerce/ecommerce.component'; +import {ProductsComponent} from './ecommerce/products/products.component'; +import {ShoppingCartComponent} from './ecommerce/shopping-cart/shopping-cart.component'; +import {OrdersComponent} from './ecommerce/orders/orders.component'; +import {EcommerceService} from "./ecommerce/services/EcommerceService"; + +@NgModule({ + declarations: [ + AppComponent, + EcommerceComponent, + ProductsComponent, + ShoppingCartComponent, + OrdersComponent + ], + imports: [ + BrowserModule, + HttpClientModule, + FormsModule, + ReactiveFormsModule + ], + providers: [EcommerceService], + bootstrap: [AppComponent] +}) +export class AppModule { +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/ecommerce.component.css b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/ecommerce.component.css new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/ecommerce.component.html b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/ecommerce.component.html new file mode 100644 index 0000000000..682f0374b5 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/ecommerce.component.html @@ -0,0 +1,31 @@ + +
    +
    + +
    +
    + +
    +
    + +
    +
    diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/ecommerce.component.spec.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/ecommerce.component.spec.ts new file mode 100644 index 0000000000..90ac7d9b58 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/ecommerce.component.spec.ts @@ -0,0 +1,25 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; + +import { EcommerceComponent } from './ecommerce.component'; + +describe('EcommerceComponent', () => { + let component: EcommerceComponent; + let fixture: ComponentFixture; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [ EcommerceComponent ] + }) + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(EcommerceComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/ecommerce.component.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/ecommerce.component.ts new file mode 100644 index 0000000000..901fdef6e6 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/ecommerce.component.ts @@ -0,0 +1,44 @@ +import {Component, OnInit, ViewChild} from '@angular/core'; +import {ProductsComponent} from "./products/products.component"; +import {ShoppingCartComponent} from "./shopping-cart/shopping-cart.component"; +import {OrdersComponent} from "./orders/orders.component"; + +@Component({ + selector: 'app-ecommerce', + templateUrl: './ecommerce.component.html', + styleUrls: ['./ecommerce.component.css'] +}) +export class EcommerceComponent implements OnInit { + private collapsed = true; + orderFinished = false; + + @ViewChild('productsC') + productsC: ProductsComponent; + + @ViewChild('shoppingCartC') + shoppingCartC: ShoppingCartComponent; + + @ViewChild('ordersC') + ordersC: OrdersComponent; + + constructor() { + } + + ngOnInit() { + } + + toggleCollapsed(): void { + this.collapsed = !this.collapsed; + } + + finishOrder(orderFinished: boolean) { + this.orderFinished = orderFinished; + } + + reset() { + this.orderFinished = false; + this.productsC.reset(); + this.shoppingCartC.reset(); + this.ordersC.paid = false; + } +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/models/product-order.model.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/models/product-order.model.ts new file mode 100644 index 0000000000..0e1d9b03c8 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/models/product-order.model.ts @@ -0,0 +1,11 @@ +import {Product} from "./product.model"; + +export class ProductOrder { + product: Product; + quantity: number; + + constructor(product: Product, quantity: number) { + this.product = product; + this.quantity = quantity; + } +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/models/product-orders.model.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/models/product-orders.model.ts new file mode 100644 index 0000000000..d6b1f321a9 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/models/product-orders.model.ts @@ -0,0 +1,5 @@ +import {ProductOrder} from "./product-order.model"; + +export class ProductOrders { + productOrders: ProductOrder[] = []; +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/models/product.model.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/models/product.model.ts new file mode 100644 index 0000000000..258753f62e --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/models/product.model.ts @@ -0,0 +1,13 @@ +export class Product { + id: number; + name: string; + price: number; + pictureUrl: string; + + constructor(id: number, name: string, price: number, pictureUrl: string) { + this.id = id; + this.name = name; + this.price = price; + this.pictureUrl = pictureUrl; + } +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/orders/orders.component.css b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/orders/orders.component.css new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/orders/orders.component.html b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/orders/orders.component.html new file mode 100644 index 0000000000..e4a8b50c63 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/orders/orders.component.html @@ -0,0 +1,13 @@ +

    ORDER

    +
      +
    • + {{ order.product.name }} - ${{ order.product.price }} x {{ order.quantity}} pcs. +
    • +
    +

    Total amount: ${{ total }}

    + + + + diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/orders/orders.component.spec.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/orders/orders.component.spec.ts new file mode 100644 index 0000000000..b8efbb0f4e --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/orders/orders.component.spec.ts @@ -0,0 +1,25 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; + +import { OrdersComponent } from './orders.component'; + +describe('OrdersComponent', () => { + let component: OrdersComponent; + let fixture: ComponentFixture; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [ OrdersComponent ] + }) + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(OrdersComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/orders/orders.component.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/orders/orders.component.ts new file mode 100644 index 0000000000..c3348ed396 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/orders/orders.component.ts @@ -0,0 +1,39 @@ +import {Component, OnInit} from '@angular/core'; +import {ProductOrders} from "../models/product-orders.model"; +import {Subscription} from "rxjs/internal/Subscription"; +import {EcommerceService} from "../services/EcommerceService"; + +@Component({ + selector: 'app-orders', + templateUrl: './orders.component.html', + styleUrls: ['./orders.component.css'] +}) +export class OrdersComponent implements OnInit { + orders: ProductOrders; + total: number; + paid: boolean; + sub: Subscription; + + constructor(private ecommerceService: EcommerceService) { + this.orders = this.ecommerceService.ProductOrders; + } + + ngOnInit() { + this.paid = false; + this.sub = this.ecommerceService.OrdersChanged.subscribe(() => { + this.orders = this.ecommerceService.ProductOrders; + }); + this.loadTotal(); + } + + pay() { + this.paid = true; + this.ecommerceService.saveOrder(this.orders).subscribe(); + } + + loadTotal() { + this.sub = this.ecommerceService.TotalChanged.subscribe(() => { + this.total = this.ecommerceService.Total; + }); + } +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/products/products.component.css b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/products/products.component.css new file mode 100644 index 0000000000..dce4e4caf2 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/products/products.component.css @@ -0,0 +1,4 @@ +.padding-0 { + padding-right: 0; + padding-left: 1; +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/products/products.component.html b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/products/products.component.html new file mode 100644 index 0000000000..f9d422b024 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/products/products.component.html @@ -0,0 +1,28 @@ +
    +
    +
    +
    +

    {{order.product.name}}

    +
    +
    + +
    ${{order.product.price}}
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    +
    +
    diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/products/products.component.spec.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/products/products.component.spec.ts new file mode 100644 index 0000000000..563ae953e1 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/products/products.component.spec.ts @@ -0,0 +1,25 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; + +import { ProductsComponent } from './products.component'; + +describe('ProductsComponent', () => { + let component: ProductsComponent; + let fixture: ComponentFixture; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [ ProductsComponent ] + }) + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(ProductsComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/products/products.component.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/products/products.component.ts new file mode 100644 index 0000000000..520d0b106a --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/products/products.component.ts @@ -0,0 +1,82 @@ +import {Component, OnInit} from '@angular/core'; +import {ProductOrder} from "../models/product-order.model"; +import {EcommerceService} from "../services/EcommerceService"; +import {Subscription} from "rxjs/internal/Subscription"; +import {ProductOrders} from "../models/product-orders.model"; +import {Product} from "../models/product.model"; + +@Component({ + selector: 'app-products', + templateUrl: './products.component.html', + styleUrls: ['./products.component.css'] +}) +export class ProductsComponent implements OnInit { + productOrders: ProductOrder[] = []; + products: Product[] = []; + selectedProductOrder: ProductOrder; + private shoppingCartOrders: ProductOrders; + sub: Subscription; + productSelected: boolean = false; + + constructor(private ecommerceService: EcommerceService) { + } + + ngOnInit() { + this.productOrders = []; + this.loadProducts(); + this.loadOrders(); + } + + addToCart(order: ProductOrder) { + this.ecommerceService.SelectedProductOrder = order; + this.selectedProductOrder = this.ecommerceService.SelectedProductOrder; + this.productSelected = true; + } + + removeFromCart(productOrder: ProductOrder) { + let index = this.getProductIndex(productOrder.product); + if (index > -1) { + this.shoppingCartOrders.productOrders.splice( + this.getProductIndex(productOrder.product), 1); + } + this.ecommerceService.ProductOrders = this.shoppingCartOrders; + this.shoppingCartOrders = this.ecommerceService.ProductOrders; + this.productSelected = false; + } + + getProductIndex(product: Product): number { + return this.ecommerceService.ProductOrders.productOrders.findIndex( + value => value.product === product); + } + + isProductSelected(product: Product): boolean { + return this.getProductIndex(product) > -1; + } + + loadProducts() { + this.ecommerceService.getAllProducts() + .subscribe( + (products: any[]) => { + this.products = products; + this.products.forEach(product => { + this.productOrders.push(new ProductOrder(product, 0)); + }) + }, + (error) => console.log(error) + ); + } + + loadOrders() { + this.sub = this.ecommerceService.OrdersChanged.subscribe(() => { + this.shoppingCartOrders = this.ecommerceService.ProductOrders; + }); + } + + reset() { + this.productOrders = []; + this.loadProducts(); + this.ecommerceService.ProductOrders.productOrders = []; + this.loadOrders(); + this.productSelected = false; + } +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/services/EcommerceService.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/services/EcommerceService.ts new file mode 100644 index 0000000000..d22b740c41 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/services/EcommerceService.ts @@ -0,0 +1,62 @@ +import {ProductOrder} from "../models/product-order.model"; +import {Subject} from "rxjs/internal/Subject"; +import {ProductOrders} from "../models/product-orders.model"; +import {HttpClient} from '@angular/common/http'; +import {Injectable} from "@angular/core"; + +@Injectable() +export class EcommerceService { + private productsUrl = "/api/products"; + private ordersUrl = "/api/orders"; + + private productOrder: ProductOrder; + private orders: ProductOrders = new ProductOrders(); + + private productOrderSubject = new Subject(); + private ordersSubject = new Subject(); + private totalSubject = new Subject(); + + private total: number; + + ProductOrderChanged = this.productOrderSubject.asObservable(); + OrdersChanged = this.ordersSubject.asObservable(); + TotalChanged = this.totalSubject.asObservable(); + + constructor(private http: HttpClient) { + } + + getAllProducts() { + return this.http.get(this.productsUrl); + } + + saveOrder(order: ProductOrders) { + return this.http.post(this.ordersUrl, order); + } + + set SelectedProductOrder(value: ProductOrder) { + this.productOrder = value; + this.productOrderSubject.next(); + } + + get SelectedProductOrder() { + return this.productOrder; + } + + set ProductOrders(value: ProductOrders) { + this.orders = value; + this.ordersSubject.next(); + } + + get ProductOrders() { + return this.orders; + } + + get Total() { + return this.total; + } + + set Total(value: number) { + this.total = value; + this.totalSubject.next(); + } +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/shopping-cart/shopping-cart.component.css b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/shopping-cart/shopping-cart.component.css new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/shopping-cart/shopping-cart.component.html b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/shopping-cart/shopping-cart.component.html new file mode 100644 index 0000000000..b18a02b93c --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/shopping-cart/shopping-cart.component.html @@ -0,0 +1,18 @@ +
    +
    Shopping Cart
    +
    +
    Total: ${{total}}
    +
    +
    Items bought:
    + +
      +
    • + {{ order.product.name }} - {{ order.quantity}} pcs. +
    • +
    + + +
    +
    diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/shopping-cart/shopping-cart.component.spec.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/shopping-cart/shopping-cart.component.spec.ts new file mode 100644 index 0000000000..5d7735477c --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/shopping-cart/shopping-cart.component.spec.ts @@ -0,0 +1,25 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; + +import { ShoppingCartComponent } from './shopping-cart.component'; + +describe('ShoppingCartComponent', () => { + let component: ShoppingCartComponent; + let fixture: ComponentFixture; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [ ShoppingCartComponent ] + }) + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(ShoppingCartComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/shopping-cart/shopping-cart.component.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/shopping-cart/shopping-cart.component.ts new file mode 100644 index 0000000000..81a6514eb7 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/app/ecommerce/shopping-cart/shopping-cart.component.ts @@ -0,0 +1,76 @@ +import {Component, EventEmitter, OnDestroy, OnInit, Output} from '@angular/core'; +import {ProductOrders} from "../models/product-orders.model"; +import {ProductOrder} from "../models/product-order.model"; +import {EcommerceService} from "../services/EcommerceService"; +import {Subscription} from "rxjs/internal/Subscription"; + +@Component({ + selector: 'app-shopping-cart', + templateUrl: './shopping-cart.component.html', + styleUrls: ['./shopping-cart.component.css'] +}) +export class ShoppingCartComponent implements OnInit, OnDestroy { + orderFinished: boolean; + orders: ProductOrders; + total: number; + sub: Subscription; + + @Output() onOrderFinished: EventEmitter; + + constructor(private ecommerceService: EcommerceService) { + this.total = 0; + this.orderFinished = false; + this.onOrderFinished = new EventEmitter(); + } + + ngOnInit() { + this.orders = new ProductOrders(); + this.loadCart(); + this.loadTotal(); + } + + private calculateTotal(products: ProductOrder[]): number { + let sum = 0; + products.forEach(value => { + sum += (value.product.price * value.quantity); + }); + return sum; + } + + ngOnDestroy() { + this.sub.unsubscribe(); + } + + finishOrder() { + this.orderFinished = true; + this.ecommerceService.Total = this.total; + this.onOrderFinished.emit(this.orderFinished); + } + + loadTotal() { + this.sub = this.ecommerceService.OrdersChanged.subscribe(() => { + this.total = this.calculateTotal(this.orders.productOrders); + }); + } + + loadCart() { + this.sub = this.ecommerceService.ProductOrderChanged.subscribe(() => { + let productOrder = this.ecommerceService.SelectedProductOrder; + if (productOrder) { + this.orders.productOrders.push(new ProductOrder( + productOrder.product, productOrder.quantity)); + } + this.ecommerceService.ProductOrders = this.orders; + this.orders = this.ecommerceService.ProductOrders; + this.total = this.calculateTotal(this.orders.productOrders); + }); + } + + reset() { + this.orderFinished = false; + this.orders = new ProductOrders(); + this.orders.productOrders = [] + this.loadTotal(); + this.total = 0; + } +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/assets/.gitkeep b/spring-boot-angular-ecommerce/src/main/frontend/src/assets/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/browserslist b/spring-boot-angular-ecommerce/src/main/frontend/src/browserslist new file mode 100644 index 0000000000..8e09ab492e --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/browserslist @@ -0,0 +1,9 @@ +# This file is currently used by autoprefixer to adjust CSS to support the below specified browsers +# For additional information regarding the format and rule options, please see: +# https://github.com/browserslist/browserslist#queries +# For IE 9-11 support, please uncomment the last line of the file and adjust as needed +> 0.5% +last 2 versions +Firefox ESR +not dead +# IE 9-11 \ No newline at end of file diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/environments/environment.prod.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/environments/environment.prod.ts new file mode 100644 index 0000000000..3612073bc3 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/environments/environment.prod.ts @@ -0,0 +1,3 @@ +export const environment = { + production: true +}; diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/environments/environment.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/environments/environment.ts new file mode 100644 index 0000000000..012182efa3 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/environments/environment.ts @@ -0,0 +1,15 @@ +// This file can be replaced during build by using the `fileReplacements` array. +// `ng build ---prod` replaces `environment.ts` with `environment.prod.ts`. +// The list of file replacements can be found in `angular.json`. + +export const environment = { + production: false +}; + +/* + * In development mode, to ignore zone related error stack frames such as + * `zone.run`, `zoneDelegate.invokeTask` for easier debugging, you can + * import the following file, but please comment it out in production mode + * because it will have performance impact when throw error + */ +// import 'zone.js/dist/zone-error'; // Included with Angular CLI. diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/favicon.ico b/spring-boot-angular-ecommerce/src/main/frontend/src/favicon.ico new file mode 100644 index 0000000000..8081c7ceaf Binary files /dev/null and b/spring-boot-angular-ecommerce/src/main/frontend/src/favicon.ico differ diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/index.html b/spring-boot-angular-ecommerce/src/main/frontend/src/index.html new file mode 100644 index 0000000000..3faefb6e8c --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/index.html @@ -0,0 +1,14 @@ + + + + + Frontend + + + + + + + + + diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/karma.conf.js b/spring-boot-angular-ecommerce/src/main/frontend/src/karma.conf.js new file mode 100644 index 0000000000..b6e00421c9 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/karma.conf.js @@ -0,0 +1,31 @@ +// Karma configuration file, see link for more information +// https://karma-runner.github.io/1.0/config/configuration-file.html + +module.exports = function (config) { + config.set({ + basePath: '', + frameworks: ['jasmine', '@angular-devkit/build-angular'], + plugins: [ + require('karma-jasmine'), + require('karma-chrome-launcher'), + require('karma-jasmine-html-reporter'), + require('karma-coverage-istanbul-reporter'), + require('@angular-devkit/build-angular/plugins/karma') + ], + client: { + clearContext: false // leave Jasmine Spec Runner output visible in browser + }, + coverageIstanbulReporter: { + dir: require('path').join(__dirname, '../coverage'), + reports: ['html', 'lcovonly'], + fixWebpackSourcePaths: true + }, + reporters: ['progress', 'kjhtml'], + port: 9876, + colors: true, + logLevel: config.LOG_INFO, + autoWatch: true, + browsers: ['Chrome'], + singleRun: false + }); +}; \ No newline at end of file diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/main.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/main.ts new file mode 100644 index 0000000000..91ec6da5f0 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/main.ts @@ -0,0 +1,12 @@ +import { enableProdMode } from '@angular/core'; +import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; + +import { AppModule } from './app/app.module'; +import { environment } from './environments/environment'; + +if (environment.production) { + enableProdMode(); +} + +platformBrowserDynamic().bootstrapModule(AppModule) + .catch(err => console.log(err)); diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/polyfills.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/polyfills.ts new file mode 100644 index 0000000000..d310405a68 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/polyfills.ts @@ -0,0 +1,80 @@ +/** + * This file includes polyfills needed by Angular and is loaded before the app. + * You can add your own extra polyfills to this file. + * + * This file is divided into 2 sections: + * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. + * 2. Application imports. Files imported after ZoneJS that should be loaded before your main + * file. + * + * The current setup is for so-called "evergreen" browsers; the last versions of browsers that + * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), + * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. + * + * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html + */ + +/*************************************************************************************************** + * BROWSER POLYFILLS + */ + +/** IE9, IE10 and IE11 requires all of the following polyfills. **/ +// import 'core-js/es6/symbol'; +// import 'core-js/es6/object'; +// import 'core-js/es6/function'; +// import 'core-js/es6/parse-int'; +// import 'core-js/es6/parse-float'; +// import 'core-js/es6/number'; +// import 'core-js/es6/math'; +// import 'core-js/es6/string'; +// import 'core-js/es6/date'; +// import 'core-js/es6/array'; +// import 'core-js/es6/regexp'; +// import 'core-js/es6/map'; +// import 'core-js/es6/weak-map'; +// import 'core-js/es6/set'; + +/** IE10 and IE11 requires the following for NgClass support on SVG elements */ +// import 'classlist.js'; // Run `npm install --save classlist.js`. + +/** IE10 and IE11 requires the following for the Reflect API. */ +// import 'core-js/es6/reflect'; + + +/** Evergreen browsers require these. **/ +// Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove. +import 'core-js/es7/reflect'; + + +/** + * Web Animations `@angular/platform-browser/animations` + * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. + * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). + **/ +// import 'web-animations-js'; // Run `npm install --save web-animations-js`. + +/** + * By default, zone.js will patch all possible macroTask and DomEvents + * user can disable parts of macroTask/DomEvents patch by setting following flags + */ + + // (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame + // (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick + // (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames + + /* + * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js + * with the following flag, it will bypass `zone.js` patch for IE/Edge + */ +// (window as any).__Zone_enable_cross_context_check = true; + +/*************************************************************************************************** + * Zone JS is required by default for Angular itself. + */ +import 'zone.js/dist/zone'; // Included with Angular CLI. + + + +/*************************************************************************************************** + * APPLICATION IMPORTS + */ diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/styles.css b/spring-boot-angular-ecommerce/src/main/frontend/src/styles.css new file mode 100644 index 0000000000..90d4ee0072 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/styles.css @@ -0,0 +1 @@ +/* You can add global styles to this file, and also import other style files */ diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/test.ts b/spring-boot-angular-ecommerce/src/main/frontend/src/test.ts new file mode 100644 index 0000000000..16317897b1 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/test.ts @@ -0,0 +1,20 @@ +// This file is required by karma.conf.js and loads recursively all the .spec and framework files + +import 'zone.js/dist/zone-testing'; +import { getTestBed } from '@angular/core/testing'; +import { + BrowserDynamicTestingModule, + platformBrowserDynamicTesting +} from '@angular/platform-browser-dynamic/testing'; + +declare const require: any; + +// First, initialize the Angular testing environment. +getTestBed().initTestEnvironment( + BrowserDynamicTestingModule, + platformBrowserDynamicTesting() +); +// Then we find all the tests. +const context = require.context('./', true, /\.spec\.ts$/); +// And load the modules. +context.keys().map(context); diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/tsconfig.app.json b/spring-boot-angular-ecommerce/src/main/frontend/src/tsconfig.app.json new file mode 100644 index 0000000000..722c370d58 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/tsconfig.app.json @@ -0,0 +1,12 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "outDir": "../out-tsc/app", + "module": "es2015", + "types": [] + }, + "exclude": [ + "src/test.ts", + "**/*.spec.ts" + ] +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/tsconfig.spec.json b/spring-boot-angular-ecommerce/src/main/frontend/src/tsconfig.spec.json new file mode 100644 index 0000000000..8f7cedecab --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/tsconfig.spec.json @@ -0,0 +1,19 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "outDir": "../out-tsc/spec", + "module": "commonjs", + "types": [ + "jasmine", + "node" + ] + }, + "files": [ + "test.ts", + "polyfills.ts" + ], + "include": [ + "**/*.spec.ts", + "**/*.d.ts" + ] +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/src/tslint.json b/spring-boot-angular-ecommerce/src/main/frontend/src/tslint.json new file mode 100644 index 0000000000..52e2c1a5a7 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/src/tslint.json @@ -0,0 +1,17 @@ +{ + "extends": "../tslint.json", + "rules": { + "directive-selector": [ + true, + "attribute", + "app", + "camelCase" + ], + "component-selector": [ + true, + "element", + "app", + "kebab-case" + ] + } +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/tsconfig.json b/spring-boot-angular-ecommerce/src/main/frontend/tsconfig.json new file mode 100644 index 0000000000..ef44e2862b --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compileOnSave": false, + "compilerOptions": { + "baseUrl": "./", + "outDir": "./dist/out-tsc", + "sourceMap": true, + "declaration": false, + "moduleResolution": "node", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "target": "es5", + "typeRoots": [ + "node_modules/@types" + ], + "lib": [ + "es2017", + "dom" + ] + } +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/tslint.json b/spring-boot-angular-ecommerce/src/main/frontend/tslint.json new file mode 100644 index 0000000000..3ea984c776 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/frontend/tslint.json @@ -0,0 +1,130 @@ +{ + "rulesDirectory": [ + "node_modules/codelyzer" + ], + "rules": { + "arrow-return-shorthand": true, + "callable-types": true, + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "curly": true, + "deprecation": { + "severity": "warn" + }, + "eofline": true, + "forin": true, + "import-blacklist": [ + true, + "rxjs/Rx" + ], + "import-spacing": true, + "indent": [ + true, + "spaces" + ], + "interface-over-type-literal": true, + "label-position": true, + "max-line-length": [ + true, + 140 + ], + "member-access": false, + "member-ordering": [ + true, + { + "order": [ + "static-field", + "instance-field", + "static-method", + "instance-method" + ] + } + ], + "no-arg": true, + "no-bitwise": true, + "no-console": [ + true, + "debug", + "info", + "time", + "timeEnd", + "trace" + ], + "no-construct": true, + "no-debugger": true, + "no-duplicate-super": true, + "no-empty": false, + "no-empty-interface": true, + "no-eval": true, + "no-inferrable-types": [ + true, + "ignore-params" + ], + "no-misused-new": true, + "no-non-null-assertion": true, + "no-shadowed-variable": true, + "no-string-literal": false, + "no-string-throw": true, + "no-switch-case-fall-through": true, + "no-trailing-whitespace": true, + "no-unnecessary-initializer": true, + "no-unused-expression": true, + "no-use-before-declare": true, + "no-var-keyword": true, + "object-literal-sort-keys": false, + "one-line": [ + true, + "check-open-brace", + "check-catch", + "check-else", + "check-whitespace" + ], + "prefer-const": true, + "quotemark": [ + true, + "single" + ], + "radix": true, + "semicolon": [ + true, + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "typedef-whitespace": [ + true, + { + "call-signature": "nospace", + "index-signature": "nospace", + "parameter": "nospace", + "property-declaration": "nospace", + "variable-declaration": "nospace" + } + ], + "unified-signatures": true, + "variable-name": false, + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ], + "no-output-on-prefix": true, + "use-input-property-decorator": true, + "use-output-property-decorator": true, + "use-host-property-decorator": true, + "no-input-rename": true, + "no-output-rename": true, + "use-life-cycle-interface": true, + "use-pipe-transform-interface": true, + "component-class-suffix": true, + "directive-class-suffix": true + } +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/EcommerceApplication.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/EcommerceApplication.java new file mode 100644 index 0000000000..b1fa14e9a9 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/EcommerceApplication.java @@ -0,0 +1,29 @@ +package com.baeldung.ecommerce; + +import com.baeldung.ecommerce.model.Product; +import com.baeldung.ecommerce.service.ProductService; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +public class EcommerceApplication { + + public static void main(String[] args) { + SpringApplication.run(EcommerceApplication.class, args); + } + + @Bean + CommandLineRunner runner(ProductService productService) { + return args -> { + productService.save(new Product(1L, "TV Set", 300.00, "http://placehold.it/200x100")); + productService.save(new Product(2L, "Game Console", 200.00, "http://placehold.it/200x100")); + productService.save(new Product(3L, "Sofa", 100.00, "http://placehold.it/200x100")); + productService.save(new Product(4L, "Icecream", 5.00, "http://placehold.it/200x100")); + productService.save(new Product(5L, "Beer", 3.00, "http://placehold.it/200x100")); + productService.save(new Product(6L, "Phone", 500.00, "http://placehold.it/200x100")); + productService.save(new Product(7L, "Watch", 30.00, "http://placehold.it/200x100")); + }; + } +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/controller/OrderController.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/controller/OrderController.java new file mode 100644 index 0000000000..c239496708 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/controller/OrderController.java @@ -0,0 +1,99 @@ +package com.baeldung.ecommerce.controller; + +import com.baeldung.ecommerce.dto.OrderProductDto; +import com.baeldung.ecommerce.exception.ResourceNotFoundException; +import com.baeldung.ecommerce.model.Order; +import com.baeldung.ecommerce.model.OrderProduct; +import com.baeldung.ecommerce.model.OrderStatus; +import com.baeldung.ecommerce.service.OrderProductService; +import com.baeldung.ecommerce.service.OrderService; +import com.baeldung.ecommerce.service.ProductService; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.util.CollectionUtils; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import javax.validation.constraints.NotNull; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +@RestController +@RequestMapping("/api/orders") +public class OrderController { + + ProductService productService; + OrderService orderService; + OrderProductService orderProductService; + + public OrderController(ProductService productService, OrderService orderService, OrderProductService orderProductService) { + this.productService = productService; + this.orderService = orderService; + this.orderProductService = orderProductService; + } + + @GetMapping + @ResponseStatus(HttpStatus.OK) + public @NotNull Iterable list() { + return this.orderService.getAllOrders(); + } + + @PostMapping + public ResponseEntity create(@RequestBody OrderForm form) { + List formDtos = form.getProductOrders(); + validateProductsExistence(formDtos); + Order order = new Order(); + order.setStatus(OrderStatus.PAID.name()); + order = this.orderService.create(order); + + List orderProducts = new ArrayList<>(); + for (OrderProductDto dto : formDtos) { + orderProducts.add(orderProductService.create(new OrderProduct(order, productService.getProduct(dto + .getProduct() + .getId()), dto.getQuantity()))); + } + + order.setOrderProducts(orderProducts); + + this.orderService.update(order); + + String uri = ServletUriComponentsBuilder + .fromCurrentServletMapping() + .path("/orders/{id}") + .buildAndExpand(order.getId()) + .toString(); + HttpHeaders headers = new HttpHeaders(); + headers.add("Location", uri); + + return new ResponseEntity<>(order, headers, HttpStatus.CREATED); + } + + private void validateProductsExistence(List orderProducts) { + List list = orderProducts + .stream() + .filter(op -> Objects.isNull(productService.getProduct(op + .getProduct() + .getId()))) + .collect(Collectors.toList()); + + if (!CollectionUtils.isEmpty(list)) { + new ResourceNotFoundException("Product not found"); + } + } + + public static class OrderForm { + + private List productOrders; + + public List getProductOrders() { + return productOrders; + } + + public void setProductOrders(List productOrders) { + this.productOrders = productOrders; + } + } +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/controller/ProductController.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/controller/ProductController.java new file mode 100644 index 0000000000..0f5af0af4b --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/controller/ProductController.java @@ -0,0 +1,25 @@ +package com.baeldung.ecommerce.controller; + +import com.baeldung.ecommerce.model.Product; +import com.baeldung.ecommerce.service.ProductService; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.validation.constraints.NotNull; + +@RestController +@RequestMapping("/api/products") +public class ProductController { + + private ProductService productService; + + public ProductController(ProductService productService) { + this.productService = productService; + } + + @GetMapping(value = { "", "/" }) + public @NotNull Iterable getProducts() { + return productService.getAllProducts(); + } +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/dto/OrderProductDto.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/dto/OrderProductDto.java new file mode 100644 index 0000000000..f4c92ee28e --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/dto/OrderProductDto.java @@ -0,0 +1,25 @@ +package com.baeldung.ecommerce.dto; + +import com.baeldung.ecommerce.model.Product; + +public class OrderProductDto { + + private Product product; + private Integer quantity; + + public Product getProduct() { + return product; + } + + public void setProduct(Product product) { + this.product = product; + } + + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/exception/ApiExceptionHandler.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/exception/ApiExceptionHandler.java new file mode 100644 index 0000000000..aae7e39ffc --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/exception/ApiExceptionHandler.java @@ -0,0 +1,81 @@ +package com.baeldung.ecommerce.exception; + +import com.fasterxml.jackson.annotation.JsonInclude; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import javax.validation.ConstraintViolation; +import javax.validation.ConstraintViolationException; +import java.util.ArrayList; +import java.util.List; + +@RestControllerAdvice +public class ApiExceptionHandler { + + @SuppressWarnings("rawtypes") + @ExceptionHandler(ConstraintViolationException.class) + public ResponseEntity handle(ConstraintViolationException e) { + ErrorResponse errors = new ErrorResponse(); + for (ConstraintViolation violation : e.getConstraintViolations()) { + ErrorItem error = new ErrorItem(); + error.setCode(violation.getMessageTemplate()); + error.setMessage(violation.getMessage()); + errors.addError(error); + } + + return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); + } + + @SuppressWarnings("rawtypes") + @ExceptionHandler(ResourceNotFoundException.class) + public ResponseEntity handle(ResourceNotFoundException e) { + ErrorItem error = new ErrorItem(); + error.setMessage(e.getMessage()); + + return new ResponseEntity<>(error, HttpStatus.NOT_FOUND); + } + + public static class ErrorItem { + + @JsonInclude(JsonInclude.Include.NON_NULL) private String code; + + private String message; + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + } + + public static class ErrorResponse { + + private List errors = new ArrayList<>(); + + public List getErrors() { + return errors; + } + + public void setErrors(List errors) { + this.errors = errors; + } + + public void addError(ErrorItem error) { + this.errors.add(error); + } + + } +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/exception/ResourceNotFoundException.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/exception/ResourceNotFoundException.java new file mode 100644 index 0000000000..3d8e47326c --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/exception/ResourceNotFoundException.java @@ -0,0 +1,22 @@ +package com.baeldung.ecommerce.exception; + +public class ResourceNotFoundException extends RuntimeException { + + private static final long serialVersionUID = 5861310537366287163L; + + public ResourceNotFoundException() { + super(); + } + + public ResourceNotFoundException(final String message, final Throwable cause) { + super(message, cause); + } + + public ResourceNotFoundException(final String message) { + super(message); + } + + public ResourceNotFoundException(final Throwable cause) { + super(cause); + } +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/model/Order.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/model/Order.java new file mode 100644 index 0000000000..5b91bc0956 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/model/Order.java @@ -0,0 +1,78 @@ +package com.baeldung.ecommerce.model; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonIdentityInfo; +import com.fasterxml.jackson.annotation.JsonManagedReference; +import com.fasterxml.jackson.annotation.ObjectIdGenerators; + +import javax.persistence.*; +import javax.validation.Valid; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; + +@Entity +@Table(name = "orders") +@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="orderProducts") +public class Order { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @JsonFormat(pattern = "dd/MM/yyyy") private LocalDate dateCreated; + + private String status; + + @OneToMany(mappedBy = "pk.order") + @Valid + private List orderProducts = new ArrayList<>(); + + @Transient + public Double getTotalOrderPrice() { + double sum = 0D; + List orderProducts = getOrderProducts(); + for (OrderProduct op : orderProducts) { + sum += op.getTotalPrice(); + } + + return sum; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public LocalDate getDateCreated() { + return dateCreated; + } + + public void setDateCreated(LocalDate dateCreated) { + this.dateCreated = dateCreated; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public List getOrderProducts() { + return orderProducts; + } + + public void setOrderProducts(List orderProducts) { + this.orderProducts = orderProducts; + } + + @Transient + public int getNumberOfProducts() { + return this.orderProducts.size(); + } +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/model/OrderProduct.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/model/OrderProduct.java new file mode 100644 index 0000000000..eb1b9876c3 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/model/OrderProduct.java @@ -0,0 +1,87 @@ +package com.baeldung.ecommerce.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +import javax.persistence.Column; +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; +import javax.persistence.Transient; + +@Entity +public class OrderProduct { + + @EmbeddedId + @JsonIgnore + private OrderProductPK pk; + + @Column(nullable = false) private Integer quantity; + + public OrderProduct() { + super(); + } + + public OrderProduct(Order order, Product product, Integer quantity) { + pk = new OrderProductPK(); + pk.setOrder(order); + pk.setProduct(product); + this.quantity = quantity; + } + + @Transient + public Product getProduct() { + return this.pk.getProduct(); + } + + @Transient + public Double getTotalPrice() { + return getProduct().getPrice() * getQuantity(); + } + + public OrderProductPK getPk() { + return pk; + } + + public void setPk(OrderProductPK pk) { + this.pk = pk; + } + + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((pk == null) ? 0 : pk.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; + } + OrderProduct other = (OrderProduct) obj; + if (pk == null) { + if (other.pk != null) { + return false; + } + } else if (!pk.equals(other.pk)) { + return false; + } + + return true; + } +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/model/OrderProductPK.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/model/OrderProductPK.java new file mode 100644 index 0000000000..8440a363c1 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/model/OrderProductPK.java @@ -0,0 +1,91 @@ +package com.baeldung.ecommerce.model; + +import com.fasterxml.jackson.annotation.JsonIdentityInfo; +import com.fasterxml.jackson.annotation.ObjectIdGenerators; + +import javax.persistence.Embeddable; +import javax.persistence.FetchType; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import java.io.Serializable; + +@Embeddable +@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "order") +public class OrderProductPK implements Serializable { + + private static final long serialVersionUID = 476151177562655457L; + + @ManyToOne(optional = false, fetch = FetchType.LAZY) + @JoinColumn(name = "order_id") + private Order order; + + @ManyToOne(optional = false, fetch = FetchType.LAZY) + @JoinColumn(name = "product_id") + private Product product; + + public Order getOrder() { + return order; + } + + public void setOrder(Order order) { + this.order = order; + } + + public Product getProduct() { + return product; + } + + public void setProduct(Product product) { + this.product = product; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + + result = prime * result + ((order.getId() == null) + ? 0 + : order + .getId() + .hashCode()); + result = prime * result + ((product.getId() == null) + ? 0 + : product + .getId() + .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; + } + OrderProductPK other = (OrderProductPK) obj; + if (order == null) { + if (other.order != null) { + return false; + } + } else if (!order.equals(other.order)) { + return false; + } + + if (product == null) { + if (other.product != null) { + return false; + } + } else if (!product.equals(other.product)) { + return false; + } + + return true; + } +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/model/OrderStatus.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/model/OrderStatus.java new file mode 100644 index 0000000000..36bcd5e30d --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/model/OrderStatus.java @@ -0,0 +1,5 @@ +package com.baeldung.ecommerce.model; + +public enum OrderStatus { + PAID +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/model/Product.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/model/Product.java new file mode 100644 index 0000000000..fe2061fab5 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/model/Product.java @@ -0,0 +1,62 @@ +package com.baeldung.ecommerce.model; + +import javax.persistence.*; +import javax.validation.constraints.NotNull; + +@Entity +public class Product { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @NotNull(message = "Product name is required.") + @Basic(optional = false) + private String name; + + private Double price; + + private String pictureUrl; + + public Product(Long id, @NotNull(message = "Product name is required.") String name, Double price, String pictureUrl) { + this.id = id; + this.name = name; + this.price = price; + this.pictureUrl = pictureUrl; + } + + public Product() { + } + + 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 Double getPrice() { + return price; + } + + public void setPrice(Double price) { + this.price = price; + } + + public String getPictureUrl() { + return pictureUrl; + } + + public void setPictureUrl(String pictureUrl) { + this.pictureUrl = pictureUrl; + } +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/repository/OrderProductRepository.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/repository/OrderProductRepository.java new file mode 100644 index 0000000000..f596ef8520 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/repository/OrderProductRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.ecommerce.repository; + +import com.baeldung.ecommerce.model.OrderProduct; +import com.baeldung.ecommerce.model.OrderProductPK; +import org.springframework.data.repository.CrudRepository; + +public interface OrderProductRepository extends CrudRepository { +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/repository/OrderRepository.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/repository/OrderRepository.java new file mode 100644 index 0000000000..c6ed21707a --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/repository/OrderRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.ecommerce.repository; + +import com.baeldung.ecommerce.model.Order; +import org.springframework.data.repository.CrudRepository; + +public interface OrderRepository extends CrudRepository { +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/repository/ProductRepository.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/repository/ProductRepository.java new file mode 100644 index 0000000000..ff56b54527 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/repository/ProductRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.ecommerce.repository; + +import com.baeldung.ecommerce.model.Product; +import org.springframework.data.repository.CrudRepository; + +public interface ProductRepository extends CrudRepository { +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/service/OrderProductService.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/service/OrderProductService.java new file mode 100644 index 0000000000..575cd68e88 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/service/OrderProductService.java @@ -0,0 +1,13 @@ +package com.baeldung.ecommerce.service; + +import com.baeldung.ecommerce.model.OrderProduct; +import org.springframework.validation.annotation.Validated; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + +@Validated +public interface OrderProductService { + + OrderProduct create(@NotNull(message = "The products for order cannot be null.") @Valid OrderProduct orderProduct); +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/service/OrderProductServiceImpl.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/service/OrderProductServiceImpl.java new file mode 100644 index 0000000000..239201d929 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/service/OrderProductServiceImpl.java @@ -0,0 +1,22 @@ +package com.baeldung.ecommerce.service; + +import com.baeldung.ecommerce.model.OrderProduct; +import com.baeldung.ecommerce.repository.OrderProductRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +public class OrderProductServiceImpl implements OrderProductService { + + private OrderProductRepository orderProductRepository; + + public OrderProductServiceImpl(OrderProductRepository orderProductRepository) { + this.orderProductRepository = orderProductRepository; + } + + @Override + public OrderProduct create(OrderProduct orderProduct) { + return this.orderProductRepository.save(orderProduct); + } +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/service/OrderService.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/service/OrderService.java new file mode 100644 index 0000000000..babc5f88c6 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/service/OrderService.java @@ -0,0 +1,17 @@ +package com.baeldung.ecommerce.service; + +import com.baeldung.ecommerce.model.Order; +import org.springframework.validation.annotation.Validated; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + +@Validated +public interface OrderService { + + @NotNull Iterable getAllOrders(); + + Order create(@NotNull(message = "The order cannot be null.") @Valid Order order); + + void update(@NotNull(message = "The order cannot be null.") @Valid Order order); +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/service/OrderServiceImpl.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/service/OrderServiceImpl.java new file mode 100644 index 0000000000..2833cfcfb6 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/service/OrderServiceImpl.java @@ -0,0 +1,36 @@ +package com.baeldung.ecommerce.service; + +import com.baeldung.ecommerce.model.Order; +import com.baeldung.ecommerce.repository.OrderRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDate; + +@Service +@Transactional +public class OrderServiceImpl implements OrderService { + + private OrderRepository orderRepository; + + public OrderServiceImpl(OrderRepository orderRepository) { + this.orderRepository = orderRepository; + } + + @Override + public Iterable getAllOrders() { + return this.orderRepository.findAll(); + } + + @Override + public Order create(Order order) { + order.setDateCreated(LocalDate.now()); + + return this.orderRepository.save(order); + } + + @Override + public void update(Order order) { + this.orderRepository.save(order); + } +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/service/ProductService.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/service/ProductService.java new file mode 100644 index 0000000000..0887f326cb --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/service/ProductService.java @@ -0,0 +1,17 @@ +package com.baeldung.ecommerce.service; + +import com.baeldung.ecommerce.model.Product; +import org.springframework.validation.annotation.Validated; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; + +@Validated +public interface ProductService { + + @NotNull Iterable getAllProducts(); + + Product getProduct(@Min(value = 1L, message = "Invalid product ID.") long id); + + Product save(Product product); +} diff --git a/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/service/ProductServiceImpl.java b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/service/ProductServiceImpl.java new file mode 100644 index 0000000000..af0cc1aaa8 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/java/com/baeldung/ecommerce/service/ProductServiceImpl.java @@ -0,0 +1,35 @@ +package com.baeldung.ecommerce.service; + +import com.baeldung.ecommerce.exception.ResourceNotFoundException; +import com.baeldung.ecommerce.model.Product; +import com.baeldung.ecommerce.repository.ProductRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +public class ProductServiceImpl implements ProductService { + + private ProductRepository productRepository; + + public ProductServiceImpl(ProductRepository productRepository) { + this.productRepository = productRepository; + } + + @Override + public Iterable getAllProducts() { + return productRepository.findAll(); + } + + @Override + public Product getProduct(long id) { + return productRepository + .findById(id) + .orElseThrow(() -> new ResourceNotFoundException("Product not found")); + } + + @Override + public Product save(Product product) { + return productRepository.save(product); + } +} diff --git a/spring-boot-angular-ecommerce/src/main/resources/application.properties b/spring-boot-angular-ecommerce/src/main/resources/application.properties new file mode 100644 index 0000000000..63a81576af --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/resources/application.properties @@ -0,0 +1,8 @@ +management.security.enabled=false + +spring.datasource.name=ecommercedb +spring.jpa.show-sql=false + +#H2 settings +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console diff --git a/spring-boot-angular-ecommerce/src/main/resources/logback.xml b/spring-boot-angular-ecommerce/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot-angular-ecommerce/src/test/java/com/baeldung/ecommerce/EcommerceApplicationIntegrationTest.java b/spring-boot-angular-ecommerce/src/test/java/com/baeldung/ecommerce/EcommerceApplicationIntegrationTest.java new file mode 100644 index 0000000000..03450ea7b2 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/test/java/com/baeldung/ecommerce/EcommerceApplicationIntegrationTest.java @@ -0,0 +1,100 @@ +package com.baeldung.ecommerce; + +import com.baeldung.ecommerce.controller.OrderController; +import com.baeldung.ecommerce.controller.ProductController; +import com.baeldung.ecommerce.dto.OrderProductDto; +import com.baeldung.ecommerce.model.Order; +import com.baeldung.ecommerce.model.Product; +import org.assertj.core.api.Assertions; +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.boot.web.server.LocalServerPort; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.Collections; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasProperty; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { EcommerceApplication.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class EcommerceApplicationIntegrationTest { + + @Autowired private TestRestTemplate restTemplate; + + @LocalServerPort private int port; + + @Autowired private ProductController productController; + + @Autowired private OrderController orderController; + + @Test + public void contextLoads() { + Assertions + .assertThat(productController) + .isNotNull(); + Assertions + .assertThat(orderController) + .isNotNull(); + } + + @Test + public void givenGetProductsApiCall_whenProductListRetrieved_thenSizeMatchAndListContainsProductNames() { + ResponseEntity> responseEntity = restTemplate.exchange("http://localhost:" + port + "/api/products", HttpMethod.GET, null, new ParameterizedTypeReference>() { + }); + Iterable products = responseEntity.getBody(); + Assertions + .assertThat(products) + .hasSize(7); + + assertThat(products, hasItem(hasProperty("name", is("TV Set")))); + assertThat(products, hasItem(hasProperty("name", is("Game Console")))); + assertThat(products, hasItem(hasProperty("name", is("Sofa")))); + assertThat(products, hasItem(hasProperty("name", is("Icecream")))); + assertThat(products, hasItem(hasProperty("name", is("Beer")))); + assertThat(products, hasItem(hasProperty("name", is("Phone")))); + assertThat(products, hasItem(hasProperty("name", is("Watch")))); + } + + @Test + public void givenGetOrdersApiCall_whenProductListRetrieved_thenSizeMatchAndListContainsProductNames() { + ResponseEntity> responseEntity = restTemplate.exchange("http://localhost:" + port + "/api/orders", HttpMethod.GET, null, new ParameterizedTypeReference>() { + }); + + Iterable orders = responseEntity.getBody(); + Assertions + .assertThat(orders) + .hasSize(0); + } + + @Test + public void givenPostOrder_whenBodyRequestMatcherJson_thenResponseContainsEqualObjectProperties() { + final ResponseEntity postResponse = restTemplate.postForEntity("http://localhost:" + port + "/api/orders", prepareOrderForm(), Order.class); + Order order = postResponse.getBody(); + Assertions + .assertThat(postResponse.getStatusCode()) + .isEqualByComparingTo(HttpStatus.CREATED); + + assertThat(order, hasProperty("status", is("PAID"))); + assertThat(order.getOrderProducts(), hasItem(hasProperty("quantity", is(2)))); + } + + private OrderController.OrderForm prepareOrderForm() { + OrderController.OrderForm orderForm = new OrderController.OrderForm(); + OrderProductDto productDto = new OrderProductDto(); + productDto.setProduct(new Product(1L, "TV Set", 300.00, "http://placehold.it/200x100")); + productDto.setQuantity(2); + orderForm.setProductOrders(Collections.singletonList(productDto)); + + return orderForm; + } +} diff --git a/spring-boot-autoconfiguration/pom.xml b/spring-boot-autoconfiguration/pom.xml index 2687fcd969..b88587f731 100644 --- a/spring-boot-autoconfiguration/pom.xml +++ b/spring-boot-autoconfiguration/pom.xml @@ -1,5 +1,5 @@ + 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-boot-autoconfiguration @@ -37,9 +37,8 @@ mysql mysql-connector-java - 8.0.11 - + spring-boot @@ -79,6 +78,7 @@ **/*LiveTest.java **/*IntegrationTest.java + **/*IntTest.java **/AutoconfigurationTest.java @@ -97,7 +97,6 @@ - 3.1.1 3.3.7-1 diff --git a/spring-boot-autoconfiguration/src/main/resources/logback.xml b/spring-boot-autoconfiguration/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-autoconfiguration/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot-bootstrap/README.md b/spring-boot-bootstrap/README.md index ec6905bf6a..519b36ce4f 100644 --- a/spring-boot-bootstrap/README.md +++ b/spring-boot-bootstrap/README.md @@ -1,3 +1,4 @@ ### 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) +- [Thin JARs with Spring Boot](http://www.baeldung.com/spring-boot-thin-jar) diff --git a/spring-boot-bootstrap/cloudfoundry/manifest.yml b/spring-boot-bootstrap/cloudfoundry/manifest.yml new file mode 100755 index 0000000000..80fce8ff4b --- /dev/null +++ b/spring-boot-bootstrap/cloudfoundry/manifest.yml @@ -0,0 +1,10 @@ +--- +applications: +- name: spring-boot-bootstrap + memory: 768M + random-route: true + path: ../target/spring-boot-bootstrap-cf.jar + env: + SPRING_PROFILES_ACTIVE: cloud,mysql + services: + - spring-bootstrap-db diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index 03ce9b6906..c1ce4df6e2 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -14,25 +14,17 @@ 0.0.1-SNAPSHOT ../parent-boot-2 - - @@ -47,10 +39,22 @@ org.springframework.boot spring-boot-starter-data-jpa + + org.springframework.cloud + spring-cloud-starter + + + org.springframework.boot + spring-boot-starter-cloud-connectors + com.h2database h2 + + mysql + mysql-connector-java + org.springframework.boot spring-boot-starter-security @@ -63,17 +67,58 @@ io.rest-assured rest-assured - 3.0.3 + ${rest-assured.version} test javax.servlet javax.servlet-api - 4.0.0 + ${servlet.version} + + cloudfoundry + + + org.springframework.cloud + spring-cloud-starter + + + org.springframework.boot + spring-boot-starter-cloud-connectors + + + + + + src/main/resources + + **/logback.xml + + + + + + org.springframework.boot + spring-boot-maven-plugin + + ${project.name}-cf + + + + org.apache.maven.plugins + maven-compiler-plugin + + + **/cloud/config/*.java + + + + + + autoconfiguration @@ -91,6 +136,7 @@ **/*LiveTest.java **/*IntegrationTest.java + **/*IntTest.java **/AutoconfigurationTest.java @@ -107,12 +153,44 @@ + + thin-jar + + + + org.springframework.boot.experimental + spring-boot-thin-maven-plugin + ${thin.version} + + + + resolve + + resolve + + false + + + + + + - + + + + org.apache.maven.plugins + maven-compiler-plugin + + + **/cloud/*.java + + + + + - UTF-8 - UTF-8 - 1.8 + 4.0.0 diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/cloud/config/CloudDataSourceConfig.java b/spring-boot-bootstrap/src/main/java/org/baeldung/cloud/config/CloudDataSourceConfig.java new file mode 100755 index 0000000000..b9f9598ca3 --- /dev/null +++ b/spring-boot-bootstrap/src/main/java/org/baeldung/cloud/config/CloudDataSourceConfig.java @@ -0,0 +1,19 @@ +package org.baeldung.cloud.config; + +import org.springframework.cloud.config.java.AbstractCloudConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +import javax.sql.DataSource; + +@Configuration +@Profile("cloud") +public class CloudDataSourceConfig extends AbstractCloudConfig { + + @Bean + public DataSource dataSource() { + return connectionFactory().dataSource(); + } + +} diff --git a/spring-boot-bootstrap/src/main/resources/application-local.properties b/spring-boot-bootstrap/src/main/resources/application-local.properties new file mode 100644 index 0000000000..8c1c677988 --- /dev/null +++ b/spring-boot-bootstrap/src/main/resources/application-local.properties @@ -0,0 +1,20 @@ +server.port = 8081 + +spring.application.name = Bootstrap Spring Boot + +spring.thymeleaf.cache = false +spring.thymeleaf.enabled=true +spring.thymeleaf.prefix=classpath:/templates/ +spring.thymeleaf.suffix=.html + +spring.security.user.name=john +spring.security.user.password=123 + +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.url=jdbc:h2:mem:bootapp;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE +spring.datasource.username=sa +spring.datasource.password= +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + +server.error.path=/error +server.error.whitelabel.enabled=false \ No newline at end of file diff --git a/spring-boot-bootstrap/src/main/resources/application-mysql.properties b/spring-boot-bootstrap/src/main/resources/application-mysql.properties new file mode 100644 index 0000000000..a1823b5d7f --- /dev/null +++ b/spring-boot-bootstrap/src/main/resources/application-mysql.properties @@ -0,0 +1 @@ +spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect \ No newline at end of file diff --git a/spring-boot-bootstrap/src/main/resources/application.properties b/spring-boot-bootstrap/src/main/resources/application.properties index e50268d32c..eee89ca460 100644 --- a/spring-boot-bootstrap/src/main/resources/application.properties +++ b/spring-boot-bootstrap/src/main/resources/application.properties @@ -1,19 +1,11 @@ -server.port = 8081 - -spring.application.name = Bootstrap Spring Boot - +server.port=${port:8080} +spring.application.name = Bootstrap Spring Cloud spring.thymeleaf.cache = false spring.thymeleaf.enabled=true spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html -spring.security.user.name=john -spring.security.user.password=123 - -spring.datasource.driver-class-name=org.h2.Driver -spring.datasource.url=jdbc:h2:mem:bootapp;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE -spring.datasource.username=sa -spring.datasource.password= - server.error.path=/error -server.error.whitelabel.enabled=false \ No newline at end of file +server.error.whitelabel.enabled=false + +spring.jpa.generate-ddl=true \ No newline at end of file diff --git a/spring-boot-bootstrap/src/main/resources/logback.xml b/spring-boot-bootstrap/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-bootstrap/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/camel-api/README.md b/spring-boot-camel/README.md similarity index 100% rename from camel-api/README.md rename to spring-boot-camel/README.md diff --git a/spring-boot-camel/pom.xml b/spring-boot-camel/pom.xml new file mode 100644 index 0000000000..f04e8e34f7 --- /dev/null +++ b/spring-boot-camel/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + com.example + spring-boot-camel + 0.0.1-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.apache.camel + camel-servlet-starter + ${camel.version} + + + org.apache.camel + camel-jackson-starter + ${camel.version} + + + org.apache.camel + camel-swagger-java-starter + ${camel.version} + + + org.apache.camel + camel-spring-boot-starter + ${camel.version} + + + org.springframework.boot + spring-boot-starter-web + ${spring-boot-starter.version} + + + + + spring-boot:run + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-starter.version} + + + + repackage + + + + + + + + + 2.19.1 + 1.5.4.RELEASE + + + diff --git a/camel-api/src/main/java/com/baeldung/camel/Application.java b/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java similarity index 100% rename from camel-api/src/main/java/com/baeldung/camel/Application.java rename to spring-boot-camel/src/main/java/com/baeldung/camel/Application.java diff --git a/camel-api/src/main/java/com/baeldung/camel/ExampleServices.java b/spring-boot-camel/src/main/java/com/baeldung/camel/ExampleServices.java similarity index 100% rename from camel-api/src/main/java/com/baeldung/camel/ExampleServices.java rename to spring-boot-camel/src/main/java/com/baeldung/camel/ExampleServices.java diff --git a/camel-api/src/main/java/com/baeldung/camel/MyBean.java b/spring-boot-camel/src/main/java/com/baeldung/camel/MyBean.java similarity index 100% rename from camel-api/src/main/java/com/baeldung/camel/MyBean.java rename to spring-boot-camel/src/main/java/com/baeldung/camel/MyBean.java diff --git a/camel-api/src/main/resources/application.properties b/spring-boot-camel/src/main/resources/application.properties similarity index 100% rename from camel-api/src/main/resources/application.properties rename to spring-boot-camel/src/main/resources/application.properties diff --git a/camel-api/src/main/resources/application.yml b/spring-boot-camel/src/main/resources/application.yml similarity index 100% rename from camel-api/src/main/resources/application.yml rename to spring-boot-camel/src/main/resources/application.yml diff --git a/camel-api/src/main/resources/logback.xml b/spring-boot-camel/src/main/resources/logback.xml similarity index 100% rename from camel-api/src/main/resources/logback.xml rename to spring-boot-camel/src/main/resources/logback.xml diff --git a/spring-boot-client/.gitignore b/spring-boot-client/.gitignore new file mode 100644 index 0000000000..da7c2c5c0a --- /dev/null +++ b/spring-boot-client/.gitignore @@ -0,0 +1,5 @@ +/target/ +.settings/ +.classpath +.project + diff --git a/spring-boot-client/README.MD b/spring-boot-client/README.MD new file mode 100644 index 0000000000..8db48089a5 --- /dev/null +++ b/spring-boot-client/README.MD @@ -0,0 +1,7 @@ +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: + +- [Quick Guide to @RestClientTest in Spring Boot](http://www.baeldung.com/restclienttest-in-spring-boot) +- [A Java Client for a WebSockets API](http://www.baeldung.com/websockets-api-java-spring-client) \ No newline at end of file diff --git a/spring-boot-client/pom.xml b/spring-boot-client/pom.xml new file mode 100644 index 0000000000..fc89931f79 --- /dev/null +++ b/spring-boot-client/pom.xml @@ -0,0 +1,141 @@ + + 4.0.0 + com.baeldung + spring-boot-client + 0.0.1-SNAPSHOT + war + spring-boot-client + This is simple boot client application for Spring boot actuator test + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + org.junit.platform + junit-platform-launcher + ${junit-platform.version} + test + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + com.h2database + h2 + + + org.springframework.boot + spring-boot-starter + + + com.google.guava + guava + ${guava.version} + + + org.springframework + spring-websocket + + + org.springframework + spring-messaging + + + + + + spring-boot-client + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-war-plugin + + + + pl.project13.maven + git-commit-id-plugin + ${git-commit-id-plugin.version} + + + + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + + + + 18.0 + 1.2.0 + 2.2.4 + + + \ No newline at end of file diff --git a/spring-boot-client/src/main/java/org/baeldung/boot/Application.java b/spring-boot-client/src/main/java/org/baeldung/boot/Application.java new file mode 100644 index 0000000000..c1b6558b26 --- /dev/null +++ b/spring-boot-client/src/main/java/org/baeldung/boot/Application.java @@ -0,0 +1,14 @@ +package org.baeldung.boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; + +@SpringBootApplication +public class Application { + private static ApplicationContext applicationContext; + + public static void main(String[] args) { + applicationContext = SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/client/Details.java b/spring-boot-client/src/main/java/org/baeldung/boot/client/Details.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/client/Details.java rename to spring-boot-client/src/main/java/org/baeldung/boot/client/Details.java diff --git a/spring-boot/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java b/spring-boot-client/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java rename to spring-boot-client/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java diff --git a/spring-boot/src/main/java/org/baeldung/websocket/client/Message.java b/spring-boot-client/src/main/java/org/baeldung/websocket/client/Message.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/websocket/client/Message.java rename to spring-boot-client/src/main/java/org/baeldung/websocket/client/Message.java diff --git a/spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java b/spring-boot-client/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java rename to spring-boot-client/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java diff --git a/spring-boot/src/main/java/org/baeldung/websocket/client/StompClient.java b/spring-boot-client/src/main/java/org/baeldung/websocket/client/StompClient.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/websocket/client/StompClient.java rename to spring-boot-client/src/main/java/org/baeldung/websocket/client/StompClient.java diff --git a/spring-boot-client/src/main/resources/logback.xml b/spring-boot-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/spring-boot-client/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java b/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java rename to spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java diff --git a/spring-boot/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java b/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java similarity index 91% rename from spring-boot/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java rename to spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java index 37fc202e8a..71fb330663 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java +++ b/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java @@ -1,23 +1,24 @@ package org.baeldung.boot.client; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.client.MockRestServiceServer; - import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; -import org.baeldung.boot.client.Details; -import org.baeldung.boot.client.DetailsServiceClient; +import org.baeldung.boot.Application; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.client.MockRestServiceServer; + +import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) @RestClientTest(DetailsServiceClient.class) public class DetailsServiceClientIntegrationTest { diff --git a/spring-boot-ctx-fluent/README.md b/spring-boot-ctx-fluent/README.md new file mode 100644 index 0000000000..0b4b9c1271 --- /dev/null +++ b/spring-boot-ctx-fluent/README.md @@ -0,0 +1,4 @@ + +### Relevant Articles: + +- [Context Hierarchy with the Spring Boot Fluent Builder API](http://www.baeldung.com/spring-boot-context-hierarchy) diff --git a/spring-boot-ctx-fluent/pom.xml b/spring-boot-ctx-fluent/pom.xml new file mode 100644 index 0000000000..f9b691aea7 --- /dev/null +++ b/spring-boot-ctx-fluent/pom.xml @@ -0,0 +1,24 @@ + + 4.0.0 + + com.baeldung + spring-boot-ctx-fluent + 0.0.1-SNAPSHOT + jar + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Config.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Config.java new file mode 100644 index 0000000000..0bacc5e8fe --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Config.java @@ -0,0 +1,22 @@ +package com.baeldung.ctx1; + +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +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 com.baeldung.parent.IHomeService; + +@Configuration +@ComponentScan("com.baeldung.ctx1") +@PropertySource("classpath:ctx1.properties") +@EnableAutoConfiguration +public class Ctx1Config { + + @Bean + public IHomeService homeService() { + return new GreetingService(); + } + +} diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Controller.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Controller.java new file mode 100644 index 0000000000..9c7667db35 --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Controller.java @@ -0,0 +1,22 @@ +package com.baeldung.ctx1; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.baeldung.parent.IHomeService; + +@Controller +public class Ctx1Controller { + + @Autowired + IHomeService homeService; + + @GetMapping("/home") + @ResponseBody + public String greeting() { + + return homeService.getGreeting(); + } +} diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/GreetingService.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/GreetingService.java new file mode 100644 index 0000000000..a0f1f16288 --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/GreetingService.java @@ -0,0 +1,13 @@ +package com.baeldung.ctx1; + +import org.springframework.stereotype.Service; + +import com.baeldung.parent.IHomeService; + +@Service +public class GreetingService implements IHomeService { + + public String getGreeting() { + return "Greetings for the day"; + } +} diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Config.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Config.java new file mode 100644 index 0000000000..fc08b741f3 --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Config.java @@ -0,0 +1,14 @@ +package com.baeldung.ctx2; + +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; + +@Configuration +@ComponentScan("com.baeldung.ctx2") +@EnableAutoConfiguration +@PropertySource("classpath:ctx2.properties") +public class Ctx2Config { + +} diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Controller.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Controller.java new file mode 100644 index 0000000000..850fd8021c --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Controller.java @@ -0,0 +1,19 @@ +package com.baeldung.ctx2; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.parent.IHomeService; + +@RestController +public class Ctx2Controller { + + @Autowired + IHomeService homeService; + + @GetMapping(value = "/greeting", produces = "application/json") + public String getGreeting() { + return homeService.getGreeting(); + } +} diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/App.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/App.java new file mode 100644 index 0000000000..609751bc0f --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/App.java @@ -0,0 +1,19 @@ +package com.baeldung.parent; + +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.builder.SpringApplicationBuilder; + +import com.baeldung.ctx1.Ctx1Config; +import com.baeldung.ctx2.Ctx2Config; + +public class App { + public static void main(String[] args) { + new SpringApplicationBuilder().parent(ParentConfig.class) + .web(WebApplicationType.NONE) + .child(Ctx1Config.class) + .web(WebApplicationType.SERVLET) + .sibling(Ctx2Config.class) + .web(WebApplicationType.SERVLET) + .run(args); + } +} diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/HomeService.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/HomeService.java new file mode 100644 index 0000000000..0d23e26cce --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/HomeService.java @@ -0,0 +1,11 @@ +package com.baeldung.parent; + +import org.springframework.stereotype.Service; + +@Service +public class HomeService implements IHomeService { + + public String getGreeting() { + return "Welcome User"; + } +} diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/IHomeService.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/IHomeService.java new file mode 100644 index 0000000000..264e49861a --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/IHomeService.java @@ -0,0 +1,6 @@ +package com.baeldung.parent; + +public interface IHomeService { + + String getGreeting(); +} diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/ParentConfig.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/ParentConfig.java new file mode 100644 index 0000000000..484d020cc0 --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/ParentConfig.java @@ -0,0 +1,8 @@ +package com.baeldung.parent; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.parent") +public class ParentConfig {} diff --git a/spring-boot-ctx-fluent/src/main/resources/ctx1.properties b/spring-boot-ctx-fluent/src/main/resources/ctx1.properties new file mode 100644 index 0000000000..2b618d4177 --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/resources/ctx1.properties @@ -0,0 +1,5 @@ +server.port=8081 +server.servlet.context-path=/ctx1 +#logging.level=debug +spring.application.admin.enabled=false +spring.application.admin.jmx-name=org.springframework.boot:type=AdminRest,name=SpringRestApplication \ No newline at end of file diff --git a/spring-boot-ctx-fluent/src/main/resources/ctx2.properties b/spring-boot-ctx-fluent/src/main/resources/ctx2.properties new file mode 100644 index 0000000000..f3599e17e0 --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/resources/ctx2.properties @@ -0,0 +1,5 @@ +server.port=8082 +server.servlet.context-path=/ctx2 + +spring.application.admin.enabled=false +spring.application.admin.jmx-name=org.springframework.boot:type=WebAdmin,name=SpringWebApplication \ No newline at end of file diff --git a/spring-boot-ctx-fluent/src/main/resources/logback.xml b/spring-boot-ctx-fluent/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot-custom-starter/README.md b/spring-boot-custom-starter/README.md index 5b05394d6e..f983441ca0 100644 --- a/spring-boot-custom-starter/README.md +++ b/spring-boot-custom-starter/README.md @@ -1,2 +1,12 @@ ### Relevant Articles: - [Creating a Custom Starter with Spring Boot](http://www.baeldung.com/spring-boot-custom-starter) + +- **greeter-library**: The sample library that we're creating the starter for. + +- **greeter-spring-boot-autoconfigure**: The project containing the auto-configuration for the library. + +- **greeter-spring-boot-starter**: The custom starter for the library. + +- **greeter-spring-boot-sample-app**: The sample project that uses the custom starter. + +- [Multi-Module Project With Spring Boot](http://www.baeldung.com/spring-boot-multiple-modules) diff --git a/spring-boot-custom-starter/greeter/README.md b/spring-boot-custom-starter/greeter-library/README.md similarity index 100% rename from spring-boot-custom-starter/greeter/README.md rename to spring-boot-custom-starter/greeter-library/README.md diff --git a/spring-boot-custom-starter/greeter-library/pom.xml b/spring-boot-custom-starter/greeter-library/pom.xml new file mode 100644 index 0000000000..3717ba005c --- /dev/null +++ b/spring-boot-custom-starter/greeter-library/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + + com.baeldung + greeter-library + 0.0.1-SNAPSHOT + + spring-boot-custom-starter + com.baeldung + 0.0.1-SNAPSHOT + ../../spring-boot-custom-starter + + \ No newline at end of file diff --git a/spring-boot-custom-starter/greeter/src/main/java/com/baeldung/greeter/Greeter.java b/spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/Greeter.java similarity index 90% rename from spring-boot-custom-starter/greeter/src/main/java/com/baeldung/greeter/Greeter.java rename to spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/Greeter.java index 970561d1fd..50fb31ddcb 100644 --- a/spring-boot-custom-starter/greeter/src/main/java/com/baeldung/greeter/Greeter.java +++ b/spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/Greeter.java @@ -1,6 +1,6 @@ -package com.baeldung.greeter; +package com.baeldung.greeter.library; -import static com.baeldung.greeter.GreeterConfigParams.*; +import static com.baeldung.greeter.library.GreeterConfigParams.*; import java.time.LocalDateTime; diff --git a/spring-boot-custom-starter/greeter/src/main/java/com/baeldung/greeter/GreeterConfigParams.java b/spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/GreeterConfigParams.java similarity index 90% rename from spring-boot-custom-starter/greeter/src/main/java/com/baeldung/greeter/GreeterConfigParams.java rename to spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/GreeterConfigParams.java index fa30b0f312..14cef3e92d 100644 --- a/spring-boot-custom-starter/greeter/src/main/java/com/baeldung/greeter/GreeterConfigParams.java +++ b/spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/GreeterConfigParams.java @@ -1,4 +1,4 @@ -package com.baeldung.greeter; +package com.baeldung.greeter.library; public class GreeterConfigParams { diff --git a/spring-boot-custom-starter/greeter/src/main/java/com/baeldung/greeter/GreetingConfig.java b/spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/GreetingConfig.java similarity index 80% rename from spring-boot-custom-starter/greeter/src/main/java/com/baeldung/greeter/GreetingConfig.java rename to spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/GreetingConfig.java index fbbe11cf4f..23d4ac0a0d 100644 --- a/spring-boot-custom-starter/greeter/src/main/java/com/baeldung/greeter/GreetingConfig.java +++ b/spring-boot-custom-starter/greeter-library/src/main/java/com/baeldung/greeter/library/GreetingConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.greeter; +package com.baeldung.greeter.library; import java.util.Properties; diff --git a/spring-boot-custom-starter/greeter-library/src/main/resources/logback.xml b/spring-boot-custom-starter/greeter-library/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-custom-starter/greeter-library/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot-custom-starter/greeter/src/test/java/com/baeldung/greeter/GreeterIntegrationTest.java b/spring-boot-custom-starter/greeter-library/src/test/java/com/baeldung/greeter/GreeterIntegrationTest.java similarity index 92% rename from spring-boot-custom-starter/greeter/src/test/java/com/baeldung/greeter/GreeterIntegrationTest.java rename to spring-boot-custom-starter/greeter-library/src/test/java/com/baeldung/greeter/GreeterIntegrationTest.java index 787f795480..2b09ecc615 100644 --- a/spring-boot-custom-starter/greeter/src/test/java/com/baeldung/greeter/GreeterIntegrationTest.java +++ b/spring-boot-custom-starter/greeter-library/src/test/java/com/baeldung/greeter/GreeterIntegrationTest.java @@ -1,10 +1,12 @@ package com.baeldung.greeter; -import static com.baeldung.greeter.GreeterConfigParams.*; +import static com.baeldung.greeter.library.GreeterConfigParams.*; import static org.junit.Assert.assertEquals; import java.time.LocalDateTime; +import com.baeldung.greeter.library.Greeter; +import com.baeldung.greeter.library.GreetingConfig; import org.junit.BeforeClass; import org.junit.Test; diff --git a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml index 6ae6572ca9..9c2d85da86 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml +++ b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml @@ -5,17 +5,13 @@ com.baeldung greeter-spring-boot-autoconfigure 0.0.1-SNAPSHOT + - parent-boot-5 + spring-boot-custom-starter com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../spring-boot-custom-starter - - UTF-8 - 1.5.2.RELEASE - 0.0.1-SNAPSHOT - @@ -40,7 +36,7 @@ com.baeldung - greeter + greeter-library ${greeter.version} true @@ -52,13 +48,20 @@ org.apache.maven.plugins maven-compiler-plugin - 3.7.0 + ${maven-compiler-plugin.version} - 1.8 - 1.8 + ${java.version} + ${java.version} + + UTF-8 + 1.5.2.RELEASE + 0.0.1-SNAPSHOT + + +
    \ No newline at end of file diff --git a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/java/com/baeldung/greeter/autoconfigure/GreeterAutoConfiguration.java b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/java/com/baeldung/greeter/autoconfigure/GreeterAutoConfiguration.java index 4cf078aa00..ae3f88f9ff 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/java/com/baeldung/greeter/autoconfigure/GreeterAutoConfiguration.java +++ b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/java/com/baeldung/greeter/autoconfigure/GreeterAutoConfiguration.java @@ -1,6 +1,6 @@ package com.baeldung.greeter.autoconfigure; -import static com.baeldung.greeter.GreeterConfigParams.*; +import static com.baeldung.greeter.library.GreeterConfigParams.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -9,8 +9,8 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.baeldung.greeter.Greeter; -import com.baeldung.greeter.GreetingConfig; +import com.baeldung.greeter.library.Greeter; +import com.baeldung.greeter.library.GreetingConfig; @Configuration @ConditionalOnClass(Greeter.class) diff --git a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/resources/logback.xml b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml b/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml index 9db76759ec..4eac7eba19 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml +++ b/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml @@ -1,5 +1,5 @@ + 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 @@ -7,25 +7,22 @@ 0.0.1-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 - - 0.0.1-SNAPSHOT - - - com.baeldung greeter-spring-boot-starter ${greeter-starter.version} - + + 0.0.1-SNAPSHOT + \ No newline at end of file diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/sample/GreeterSampleApplication.java b/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/sample/GreeterSampleApplication.java index 3c87524648..5aa3ac7015 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/sample/GreeterSampleApplication.java +++ b/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/sample/GreeterSampleApplication.java @@ -5,7 +5,7 @@ import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import com.baeldung.greeter.Greeter; +import com.baeldung.greeter.library.Greeter; @SpringBootApplication public class GreeterSampleApplication implements CommandLineRunner { diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/resources/logback.xml b/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/sample/GreeterSampleApplicationIntegrationTest.java b/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/sample/GreeterSampleApplicationIntegrationTest.java index a4816cf319..50193ccd60 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/sample/GreeterSampleApplicationIntegrationTest.java +++ b/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/sample/GreeterSampleApplicationIntegrationTest.java @@ -10,7 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.baeldung.greeter.Greeter; +import com.baeldung.greeter.library.Greeter; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = GreeterSampleApplication.class) diff --git a/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml b/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml index e771cbaa8d..e71882db29 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml +++ b/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml @@ -5,17 +5,13 @@ com.baeldung greeter-spring-boot-starter 0.0.1-SNAPSHOT + - parent-boot-5 + spring-boot-custom-starter com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../spring-boot-custom-starter - - UTF-8 - 0.0.1-SNAPSHOT - 1.5.2.RELEASE - @@ -33,7 +29,7 @@ com.baeldung - greeter + greeter-library ${greeter.version} @@ -44,13 +40,19 @@ org.apache.maven.plugins maven-compiler-plugin - 3.7.0 + ${maven-compiler-plugin.version} - 1.8 - 1.8 + ${java.version} + ${java.version} + + UTF-8 + 0.0.1-SNAPSHOT + 1.5.2.RELEASE + +
    \ No newline at end of file diff --git a/spring-boot-custom-starter/greeter/pom.xml b/spring-boot-custom-starter/greeter/pom.xml index 6143992088..3cfd6da09e 100644 --- a/spring-boot-custom-starter/greeter/pom.xml +++ b/spring-boot-custom-starter/greeter/pom.xml @@ -1,14 +1,14 @@ + 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 greeter 0.0.1-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 \ No newline at end of file diff --git a/spring-boot-custom-starter/pom.xml b/spring-boot-custom-starter/pom.xml index 1bc0e14d8e..b8ad8fa12c 100644 --- a/spring-boot-custom-starter/pom.xml +++ b/spring-boot-custom-starter/pom.xml @@ -1,5 +1,5 @@ + 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-boot-custom-starter @@ -13,14 +13,10 @@ - greeter + greeter-library greeter-spring-boot-autoconfigure greeter-spring-boot-starter greeter-spring-boot-sample-app - - UTF-8 - - \ No newline at end of file diff --git a/spring-boot-gradle/.gitignore b/spring-boot-gradle/.gitignore new file mode 100644 index 0000000000..192221b47d --- /dev/null +++ b/spring-boot-gradle/.gitignore @@ -0,0 +1,2 @@ +.gradle/ +build/ \ No newline at end of file diff --git a/spring-boot-gradle/README.md b/spring-boot-gradle/README.md index f96aa9ccf8..76b82dce02 100644 --- a/spring-boot-gradle/README.md +++ b/spring-boot-gradle/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Spring Boot: Configuring a Main Class](http://www.baeldung.com/spring-boot-main-class) +- [Thin JARs with Spring Boot](http://www.baeldung.com/spring-boot-thin-jar) diff --git a/spring-boot-gradle/build.gradle b/spring-boot-gradle/build.gradle index e602c485a9..96055536c3 100644 --- a/spring-boot-gradle/build.gradle +++ b/spring-boot-gradle/build.gradle @@ -1,12 +1,16 @@ buildscript { ext { - springBootVersion = '2.0.0.RELEASE' + springBootPlugin = 'org.springframework.boot:spring-boot-gradle-plugin' + springBootVersion = '2.0.2.RELEASE' + thinPlugin = 'org.springframework.boot.experimental:spring-boot-thin-gradle-plugin' + thinVersion = '1.0.11.RELEASE' } repositories { mavenCentral() } dependencies { - classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") + classpath("${springBootPlugin}:${springBootVersion}") + classpath("${thinPlugin}:${thinVersion}") } } @@ -14,6 +18,8 @@ apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' +//add tasks thinJar and thinResolve for thin JAR deployments +apply plugin: 'org.springframework.boot.experimental.thin-launcher' group = 'org.baeldung' version = '0.0.1-SNAPSHOT' @@ -23,7 +29,6 @@ repositories { mavenCentral() } - dependencies { compile('org.springframework.boot:spring-boot-starter') testCompile('org.springframework.boot:spring-boot-starter-test') @@ -42,3 +47,21 @@ bootJar { // attributes 'Start-Class': 'org.baeldung.DemoApplication' // } } + +//Enable this to generate and use a pom.xml file +apply plugin: 'maven' + +//If you want to customize the generated pom.xml you can edit this task and add it as a dependency to the bootJar task +task createPom { + def basePath = 'build/resources/main/META-INF/maven' + doLast { + pom { + withXml(dependencyManagement.pomConfigurer) + }.writeTo("${basePath}/${project.group}/${project.name}/pom.xml") + } +} +//Uncomment the following to use your custom generated pom.xml +bootJar.dependsOn = [createPom] + +//Enable this to generate and use a thin.properties file +//bootJar.dependsOn = [thinProperties] \ No newline at end of file diff --git a/spring-boot-gradle/gradle/wrapper/gradle-wrapper.properties b/spring-boot-gradle/gradle/wrapper/gradle-wrapper.properties index 44d9d03d80..a8868a918a 100644 --- a/spring-boot-gradle/gradle/wrapper/gradle-wrapper.properties +++ b/spring-boot-gradle/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Tue Feb 06 12:27:20 CET 2018 +#Fri Jun 01 20:39:48 CEST 2018 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.5.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-4.5.1-all.zip diff --git a/spring-boot-gradle/src/main/resources/logback.xml b/spring-boot-gradle/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-gradle/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot-h2/spring-boot-h2-database/.gitignore b/spring-boot-h2/spring-boot-h2-database/.gitignore new file mode 100644 index 0000000000..82eca336e3 --- /dev/null +++ b/spring-boot-h2/spring-boot-h2-database/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/spring-boot-h2/spring-boot-h2-database/pom.xml b/spring-boot-h2/spring-boot-h2-database/pom.xml new file mode 100644 index 0000000000..4b660334da --- /dev/null +++ b/spring-boot-h2/spring-boot-h2-database/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + com.baeldung.h2db + spring-boot-h2-database + 0.0.1-SNAPSHOT + jar + + Demo Spring Boot applications that starts H2 in memory database + + + org.springframework.boot + spring-boot-starter-parent + 2.0.4.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/SpringBootApp.java b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/SpringBootApp.java new file mode 100644 index 0000000000..1fe080ec22 --- /dev/null +++ b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/SpringBootApp.java @@ -0,0 +1,60 @@ +package com.baeldung.h2db.demo; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Arrays; +import javax.annotation.PostConstruct; +import org.h2.tools.Server; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; + +@SpringBootApplication +public class SpringBootApp { + + @Autowired + private JdbcTemplate jdbcTemplate; + + public static void main(String[] args) { + SpringApplication.run(SpringBootApp.class, args); + } + + @PostConstruct + private void initDb() { + System.out.println(String.format( + "****** Creating table: %s, and Inserting test data ******", "Employees")); + + String sqlStatements[] = { + "drop table employees if exists", + "create table employees(id serial,first_name varchar(255),last_name varchar(255))", + "insert into employees(first_name, last_name) values('Eugen','Paraschiv')", + "insert into employees(first_name, last_name) values('Scott','Tiger')" + }; + + Arrays.asList(sqlStatements).stream().forEach(sql -> { + System.out.println(sql); + jdbcTemplate.execute(sql); + }); + + System.out.println(String.format("****** Fetching from table: %s ******", "Employees")); + jdbcTemplate.query("select id,first_name,last_name from employees", + new RowMapper() { + @Override + public Object mapRow(ResultSet rs, int i) throws SQLException { + System.out.println(String.format("id:%s,first_name:%s,last_name:%s", + rs.getString("id"), + rs.getString("first_name"), + rs.getString("last_name"))); + return null; + } + }); + } + + @Bean(initMethod = "start", destroyMethod = "stop") + public Server inMemoryH2DatabaseServer() throws SQLException { + return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9091"); + } +} \ No newline at end of file diff --git a/spring-boot-h2/spring-boot-h2-database/src/main/resources/application.properties b/spring-boot-h2/spring-boot-h2-database/src/main/resources/application.properties new file mode 100644 index 0000000000..0591cc9e0f --- /dev/null +++ b/spring-boot-h2/spring-boot-h2-database/src/main/resources/application.properties @@ -0,0 +1,7 @@ +spring.datasource.url=jdbc:h2:mem:mydb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= +spring.jpa.hibernate.ddl-auto=create +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console \ No newline at end of file diff --git a/spring-boot-h2/spring-boot-h2-remote-app/.gitignore b/spring-boot-h2/spring-boot-h2-remote-app/.gitignore new file mode 100644 index 0000000000..82eca336e3 --- /dev/null +++ b/spring-boot-h2/spring-boot-h2-remote-app/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/spring-boot-h2/spring-boot-h2-remote-app/pom.xml b/spring-boot-h2/spring-boot-h2-remote-app/pom.xml new file mode 100644 index 0000000000..8eb59d2098 --- /dev/null +++ b/spring-boot-h2/spring-boot-h2-remote-app/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + + com.baeldung.h2db + spring-boot-h2-remote-app + 0.0.1-SNAPSHOT + jar + + Demo Spring Boot applications that access H2 in memory database created + in another Spring Boot application + + + + org.springframework.boot + spring-boot-starter-parent + 2.0.4.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spring-boot-h2/spring-boot-h2-remote-app/src/main/java/com/baeldung/h2db/demo/ClientSpringBootApp.java b/spring-boot-h2/spring-boot-h2-remote-app/src/main/java/com/baeldung/h2db/demo/ClientSpringBootApp.java new file mode 100644 index 0000000000..39e52afd2c --- /dev/null +++ b/spring-boot-h2/spring-boot-h2-remote-app/src/main/java/com/baeldung/h2db/demo/ClientSpringBootApp.java @@ -0,0 +1,49 @@ +package com.baeldung.h2db.demo; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Arrays; +import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; + +@SpringBootApplication +public class ClientSpringBootApp { + + @Autowired + private JdbcTemplate jdbcTemplate; + + public static void main(String[] args) { + SpringApplication.run(ClientSpringBootApp.class, args); + } + + @PostConstruct + private void initDb() { + System.out.println("****** Inserting more sample data in the table: Employees ******"); + String sqlStatements[] = { + "insert into employees(first_name, last_name) values('Donald','Trump')", + "insert into employees(first_name, last_name) values('Barack','Obama')" + }; + + Arrays.asList(sqlStatements).stream().forEach(sql -> { + System.out.println(sql); + jdbcTemplate.execute(sql); + }); + + System.out.println(String.format("****** Fetching from table: %s ******", "Employees")); + jdbcTemplate.query("select id,first_name,last_name from employees", + new RowMapper() { + @Override + public Object mapRow(ResultSet rs, int i) throws SQLException { + System.out.println(String.format("id:%s,first_name:%s,last_name:%s", + rs.getString("id"), + rs.getString("first_name"), + rs.getString("last_name"))); + return null; + } + }); + } +} \ No newline at end of file diff --git a/spring-boot-h2/spring-boot-h2-remote-app/src/main/resources/application.properties b/spring-boot-h2/spring-boot-h2-remote-app/src/main/resources/application.properties new file mode 100644 index 0000000000..6c3446f03a --- /dev/null +++ b/spring-boot-h2/spring-boot-h2-remote-app/src/main/resources/application.properties @@ -0,0 +1,5 @@ +spring.datasource.url=jdbc:h2:tcp://localhost:9091/mem:mydb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= +spring.jpa.hibernate.ddl-auto=create \ No newline at end of file diff --git a/spring-boot-jasypt/README.md b/spring-boot-jasypt/README.md new file mode 100644 index 0000000000..5df2a4a6e5 --- /dev/null +++ b/spring-boot-jasypt/README.md @@ -0,0 +1,4 @@ + +### Relevant Articles: + +- [Spring Boot Configuration with Jasypt](http://www.baeldung.com/spring-boot-jasypt) diff --git a/spring-boot-jasypt/pom.xml b/spring-boot-jasypt/pom.xml index e094f0b061..212f524da6 100644 --- a/spring-boot-jasypt/pom.xml +++ b/spring-boot-jasypt/pom.xml @@ -4,26 +4,19 @@ 4.0.0 com.example.jasypt - JasyptDemo + spring-boot-jasypt 0.0.1-SNAPSHOT jar - - JasyptDemo + spring-boot-jasypt Demo project for Spring Boot - org.springframework.boot - spring-boot-starter-parent - 2.0.1.RELEASE - + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 - - UTF-8 - UTF-8 - 1.8 - - org.springframework.boot @@ -35,17 +28,17 @@ spring-boot-starter-test test - + com.github.ulisesbocchio jasypt-spring-boot-starter - 2.0.0 + ${jasypt.version} com.github.ulisesbocchio jasypt-spring-boot - 2.0.0 + ${jasypt.version} @@ -57,4 +50,12 @@ + + + UTF-8 + UTF-8 + 1.8 + 2.0.0 + + diff --git a/spring-boot-jasypt/src/main/resources/logback.xml b/spring-boot-jasypt/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-jasypt/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot-keycloak/pom.xml b/spring-boot-keycloak/pom.xml index d2df261b2f..3a39d4aa94 100644 --- a/spring-boot-keycloak/pom.xml +++ b/spring-boot-keycloak/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.keycloak spring-boot-keycloak @@ -11,9 +11,9 @@ com.baeldung - parent-boot-5 + parent-boot-1 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -75,8 +75,6 @@ - UTF-8 - UTF-8 3.3.0.Final diff --git a/spring-boot-keycloak/src/main/resources/logback.xml b/spring-boot-keycloak/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-keycloak/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot-logging-log4j2/.gitignore b/spring-boot-logging-log4j2/.gitignore new file mode 100644 index 0000000000..d129c74ec9 --- /dev/null +++ b/spring-boot-logging-log4j2/.gitignore @@ -0,0 +1,29 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +/logs/ +/bin/ +/mvnw +/mvnw.cmd diff --git a/spring-boot-logging-log4j2/README.md b/spring-boot-logging-log4j2/README.md new file mode 100644 index 0000000000..305957ed8d --- /dev/null +++ b/spring-boot-logging-log4j2/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Logging in Spring Boot](http://www.baeldung.com/spring-boot-logging) +- [How to Disable Console Logging in Spring Boot](https://www.baeldung.com/spring-boot-disable-console-logging) diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/pom.xml b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/pom.xml new file mode 100644 index 0000000000..c4f9b12676 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/pom.xml @@ -0,0 +1,53 @@ + + 4.0.0 + com.baeldung + 0.0.1-SNAPSHOT + disabling-console-jul + + + org.springframework.boot + spring-boot-starter-parent + 2.0.4.RELEASE + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.slf4j + jul-to-slf4j + + + org.slf4j + slf4j-simple + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + UTF-8 + 1.8 + + \ No newline at end of file diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/DisablingConsoleJulApp.java b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/DisablingConsoleJulApp.java new file mode 100644 index 0000000000..c9187e9ace --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/DisablingConsoleJulApp.java @@ -0,0 +1,11 @@ +package com.baeldung.springbootlogging.disablingconsole.jul.properties; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DisablingConsoleJulApp { + public static void main(String[] args) { + SpringApplication.run(DisablingConsoleJulApp.class, args); + } +} diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/controllers/DisabledConsoleRestController.java b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/controllers/DisabledConsoleRestController.java new file mode 100644 index 0000000000..e33089ed36 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/controllers/DisabledConsoleRestController.java @@ -0,0 +1,19 @@ +package com.baeldung.springbootlogging.disablingconsole.jul.properties.controllers; + +import java.time.LocalTime; +import java.util.logging.Logger; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class DisabledConsoleRestController { + + private static final Logger LOG = Logger.getLogger(DisabledConsoleRestController.class.getName()); + + @GetMapping("/disabled-console-jul-properties") + public String logTime() { + LOG.info("Current time: " + LocalTime.now()); + return "finished!"; + } +} diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/resources/application.properties b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/resources/application.properties new file mode 100644 index 0000000000..d81eed95d3 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/resources/application.properties @@ -0,0 +1 @@ +logging.file=true \ No newline at end of file diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/resources/logging.properties b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/resources/logging.properties new file mode 100644 index 0000000000..0136354868 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/resources/logging.properties @@ -0,0 +1,4 @@ +handlers= java.util.logging.FileHandler + +java.util.logging.FileHandler.pattern=baeldung.log +java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter \ No newline at end of file diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/pom.xml b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/pom.xml new file mode 100644 index 0000000000..97d10c574a --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/pom.xml @@ -0,0 +1,49 @@ + + 4.0.0 + com.baeldung + 0.0.1-SNAPSHOT + disabling-console-log4j2 + + org.springframework.boot + spring-boot-starter-parent + 2.0.4.RELEASE + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-log4j2 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + UTF-8 + 1.8 + + + \ No newline at end of file diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/DisablingConsoleLog4j2App.java b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/DisablingConsoleLog4j2App.java new file mode 100644 index 0000000000..ae59f3b3e1 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/DisablingConsoleLog4j2App.java @@ -0,0 +1,11 @@ +package com.baeldung.springbootlogging.disablingconsole.log4j2.xml; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DisablingConsoleLog4j2App { + public static void main(String[] args) { + SpringApplication.run(DisablingConsoleLog4j2App.class, args); + } +} diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/controllers/DisabledConsoleRestController.java b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/controllers/DisabledConsoleRestController.java new file mode 100644 index 0000000000..f6485b63d4 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/controllers/DisabledConsoleRestController.java @@ -0,0 +1,20 @@ +package com.baeldung.springbootlogging.disablingconsole.log4j2.xml.controllers; + +import java.time.LocalTime; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class DisabledConsoleRestController { + + private static final Logger LOG = LoggerFactory.getLogger(DisabledConsoleRestController.class); + + @GetMapping("/disabled-console-log4j2-xml") + public String logTime() { + LOG.info("Current time: {}", LocalTime.now()); + return "finished!"; + } +} diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/resources/log4j2.xml b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..20975f40d9 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/resources/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/pom.xml b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/pom.xml new file mode 100644 index 0000000000..6f2170390b --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/pom.xml @@ -0,0 +1,9 @@ + + 4.0.0 + + com.baeldung + disabling-console-logging + 0.0.1-SNAPSHOT + + disabling-console-logback + \ No newline at end of file diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/DisablingConsoleLogbackApp.java b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/DisablingConsoleLogbackApp.java new file mode 100644 index 0000000000..9b38d42477 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/DisablingConsoleLogbackApp.java @@ -0,0 +1,11 @@ +package com.baeldung.springbootlogging.disablingconsole.logback.xml; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DisablingConsoleLogbackApp { + public static void main(String[] args) { + SpringApplication.run(DisablingConsoleLogbackApp.class, args); + } +} diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/controllers/DisabledConsoleRestController.java b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/controllers/DisabledConsoleRestController.java new file mode 100644 index 0000000000..e1d6b1d45e --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/controllers/DisabledConsoleRestController.java @@ -0,0 +1,20 @@ +package com.baeldung.springbootlogging.disablingconsole.logback.xml.controllers; + +import java.time.LocalTime; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class DisabledConsoleRestController { + + private static final Logger LOG = LoggerFactory.getLogger(DisabledConsoleRestController.class); + + @GetMapping("/disabled-console-logback-xml") + public String logTime() { + LOG.info("Current time: {}", LocalTime.now()); + return "finished!"; + } +} diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/resources/application.properties b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/resources/application.properties new file mode 100644 index 0000000000..70c2f97194 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/resources/application.properties @@ -0,0 +1,7 @@ +logging.file=disabled-console.log + +### we could potentially 'disable' console logging by setting a blank log pattern: +#logging.pattern.console= + +### or disable the logs completely by setting the root logging level as 'OFF': +#logging.level.root=OFF diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/resources/logback-spring.xml b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/resources/logback-spring.xml new file mode 100644 index 0000000000..5c751e994f --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/resources/logback-spring.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/spring-boot-logging-log4j2/disabling-console-logging/pom.xml b/spring-boot-logging-log4j2/disabling-console-logging/pom.xml new file mode 100644 index 0000000000..bc248e49b2 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/pom.xml @@ -0,0 +1,21 @@ + + 4.0.0 + 0.0.1-SNAPSHOT + com.baeldung + disabling-console-logging + pom + Projects for Disabling Spring Boot Console Logging tutorials + + + com.baeldung + spring-boot-logging-log4j2 + 0.0.1-SNAPSHOT + + + + disabling-console-logback + disabling-console-log4j2 + disabling-console-jul + + \ No newline at end of file diff --git a/spring-boot-logging-log4j2/pom.xml b/spring-boot-logging-log4j2/pom.xml new file mode 100644 index 0000000000..ee4d07c3e8 --- /dev/null +++ b/spring-boot-logging-log4j2/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + com.baeldung + spring-boot-logging-log4j2 + 0.0.1-SNAPSHOT + pom + Projects for Spring Boot Logging tutorials + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + spring-boot-logging-log4j2-app + disabling-console-logging + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + UTF-8 + 1.8 + + + diff --git a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/pom.xml b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/pom.xml new file mode 100644 index 0000000000..1d4c8867fb --- /dev/null +++ b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + + com.baeldung + spring-boot-logging-log4j2-app + 0.0.1-SNAPSHOT + jar + Demo project for Spring Boot Logging with Log4J2 + + + spring-boot-logging-log4j2 + com.baeldung + 0.0.1-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-log4j2 + + + diff --git a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/java/com/baeldung/springbootlogging/LoggingController.java b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/java/com/baeldung/springbootlogging/LoggingController.java new file mode 100644 index 0000000000..07763c8c3b --- /dev/null +++ b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/java/com/baeldung/springbootlogging/LoggingController.java @@ -0,0 +1,37 @@ +package com.baeldung.springbootlogging; + +import org.apache.logging.log4j.LogManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class LoggingController { + + private final static Logger logger = LoggerFactory.getLogger(LoggingController.class); + + @GetMapping("/") + public String index() { + logger.trace("A TRACE Message"); + logger.debug("A DEBUG Message"); + logger.info("An INFO Message"); + logger.warn("A WARN Message"); + logger.error("An ERROR Message"); + + return "Howdy! Check out the Logs to see the output..."; + } + + private static final org.apache.logging.log4j.Logger loggerNative = LogManager.getLogger(LoggingController.class); + + @GetMapping("/native") + public String nativeLogging() { + loggerNative.trace("This TRACE message has been printed by Log4j2 without passing through SLF4J"); + loggerNative.debug("This DEBUG message has been printed by Log4j2 without passing through SLF4J"); + loggerNative.info("This INFO message has been printed by Log4j2 without passing through SLF4J"); + loggerNative.warn("This WARN message been printed by Log4j2 without passing through SLF4J"); + loggerNative.error("This ERROR message been printed by Log4j2 without passing through SLF4J"); + loggerNative.fatal("This FATAL message been printed by Log4j2 without passing through SLF4J"); + return "Howdy! Check out the Logs to see the output printed directly throguh Log4j2..."; + } +} diff --git a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/java/com/baeldung/springbootlogging/SpringBootLoggingApplication.java b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/java/com/baeldung/springbootlogging/SpringBootLoggingApplication.java new file mode 100644 index 0000000000..336997a81e --- /dev/null +++ b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/java/com/baeldung/springbootlogging/SpringBootLoggingApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.springbootlogging; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootLoggingApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootLoggingApplication.class, args); + } +} diff --git a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/resources/application.properties b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/resources/log4j2-spring.xml b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/resources/log4j2-spring.xml new file mode 100644 index 0000000000..b08cd2d22d --- /dev/null +++ b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/resources/log4j2-spring.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + %d %p %C{1.} [%t] %m%n + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-boot-mvc/.gitignore b/spring-boot-mvc/.gitignore new file mode 100644 index 0000000000..82eca336e3 --- /dev/null +++ b/spring-boot-mvc/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/spring-boot-mvc/README.md b/spring-boot-mvc/README.md new file mode 100644 index 0000000000..b46dbe3bae --- /dev/null +++ b/spring-boot-mvc/README.md @@ -0,0 +1,10 @@ +### Relevant Articles: + +- [Guide to the Favicon in Spring Boot](http://www.baeldung.com/spring-boot-favicon) +- [Custom Validation MessageSource in Spring Boot](https://www.baeldung.com/spring-custom-validation-message-source) +- [Spring Boot Annotations](http://www.baeldung.com/spring-boot-annotations) +- [Spring Scheduling Annotations](http://www.baeldung.com/spring-scheduling-annotations) +- [Spring Web Annotations](http://www.baeldung.com/spring-mvc-annotations) +- [Spring Core Annotations](http://www.baeldung.com/spring-core-annotations) +- [Display RSS Feed with Spring MVC](http://www.baeldung.com/spring-mvc-rss-feed) + diff --git a/spring-boot-mvc/pom.xml b/spring-boot-mvc/pom.xml new file mode 100644 index 0000000000..e456155f36 --- /dev/null +++ b/spring-boot-mvc/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + com.baeldung + spring-boot-mvc + 0.0.1-SNAPSHOT + jar + spring-boot-mvc + Demo project for Spring Boot + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.boot + spring-boot-starter-validation + + + + + com.rometools + rome + ${rome.version} + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + UTF-8 + 1.8 + + 1.10.0 + + + diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/Bike.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/Bike.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/Bike.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/Bike.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/Biker.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/Biker.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/Biker.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/Biker.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/Car.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/Car.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/Car.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/Car.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/CarMechanic.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/CarMechanic.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/CarMechanic.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/CarMechanic.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/CarUtility.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/CarUtility.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/CarUtility.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/CarUtility.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomException.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomException.java new file mode 100644 index 0000000000..4502a45301 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomException.java @@ -0,0 +1,8 @@ +package com.baeldung.annotations; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.BAD_REQUEST) +public class CustomException extends RuntimeException { +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomResponseController.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomResponseController.java new file mode 100644 index 0000000000..a29a6252f2 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomResponseController.java @@ -0,0 +1,62 @@ +package com.baeldung.annotations; + +import java.io.IOException; +import java.time.Year; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +@Controller +@RequestMapping("/customResponse") +public class CustomResponseController { + + @GetMapping("/hello") + public ResponseEntity hello() { + return new ResponseEntity<>("Hello World!", HttpStatus.OK); + } + + @GetMapping("/age") + public ResponseEntity age(@RequestParam("yearOfBirth") int yearOfBirth) { + if (isInFuture(yearOfBirth)) { + return new ResponseEntity<>("Year of birth cannot be in the future", HttpStatus.BAD_REQUEST); + } + + return new ResponseEntity<>("Your age is " + calculateAge(yearOfBirth), HttpStatus.OK); + } + + private int calculateAge(int yearOfBirth) { + return currentYear() - yearOfBirth; + } + + private boolean isInFuture(int year) { + return currentYear() < year; + } + + private int currentYear() { + return Year.now().getValue(); + } + + @GetMapping("/customHeader") + public ResponseEntity customHeader() { + HttpHeaders headers = new HttpHeaders(); + headers.add("Custom-Header", "foo"); + + return new ResponseEntity<>("Custom header set", headers, HttpStatus.OK); + } + + @GetMapping("/manual") + public void manual(HttpServletResponse response) throws IOException { + response.setHeader("Custom-Header", "foo"); + response.setStatus(200); + response.getWriter() + .println("Hello World!"); + } + +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomResponseWithBuilderController.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomResponseWithBuilderController.java new file mode 100644 index 0000000000..9a77029128 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomResponseWithBuilderController.java @@ -0,0 +1,52 @@ +package com.baeldung.annotations; + +import java.time.Year; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +@Controller +@RequestMapping("/customResponseWithBuilder") +public class CustomResponseWithBuilderController { + + @GetMapping("/hello") + public ResponseEntity hello() { + return ResponseEntity.ok("Hello World!"); + } + + @GetMapping("/age") + public ResponseEntity age(@RequestParam("yearOfBirth") int yearOfBirth) { + if (isInFuture(yearOfBirth)) { + return ResponseEntity.badRequest() + .body("Year of birth cannot be in the future"); + } + + return ResponseEntity.status(HttpStatus.OK) + .body("Your age is " + calculateAge(yearOfBirth)); + } + + private int calculateAge(int yearOfBirth) { + return currentYear() - yearOfBirth; + } + + private boolean isInFuture(int year) { + return currentYear() < year; + } + + private int currentYear() { + return Year.now() + .getValue(); + } + + @GetMapping("/customHeader") + public ResponseEntity customHeader() { + return ResponseEntity.ok() + .header("Custom-Header", "foo") + .body("Custom header set"); + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/Driver.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/Driver.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/Driver.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/Driver.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/Engine.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/Engine.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/Engine.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/Engine.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/Vehicle.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/Vehicle.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/Vehicle.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/Vehicle.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleController.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleController.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleFactoryConfig.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryConfig.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleFactoryConfig.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryConfig.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleRepository.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleRepository.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleRepository.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleRepository.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleRestController.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleRestController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleRestController.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleRestController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleService.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleService.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleService.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleService.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedApplication.java b/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedApplication.java new file mode 100644 index 0000000000..0f9de840d5 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedApplication.java @@ -0,0 +1,23 @@ +package com.baeldung.rss; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * Spring Boot launcher for an application which exposes an RSS Feed. + * + * @author Donato Rimenti + * + */ +@SpringBootApplication +public class RssFeedApplication { + + /** + * Launches a Spring Boot application which exposes an RSS Feed. + * + * @param args null + */ + public static void main(final String[] args) { + SpringApplication.run(RssFeedApplication.class, args); + } +} \ No newline at end of file diff --git a/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedController.java b/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedController.java new file mode 100644 index 0000000000..9d4e36dd5f --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedController.java @@ -0,0 +1,32 @@ +package com.baeldung.rss; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.View; + +/** + * REST Controller which returns an RSS Feed created by {@link RssFeedView}. + * + * @author Donato Rimenti + * + */ +@RestController +public class RssFeedController { + + /** + * View used by this controller. + */ + @Autowired + private RssFeedView view; + + /** + * Returns an RSS Feed created by {@link #view}. + * + * @return an RSS Feed + */ + @GetMapping("/rss") + public View getFeed() { + return view; + } +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedView.java b/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedView.java new file mode 100644 index 0000000000..c9b9c51bec --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedView.java @@ -0,0 +1,98 @@ +package com.baeldung.rss; + +import java.sql.Date; +import java.time.Instant; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.view.feed.AbstractRssFeedView; + +import com.rometools.rome.feed.rss.Channel; +import com.rometools.rome.feed.rss.Item; + +/** + * View for a RSS feed. + * + * @author Donato Rimenti + */ +@Component +public class RssFeedView extends AbstractRssFeedView { + + /* + * (non-Javadoc) + * + * @see org.springframework.web.servlet.view.feed.AbstractFeedView# + * buildFeedMetadata(java.util.Map, com.rometools.rome.feed.WireFeed, + * javax.servlet.http.HttpServletRequest) + */ + @Override + protected void buildFeedMetadata(Map model, Channel feed, HttpServletRequest request) { + feed.setTitle("Baeldung RSS Feed"); + feed.setDescription("Learn how to program in Java"); + feed.setLink("http://www.baeldung.com"); + } + + /* + * (non-Javadoc) + * + * @see org.springframework.web.servlet.view.feed.AbstractRssFeedView# + * buildFeedItems(java.util.Map, javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse) + */ + @Override + protected List buildFeedItems(Map model, HttpServletRequest request, + HttpServletResponse response) { + + // Builds the single entries. + Item entryOne = new Item(); + entryOne.setTitle("JUnit 5 @Test Annotation"); + entryOne.setAuthor("donatohan.rimenti@gmail.com"); + entryOne.setLink("http://www.baeldung.com/junit-5-test-annotation"); + entryOne.setPubDate(Date.from(Instant.parse("2017-12-19T00:00:00Z"))); + + Item entryTwo = new Item(); + entryTwo.setTitle("Creating and Configuring Jetty 9 Server in Java"); + entryTwo.setAuthor("donatohan.rimenti@gmail.com"); + entryTwo.setLink("http://www.baeldung.com/jetty-java-programmatic"); + entryTwo.setPubDate(Date.from(Instant.parse("2018-01-23T00:00:00Z"))); + + Item entryThree = new Item(); + entryThree.setTitle("Flyweight Pattern in Java"); + entryThree.setAuthor("donatohan.rimenti@gmail.com"); + entryThree.setLink("http://www.baeldung.com/java-flyweight"); + entryThree.setPubDate(Date.from(Instant.parse("2018-02-01T00:00:00Z"))); + + Item entryFour = new Item(); + entryFour.setTitle("Multi-Swarm Optimization Algorithm in Java"); + entryFour.setAuthor("donatohan.rimenti@gmail.com"); + entryFour.setLink("http://www.baeldung.com/java-multi-swarm-algorithm"); + entryFour.setPubDate(Date.from(Instant.parse("2018-03-09T00:00:00Z"))); + + Item entryFive = new Item(); + entryFive.setTitle("A Simple Tagging Implementation with MongoDB"); + entryFive.setAuthor("donatohan.rimenti@gmail.com"); + entryFive.setLink("http://www.baeldung.com/mongodb-tagging"); + entryFive.setPubDate(Date.from(Instant.parse("2018-03-27T00:00:00Z"))); + + Item entrySix = new Item(); + entrySix.setTitle("Double-Checked Locking with Singleton"); + entrySix.setAuthor("donatohan.rimenti@gmail.com"); + entrySix.setLink("http://www.baeldung.com/java-singleton-double-checked-locking"); + entrySix.setPubDate(Date.from(Instant.parse("2018-04-23T00:00:00Z"))); + + Item entrySeven = new Item(); + entrySeven.setTitle("Introduction to Dagger 2"); + entrySeven.setAuthor("donatohan.rimenti@gmail.com"); + entrySeven.setLink("http://www.baeldung.com/dagger-2"); + entrySeven.setPubDate(Date.from(Instant.parse("2018-06-30T00:00:00Z"))); + + // Creates the feed. + return Arrays.asList(entryOne, entryTwo, entryThree, entryFour, entryFive, entrySix, entrySeven); + } + +} \ No newline at end of file diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/LoggingController.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/LoggingController.java new file mode 100644 index 0000000000..819ee589fe --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/LoggingController.java @@ -0,0 +1,23 @@ +package com.baeldung.springbootmvc; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class LoggingController { + + Logger logger = LoggerFactory.getLogger(LoggingController.class); + + @GetMapping("/") + public String index() { + logger.trace("A TRACE Message"); + logger.debug("A DEBUG Message"); + logger.info("An INFO Message"); + logger.warn("A WARN Message"); + logger.error("An ERROR Message"); + + return "Howdy! Check out the Logs to see the output..."; + } +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/LoginController.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/LoginController.java new file mode 100644 index 0000000000..589024c0bc --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/LoginController.java @@ -0,0 +1,20 @@ +package com.baeldung.springbootmvc; + +import javax.validation.Valid; + +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.springbootmvc.model.LoginForm; + +@RestController +@RequestMapping("/") +public class LoginController { + + @PostMapping("loginform") + public String processLogin(@Valid LoginForm form) { + return "Success"; + + } +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java new file mode 100644 index 0000000000..df8f72f500 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.springbootmvc; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootMvcApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootMvcApplication.class, args); + } +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/CustomMessageSourceConfiguration.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/CustomMessageSourceConfiguration.java new file mode 100644 index 0000000000..e83f15a366 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/CustomMessageSourceConfiguration.java @@ -0,0 +1,27 @@ +package com.baeldung.springbootmvc.config; + +import org.springframework.context.MessageSource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.ReloadableResourceBundleMessageSource; +import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; + +@Configuration +public class CustomMessageSourceConfiguration { + + @Bean + public MessageSource messageSource() { + ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); + messageSource.setBasename("classpath:messages"); + messageSource.setDefaultEncoding("UTF-8"); + return messageSource; + } + + @Bean + public LocalValidatorFactoryBean getValidator() { + LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean(); + bean.setValidationMessageSource(messageSource()); + return bean; + } + +} diff --git a/spring-rest/src/main/java/org/baeldung/config/FaviconConfiguration.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/FaviconConfiguration.java similarity index 85% rename from spring-rest/src/main/java/org/baeldung/config/FaviconConfiguration.java rename to spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/FaviconConfiguration.java index 78a2a3eb2c..9a1f47b5cb 100644 --- a/spring-rest/src/main/java/org/baeldung/config/FaviconConfiguration.java +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/FaviconConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.springbootmvc.config; import java.util.Arrays; import java.util.Collections; @@ -8,7 +8,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; -import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @@ -28,17 +27,18 @@ public class FaviconConfiguration { @Bean protected ResourceHttpRequestHandler faviconRequestHandler() { ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler(); - ClassPathResource classPathResource = new ClassPathResource("com/baeldung/produceimage/images"); + ClassPathResource classPathResource = new ClassPathResource("com/baeldung/images"); List locations = Arrays.asList(classPathResource); requestHandler.setLocations(locations); return requestHandler; } - - //@Controller + + // @Controller static class FaviconController { - - @RequestMapping(value="favicon.ico", method=RequestMethod.GET) + + @RequestMapping(value = "favicon.ico", method = RequestMethod.GET) @ResponseBody - void favicon() {} + void favicon() { + } } } diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/model/LoginForm.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/model/LoginForm.java new file mode 100644 index 0000000000..107cd1bbf1 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/model/LoginForm.java @@ -0,0 +1,32 @@ +package com.baeldung.springbootmvc.model; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; + +public class LoginForm { + + @NotEmpty(message = "{email.notempty}") + @Email + private String email; + + @NotNull + private String 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/spring-boot-mvc/src/main/resources/application.properties b/spring-boot-mvc/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-rest/src/main/resources/static/favicon.ico b/spring-boot-mvc/src/main/resources/com/baeldung/images/favicon.ico similarity index 100% rename from spring-rest/src/main/resources/static/favicon.ico rename to spring-boot-mvc/src/main/resources/com/baeldung/images/favicon.ico diff --git a/spring-boot-mvc/src/main/resources/favicon.ico b/spring-boot-mvc/src/main/resources/favicon.ico new file mode 100644 index 0000000000..64105ac11c Binary files /dev/null and b/spring-boot-mvc/src/main/resources/favicon.ico differ diff --git a/spring-boot-mvc/src/main/resources/logback.xml b/spring-boot-mvc/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-mvc/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot-mvc/src/main/resources/messages.properties b/spring-boot-mvc/src/main/resources/messages.properties new file mode 100644 index 0000000000..9794c89651 --- /dev/null +++ b/spring-boot-mvc/src/main/resources/messages.properties @@ -0,0 +1 @@ +email.notempty=Please provide valid email id. \ No newline at end of file diff --git a/spring-boot-mvc/src/main/resources/messages_fr.properties b/spring-boot-mvc/src/main/resources/messages_fr.properties new file mode 100644 index 0000000000..070f4e0bfc --- /dev/null +++ b/spring-boot-mvc/src/main/resources/messages_fr.properties @@ -0,0 +1 @@ +email.notempty=Veuillez fournir un identifiant de messagerie valide. \ No newline at end of file diff --git a/spring-boot-mvc/src/main/resources/static/favicon.ico b/spring-boot-mvc/src/main/resources/static/favicon.ico new file mode 100644 index 0000000000..64105ac11c Binary files /dev/null and b/spring-boot-mvc/src/main/resources/static/favicon.ico differ diff --git a/spring-boot-mvc/src/main/resources/static/index.html b/spring-boot-mvc/src/main/resources/static/index.html new file mode 100644 index 0000000000..9f55d12685 --- /dev/null +++ b/spring-boot-mvc/src/main/resources/static/index.html @@ -0,0 +1 @@ +Welcome to Baeldung \ No newline at end of file diff --git a/spring-boot-mvc/src/test/java/com/baeldung/rss/RssFeedUnitTest.java b/spring-boot-mvc/src/test/java/com/baeldung/rss/RssFeedUnitTest.java new file mode 100644 index 0000000000..f5524c36fe --- /dev/null +++ b/spring-boot-mvc/src/test/java/com/baeldung/rss/RssFeedUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.rss; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +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; + +/** + * Test for {@link RssFeedApplication}. + * + * @author Donato Rimenti + * + */ +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = RssFeedApplication.class) +public class RssFeedUnitTest { + + /** + * Application context. + */ + @Autowired + private WebApplicationContext context; + + /** + * Mock to perform tests on Spring Web Controller. + */ + private MockMvc mvc; + + /** + * Sets the test up. + */ + @Before + public void setup() { + mvc = MockMvcBuilders.webAppContextSetup(context).build(); + } + + /** + * Calls the RSS feed endpoint and checks that the result matches an + * expected one. + * + * @throws Exception + */ + @Test + public void givenRssFeed_whenComparedWithExisting_thenEquals() throws Exception { + // The expected response. + String expectedResult = " Baeldung RSS Feed http://www.baeldung.com Learn how to program in Java JUnit 5 @Test Annotation http://www.baeldung.com/junit-5-test-annotation Tue, 19 Dec 2017 00:00:00 GMT donatohan.rimenti@gmail.com Creating and Configuring Jetty 9 Server in Java http://www.baeldung.com/jetty-java-programmatic Tue, 23 Jan 2018 00:00:00 GMT donatohan.rimenti@gmail.com Flyweight Pattern in Java http://www.baeldung.com/java-flyweight Thu, 01 Feb 2018 00:00:00 GMT donatohan.rimenti@gmail.com Multi-Swarm Optimization Algorithm in Java http://www.baeldung.com/java-multi-swarm-algorithm Fri, 09 Mar 2018 00:00:00 GMT donatohan.rimenti@gmail.com A Simple Tagging Implementation with MongoDB http://www.baeldung.com/mongodb-tagging Tue, 27 Mar 2018 00:00:00 GMT donatohan.rimenti@gmail.com Double-Checked Locking with Singleton http://www.baeldung.com/java-singleton-double-checked-locking Mon, 23 Apr 2018 00:00:00 GMT donatohan.rimenti@gmail.com Introduction to Dagger 2 http://www.baeldung.com/dagger-2 Sat, 30 Jun 2018 00:00:00 GMT donatohan.rimenti@gmail.com "; + + // Performs a post against the RSS feed endpoint and checks that the + // result is equals to the expected one. + mvc.perform(MockMvcRequestBuilders.get("/rss")).andExpect(status().isOk()) + .andExpect(content().xml(expectedResult)); + } + +} diff --git a/spring-boot-mvc/src/test/java/com/baeldung/springbootmvc/LoginControllerUnitTest.java b/spring-boot-mvc/src/test/java/com/baeldung/springbootmvc/LoginControllerUnitTest.java new file mode 100644 index 0000000000..68229f459c --- /dev/null +++ b/spring-boot-mvc/src/test/java/com/baeldung/springbootmvc/LoginControllerUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.springbootmvc; + +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.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.RequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import com.baeldung.springbootmvc.config.CustomMessageSourceConfiguration; + +@RunWith(SpringRunner.class) +@WebMvcTest(value = LoginController.class, secure = false) +@ContextConfiguration(classes = { SpringBootMvcApplication.class, CustomMessageSourceConfiguration.class }) +public class LoginControllerUnitTest { + + @Autowired + private MockMvc mockMvc; + + @Test + public void givenLoginForm_whenEmailFieldNotProvided_testCustomValidMessageIsReturned() throws Exception { + + RequestBuilder builder = MockMvcRequestBuilders.post("/loginform").param("email", "").param("password", "helo"); + + // header("accept-language", "fr"). + MvcResult perform = mockMvc.perform(builder).andReturn(); + Assert.assertTrue(perform.getResolvedException().getMessage().contains("valid email")); + + } +} \ No newline at end of file diff --git a/spring-boot-ops/README.md b/spring-boot-ops/README.md new file mode 100644 index 0000000000..c125c96c36 --- /dev/null +++ b/spring-boot-ops/README.md @@ -0,0 +1,12 @@ +### Relevant Articles: + - [Deploy a Spring Boot WAR into a Tomcat Server](http://www.baeldung.com/spring-boot-war-tomcat-deploy) + - [Spring Boot Dependency Management with a Custom Parent](http://www.baeldung.com/spring-boot-dependency-management-custom-parent) + - [A Custom Data Binder in Spring MVC](http://www.baeldung.com/spring-mvc-custom-data-binder) + - [Create a Fat Jar App with Spring Boot](http://www.baeldung.com/deployable-fat-jar-spring-boot) + - [Introduction to WebJars](http://www.baeldung.com/maven-webjars) + - [Intro to Spring Boot Starters](http://www.baeldung.com/spring-boot-starters) + - [A Quick Guide to Maven Wrapper](http://www.baeldung.com/maven-wrapper) + - [Shutdown a Spring Boot Application](http://www.baeldung.com/spring-boot-shutdown) + - [Spring Boot Console Application](http://www.baeldung.com/spring-boot-console-app) + - [Comparing Embedded Servlet Containers in Spring Boot](http://www.baeldung.com/spring-boot-servlet-containers) + diff --git a/spring-boot-ops/docker/Dockerfile b/spring-boot-ops/docker/Dockerfile new file mode 100644 index 0000000000..85db5c7bed --- /dev/null +++ b/spring-boot-ops/docker/Dockerfile @@ -0,0 +1,16 @@ +# Alpine Linux with OpenJDK JRE +FROM openjdk:8-jre-alpine +RUN apk add --no-cache bash + +# copy fat WAR +COPY spring-boot-ops.war /app.war + +# copy fat WAR +COPY logback.xml /logback.xml + +COPY run.sh /run.sh + +# runs application +#CMD ["/usr/bin/java", "-jar", "-Dspring.profiles.active=default", "-Dlogging.config=/logback.xml", "/app.war"] + +ENTRYPOINT ["/run.sh"] diff --git a/spring-boot-ops/docker/logback.xml b/spring-boot-ops/docker/logback.xml new file mode 100644 index 0000000000..aad6d3fcb3 --- /dev/null +++ b/spring-boot-ops/docker/logback.xml @@ -0,0 +1,15 @@ + + + + + /var/log/WebjarsdemoApplication/application.log + true + + %-7d{yyyy-MM-dd HH:mm:ss:SSS} %m%n + + + + + + + diff --git a/spring-boot-ops/docker/run.sh b/spring-boot-ops/docker/run.sh new file mode 100755 index 0000000000..aeecc29371 --- /dev/null +++ b/spring-boot-ops/docker/run.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +java -Dspring.profiles.active=$1 -Dlogging.config=/logback.xml -jar /app.war + diff --git a/spring-boot-ops/pom.xml b/spring-boot-ops/pom.xml index 0d0ccc0ef2..57779c3f8e 100644 --- a/spring-boot-ops/pom.xml +++ b/spring-boot-ops/pom.xml @@ -1,57 +1,158 @@ - 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-boot-ops - 0.0.1-SNAPSHOT - war + spring-boot-ops + war + spring-boot-ops + Demo project for Spring Boot - spring-boot-ops - Demo project for Spring Boot + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + - - org.springframework.boot - spring-boot-starter-parent - 2.0.1.RELEASE - - + - - UTF-8 - UTF-8 - 1.8 - + + org.springframework.boot + spring-boot-starter-web + - - - org.springframework.boot - spring-boot-starter-web - + + org.springframework.boot + spring-boot-starter-thymeleaf + provided + - - org.springframework.boot - spring-boot-starter-tomcat - provided - + + org.springframework.boot + spring-boot-starter-test + test + - - org.springframework.boot - spring-boot-starter-test - test - - + + org.springframework.boot + spring-boot-starter-data-jpa + - - ${artifactId} - - - org.springframework.boot - spring-boot-maven-plugin - - - + + org.springframework.boot + spring-boot-starter-mail + + + org.springframework.boot + spring-boot-starter-actuator + + + + com.h2database + h2 + runtime + + + + javax.persistence + javax.persistence-api + ${jpa.version} + + + + com.google.guava + guava + ${guava.version} + + + + org.subethamail + subethasmtp + ${subethasmtp.version} + test + + + + org.webjars + bootstrap + ${bootstrap.version} + + + + org.webjars + jquery + ${jquery.version} + + + + + + ${project.artifactId} + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + com.baeldung.webjar.WebjarsdemoApplication + + + + + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + + + + + org.baeldung.boot.Application + 3.1.1 + 3.3.7-1 + 2.2 + 18.0 + 3.1.7 + diff --git a/spring-boot-ops/src/main/java/com/baeldung/compare/ComparisonApplication.java b/spring-boot-ops/src/main/java/com/baeldung/compare/ComparisonApplication.java new file mode 100644 index 0000000000..eb9d5ec4d0 --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/compare/ComparisonApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.compare; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ComparisonApplication { + + public static void main(String[] args) { + SpringApplication.run(ComparisonApplication.class, args); + } +} diff --git a/spring-boot-ops/src/main/java/com/baeldung/compare/StartupEventHandler.java b/spring-boot-ops/src/main/java/com/baeldung/compare/StartupEventHandler.java new file mode 100644 index 0000000000..e0756f704e --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/compare/StartupEventHandler.java @@ -0,0 +1,65 @@ +package com.baeldung.compare; + +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.function.BiFunction; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +import io.micrometer.core.instrument.Meter; +import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.instrument.Statistic; + +@Component +public class StartupEventHandler { + + // logger, constructor + private static Logger logger = LoggerFactory.getLogger(StartupEventHandler.class); + + public StartupEventHandler(MeterRegistry registry) { + this.meterRegistry = registry; + } + + private String[] METRICS = { + "jvm.memory.used", + "jvm.classes.loaded", + "jvm.threads.live"}; + + private String METRIC_MSG_FORMAT = "Startup Metric >> {}={}"; + + private MeterRegistry meterRegistry; + + @EventListener + public void getAndLogStartupMetrics( + ApplicationReadyEvent event) { + Arrays.asList(METRICS) + .forEach(this::getAndLogActuatorMetric); + } + + private void getAndLogActuatorMetric(String metric) { + Meter meter = meterRegistry.find(metric).meter(); + Map stats = getSamples(meter); + + logger.info(METRIC_MSG_FORMAT, metric, stats.get(Statistic.VALUE).longValue()); + } + + private Map getSamples(Meter meter) { + Map samples = new LinkedHashMap<>(); + mergeMeasurements(samples, meter); + return samples; + } + + private void mergeMeasurements(Map samples, Meter meter) { + meter.measure().forEach((measurement) -> samples.merge(measurement.getStatistic(), + measurement.getValue(), mergeFunction(measurement.getStatistic()))); + } + + private BiFunction mergeFunction(Statistic statistic) { + return Statistic.MAX.equals(statistic) ? Double::max : Double::sum; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdown/Application.java b/spring-boot-ops/src/main/java/com/baeldung/shutdown/Application.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/shutdown/Application.java rename to spring-boot-ops/src/main/java/com/baeldung/shutdown/Application.java diff --git a/spring-boot/src/main/java/com/baeldung/shutdown/ShutdownConfig.java b/spring-boot-ops/src/main/java/com/baeldung/shutdown/ShutdownConfig.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/shutdown/ShutdownConfig.java rename to spring-boot-ops/src/main/java/com/baeldung/shutdown/ShutdownConfig.java diff --git a/spring-boot/src/main/java/com/baeldung/shutdown/TerminateBean.java b/spring-boot-ops/src/main/java/com/baeldung/shutdown/TerminateBean.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/shutdown/TerminateBean.java rename to spring-boot-ops/src/main/java/com/baeldung/shutdown/TerminateBean.java diff --git a/spring-boot/src/main/java/com/baeldung/shutdown/shutdown/ShutdownController.java b/spring-boot-ops/src/main/java/com/baeldung/shutdown/shutdown/ShutdownController.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/shutdown/shutdown/ShutdownController.java rename to spring-boot-ops/src/main/java/com/baeldung/shutdown/shutdown/ShutdownController.java diff --git a/spring-boot-ops/src/main/java/com/baeldung/springbootnonwebapp/SpringBootConsoleApplication.java b/spring-boot-ops/src/main/java/com/baeldung/springbootnonwebapp/SpringBootConsoleApplication.java new file mode 100644 index 0000000000..9faa463378 --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/springbootnonwebapp/SpringBootConsoleApplication.java @@ -0,0 +1,38 @@ +package com.baeldung.springbootnonwebapp; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * 1. Act as main class for spring boot application + * 2. Also implements CommandLineRunner, so that code within run method + * is executed before application startup but after all beans are effectively created + * @author hemant + * + */ +@SpringBootApplication +public class SpringBootConsoleApplication implements CommandLineRunner { + + private static Logger LOG = LoggerFactory.getLogger(SpringBootConsoleApplication.class); + + public static void main(String[] args) { + LOG.info("STARTING THE APPLICATION"); + SpringApplication.run(SpringBootConsoleApplication.class, args); + LOG.info("APPLICATION FINISHED"); + } + + /** + * This method will be executed after the application context is loaded and + * right before the Spring Application main method is completed. + */ + @Override + public void run(String... args) throws Exception { + LOG.info("EXECUTING : command line runner"); + for (int i = 0; i < args.length; ++i) { + LOG.info("args[{}]: {}", i, args[i]); + } + } +} diff --git a/spring-boot/src/main/java/com/baeldung/webjar/TestController.java b/spring-boot-ops/src/main/java/com/baeldung/webjar/TestController.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/webjar/TestController.java rename to spring-boot-ops/src/main/java/com/baeldung/webjar/TestController.java diff --git a/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java b/spring-boot-ops/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java rename to spring-boot-ops/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/Application.java b/spring-boot-ops/src/main/java/org/baeldung/boot/Application.java new file mode 100644 index 0000000000..c1b6558b26 --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/Application.java @@ -0,0 +1,14 @@ +package org.baeldung.boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; + +@SpringBootApplication +public class Application { + private static ApplicationContext applicationContext; + + public static void main(String[] args) { + applicationContext = SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/config/WebConfig.java b/spring-boot-ops/src/main/java/org/baeldung/boot/config/WebConfig.java new file mode 100644 index 0000000000..6d8708b06a --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/config/WebConfig.java @@ -0,0 +1,28 @@ +package org.baeldung.boot.config; + +import org.baeldung.boot.converter.GenericBigDecimalConverter; +import org.baeldung.boot.converter.StringToEmployeeConverter; +import org.baeldung.boot.converter.StringToEnumConverterFactory; +import org.baeldung.boot.web.resolver.HeaderVersionArgumentResolver; +import org.springframework.context.annotation.Configuration; +import org.springframework.format.FormatterRegistry; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import java.util.List; + +@Configuration +public class WebConfig implements WebMvcConfigurer { + + @Override + public void addArgumentResolvers(final List argumentResolvers) { + argumentResolvers.add(new HeaderVersionArgumentResolver()); + } + + @Override + public void addFormatters(FormatterRegistry registry) { + registry.addConverter(new StringToEmployeeConverter()); + registry.addConverterFactory(new StringToEnumConverterFactory()); + registry.addConverter(new GenericBigDecimalConverter()); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/controller/GenericEntityController.java b/spring-boot-ops/src/main/java/org/baeldung/boot/controller/GenericEntityController.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/controller/GenericEntityController.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/controller/GenericEntityController.java diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java new file mode 100644 index 0000000000..f756a25f67 --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java @@ -0,0 +1,34 @@ +package org.baeldung.boot.converter; + +import com.google.common.collect.ImmutableSet; +import org.springframework.core.convert.TypeDescriptor; +import org.springframework.core.convert.converter.GenericConverter; + +import java.math.BigDecimal; +import java.util.Set; + +public class GenericBigDecimalConverter implements GenericConverter { + @Override + public Set getConvertibleTypes() { + + ConvertiblePair[] pairs = new ConvertiblePair[] { new ConvertiblePair(Number.class, BigDecimal.class), new ConvertiblePair(String.class, BigDecimal.class) }; + + return ImmutableSet.copyOf(pairs); + } + + @Override + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { + if (sourceType.getType() == BigDecimal.class) { + return source; + } + + if (sourceType.getType() == String.class) { + String number = (String) source; + return new BigDecimal(number); + } else { + Number number = (Number) source; + BigDecimal converted = new BigDecimal(number.doubleValue()); + return converted.setScale(2, BigDecimal.ROUND_HALF_EVEN); + } + } +} \ No newline at end of file diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java new file mode 100644 index 0000000000..e00d0ad312 --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java @@ -0,0 +1,13 @@ +package org.baeldung.boot.converter; + +import org.baeldung.boot.domain.Employee; +import org.springframework.core.convert.converter.Converter; + +public class StringToEmployeeConverter implements Converter { + + @Override + public Employee convert(String from) { + String[] data = from.split(","); + return new Employee(Long.parseLong(data[0]), Double.parseDouble(data[1])); + } +} \ No newline at end of file diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java new file mode 100644 index 0000000000..6fa51bfdcc --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java @@ -0,0 +1,27 @@ +package org.baeldung.boot.converter; + +import org.springframework.core.convert.converter.Converter; +import org.springframework.core.convert.converter.ConverterFactory; +import org.springframework.stereotype.Component; + +@Component +public class StringToEnumConverterFactory implements ConverterFactory { + + private static class StringToEnumConverter implements Converter { + + private Class enumType; + + public StringToEnumConverter(Class enumType) { + this.enumType = enumType; + } + + public T convert(String source) { + return (T) Enum.valueOf(this.enumType, source.trim()); + } + } + + @Override + public Converter getConverter(final Class targetType) { + return new StringToEnumConverter(targetType); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToLocalDateTimeConverter.java b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToLocalDateTimeConverter.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/converter/StringToLocalDateTimeConverter.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToLocalDateTimeConverter.java diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java new file mode 100644 index 0000000000..762d237156 --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java @@ -0,0 +1,15 @@ +package org.baeldung.boot.converter.controller; + +import org.baeldung.boot.domain.Employee; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/string-to-employee") +public class StringToEmployeeConverterController { + + @GetMapping + public ResponseEntity getStringToEmployee(@RequestParam("employee") Employee employee) { + return ResponseEntity.ok(employee); + } +} diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Employee.java b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Employee.java new file mode 100644 index 0000000000..8242e53200 --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Employee.java @@ -0,0 +1,37 @@ +package org.baeldung.boot.domain; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + + @Id + private long id; + private double salary; + + public Employee() { + } + + public Employee(long id, double salary) { + this.id = id; + this.salary = salary; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/domain/GenericEntity.java b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/GenericEntity.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/domain/GenericEntity.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/domain/GenericEntity.java diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Modes.java b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Modes.java new file mode 100644 index 0000000000..dcba064e8c --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Modes.java @@ -0,0 +1,6 @@ +package org.baeldung.boot.domain; + +public enum Modes { + + ALPHA, BETA; +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java b/spring-boot-ops/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java diff --git a/spring-boot/src/main/java/org/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java b/spring-boot-ops/src/main/java/org/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java diff --git a/spring-boot/src/main/java/org/baeldung/boot/web/resolver/Version.java b/spring-boot-ops/src/main/java/org/baeldung/boot/web/resolver/Version.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/web/resolver/Version.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/web/resolver/Version.java diff --git a/spring-boot-ops/src/main/resources/application.properties b/spring-boot-ops/src/main/resources/application.properties index e69de29bb2..a86bd3052e 100644 --- a/spring-boot-ops/src/main/resources/application.properties +++ b/spring-boot-ops/src/main/resources/application.properties @@ -0,0 +1,3 @@ +management.endpoints.web.exposure.include=* +management.metrics.enable.root=true +management.metrics.enable.jvm=true \ No newline at end of file diff --git a/spring-boot-ops/src/main/resources/logback.xml b/spring-boot-ops/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-ops/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/index.html b/spring-boot-ops/src/main/resources/templates/index.html similarity index 100% rename from spring-boot/src/main/resources/templates/index.html rename to spring-boot-ops/src/main/resources/templates/index.html diff --git a/spring-boot/src/test/java/com/baeldung/shutdown/ShutdownApplicationIntegrationTest.java b/spring-boot-ops/src/test/java/com/baeldung/shutdown/ShutdownApplicationIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/shutdown/ShutdownApplicationIntegrationTest.java rename to spring-boot-ops/src/test/java/com/baeldung/shutdown/ShutdownApplicationIntegrationTest.java diff --git a/spring-boot-ops/src/test/java/com/baeldung/springbootsimple/SpringBootTomcatApplicationIntegrationTest.java b/spring-boot-ops/src/test/java/com/baeldung/springbootsimple/SpringBootTomcatApplicationIntegrationTest.java new file mode 100644 index 0000000000..a10ebbbd35 --- /dev/null +++ b/spring-boot-ops/src/test/java/com/baeldung/springbootsimple/SpringBootTomcatApplicationIntegrationTest.java @@ -0,0 +1,16 @@ +package com.baeldung.springbootsimple; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringBootTomcatApplicationIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-boot-ops/src/test/java/com/baeldung/springbootsimple/SpringBootTomcatApplicationTests.java b/spring-boot-ops/src/test/java/com/baeldung/springbootsimple/SpringBootTomcatApplicationTests.java deleted file mode 100644 index 4c0d4d577a..0000000000 --- a/spring-boot-ops/src/test/java/com/baeldung/springbootsimple/SpringBootTomcatApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.springbootsimple; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class SpringBootTomcatApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-boot/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java b/spring-boot-ops/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java rename to spring-boot-ops/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java b/spring-boot-ops/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java rename to spring-boot-ops/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java b/spring-boot-ops/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java rename to spring-boot-ops/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java b/spring-boot-ops/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java rename to spring-boot-ops/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java diff --git a/spring-boot-ops/src/test/resources/application-integrationtest.properties b/spring-boot-ops/src/test/resources/application-integrationtest.properties new file mode 100644 index 0000000000..bcd03226d3 --- /dev/null +++ b/spring-boot-ops/src/test/resources/application-integrationtest.properties @@ -0,0 +1,4 @@ +spring.datasource.url=jdbc:mysql://localhost:3306/employee_int_test +spring.datasource.username=root +spring.datasource.password=root + diff --git a/spring-boot-ops/src/test/resources/application.properties b/spring-boot-ops/src/test/resources/application.properties new file mode 100644 index 0000000000..2095a82a14 --- /dev/null +++ b/spring-boot-ops/src/test/resources/application.properties @@ -0,0 +1,7 @@ +spring.mail.host=localhost +spring.mail.port=8025 +spring.mail.properties.mail.smtp.auth=false + +management.endpoints.web.exposure.include=* +management.endpoint.shutdown.enabled=true +endpoints.shutdown.enabled=true \ No newline at end of file diff --git a/spring-boot-persistence/.gitignore b/spring-boot-persistence/.gitignore new file mode 100644 index 0000000000..88e3308e9d --- /dev/null +++ b/spring-boot-persistence/.gitignore @@ -0,0 +1,5 @@ +/target/ +.settings/ +.classpath +.project + diff --git a/spring-boot-persistence/.mvn/wrapper/maven-wrapper.properties b/spring-boot-persistence/.mvn/wrapper/maven-wrapper.properties new file mode 100755 index 0000000000..a447c9fa81 --- /dev/null +++ b/spring-boot-persistence/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip \ No newline at end of file diff --git a/spring-boot-persistence/README.MD b/spring-boot-persistence/README.MD new file mode 100644 index 0000000000..6cf172426a --- /dev/null +++ b/spring-boot-persistence/README.MD @@ -0,0 +1,6 @@ +### Relevant Articles: + +- [Spring Boot with Multiple SQL Import Files](http://www.baeldung.com/spring-boot-sql-import-files) +- [Configuring Separate Spring DataSource for Tests](http://www.baeldung.com/spring-testing-separate-data-source) +- [Quick Guide on data.sql and schema.sql Files in Spring Boot](http://www.baeldung.com/spring-boot-data-sql-and-schema-sql) +- [Configuring a Tomcat Connection Pool in Spring Boot](https://www.baeldung.com/spring-boot-tomcat-connection-pool) diff --git a/spring-boot-persistence/mvnw b/spring-boot-persistence/mvnw new file mode 100755 index 0000000000..e96ccd5fbb --- /dev/null +++ b/spring-boot-persistence/mvnw @@ -0,0 +1,227 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/spring-boot-persistence/mvnw.cmd b/spring-boot-persistence/mvnw.cmd new file mode 100755 index 0000000000..4f0b068a03 --- /dev/null +++ b/spring-boot-persistence/mvnw.cmd @@ -0,0 +1,145 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/spring-boot-persistence/pom.xml b/spring-boot-persistence/pom.xml new file mode 100644 index 0000000000..08989edfa9 --- /dev/null +++ b/spring-boot-persistence/pom.xml @@ -0,0 +1,75 @@ + + + 4.0.0 + + com.baeldung + spring-boot-persistence + 0.1.0 + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.zaxxer + HikariCP + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.apache.tomcat + tomcat-jdbc + ${tomcat-jdbc.version} + + + mysql + mysql-connector-java + ${mysql-connector-java.version} + + + com.h2database + h2 + ${h2database.version} + runtime + + + + + UTF-8 + 1.8 + 8.0.12 + 9.0.10 + 1.4.197 + + + + spring-boot-persistence + + + src/main/resources + true + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spring-boot-persistence/src/main/java/com/baeldung/Application.java b/spring-boot-persistence/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..43888c2d67 --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/Application.java @@ -0,0 +1,14 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; + +@SpringBootApplication +public class Application { + private static ApplicationContext applicationContext; + + public static void main(String[] args) { + applicationContext = SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java b/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java new file mode 100644 index 0000000000..ef90714347 --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java @@ -0,0 +1,67 @@ +package com.baeldung.boot.config; + +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@EnableJpaRepositories(basePackages = { "org.baeldung.boot.repository", "org.baeldung.repository" }) +@PropertySource("classpath:persistence-generic-entity.properties") +@EnableTransactionManagement +public class H2JpaConfig { + + @Autowired + private Environment env; + + @Bean + public DataSource dataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); + dataSource.setUrl(env.getProperty("jdbc.url")); + dataSource.setUsername(env.getProperty("jdbc.user")); + dataSource.setPassword(env.getProperty("jdbc.pass")); + + return dataSource; + } + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[] { "org.baeldung.boot.domain" }); + em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); + em.setJpaProperties(additionalProperties()); + return em; + } + + @Bean + JpaTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(entityManagerFactory); + return transactionManager; + } + + final Properties additionalProperties() { + final Properties hibernateProperties = new Properties(); + + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); + + return hibernateProperties; + } + +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/domain/Country.java b/spring-boot-persistence/src/main/java/com/baeldung/domain/Country.java new file mode 100644 index 0000000000..e6a88c7121 --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/domain/Country.java @@ -0,0 +1,36 @@ +package com.baeldung.domain; + +import static javax.persistence.GenerationType.IDENTITY; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Country { + + @Id + @GeneratedValue(strategy = IDENTITY) + private Integer id; + + @Column(nullable = false) + private String name; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/domain/User.java b/spring-boot-persistence/src/main/java/com/baeldung/domain/User.java new file mode 100644 index 0000000000..9d1fc4c8ad --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/domain/User.java @@ -0,0 +1,49 @@ +package com.baeldung.domain; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue + private Integer id; + private String name; + private Integer status; + + public User() { + } + + public User(String name, Integer status) { + this.name = name; + this.status = status; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/repository/UserRepository.java b/spring-boot-persistence/src/main/java/com/baeldung/repository/UserRepository.java new file mode 100644 index 0000000000..bdc1e0af33 --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/repository/UserRepository.java @@ -0,0 +1,82 @@ +package com.baeldung.repository; + +import com.baeldung.domain.User; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Repository; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Stream; + +@Repository("userRepository") +public interface UserRepository extends JpaRepository { + + int countByStatus(int status); + + Optional findOneByName(String name); + + Stream findAllByName(String name); + + @Async + CompletableFuture findOneByStatus(Integer status); + + @Query("SELECT u FROM User u WHERE u.status = 1") + Collection findAllActiveUsers(); + + @Query(value = "SELECT * FROM USERS u WHERE u.status = 1", nativeQuery = true) + Collection findAllActiveUsersNative(); + + @Query("SELECT u FROM User u WHERE u.status = ?1") + User findUserByStatus(Integer status); + + @Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true) + User findUserByStatusNative(Integer status); + + @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") + User findUserByStatusAndName(Integer status, String name); + + @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") + User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name); + + @Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) + User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name); + + @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") + User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName); + + @Query("SELECT u FROM User u WHERE u.name like ?1%") + User findUserByNameLike(String name); + + @Query("SELECT u FROM User u WHERE u.name like :name%") + User findUserByNameLikeNamedParam(@Param("name") String name); + + @Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true) + User findUserByNameLikeNative(String name); + + @Query(value = "SELECT u FROM User u") + List findAllUsers(Sort sort); + + @Query(value = "SELECT u FROM User u ORDER BY id") + Page findAllUsersWithPagination(Pageable pageable); + + @Query(value = "SELECT * FROM Users ORDER BY id \n-- #pageable\n", countQuery = "SELECT count(*) FROM Users", nativeQuery = true) + Page findAllUsersWithPaginationNative(Pageable pageable); + + @Modifying + @Query("update User u set u.status = :status where u.name = :name") + int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); + + @Modifying + @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) + int updateUserSetStatusForNameNative(Integer status, String name); + +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java new file mode 100644 index 0000000000..ff37442cd4 --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java @@ -0,0 +1,22 @@ +package com.baeldung.tomcatconnectionpool.application; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@SpringBootApplication +@EnableAutoConfiguration +@ComponentScan(basePackages={"com.baeldung.tomcatconnectionpool.application"}) +@EnableJpaRepositories(basePackages="com.baeldung.tomcatconnectionpool.application.repositories") +@EnableTransactionManagement +@EntityScan(basePackages="com.baeldung.tomcatconnectionpool.application.entities") +public class SpringBootConsoleApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootConsoleApplication.class); + } +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java new file mode 100644 index 0000000000..4003d5aca9 --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java @@ -0,0 +1,53 @@ +package com.baeldung.tomcatconnectionpool.application.entities; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "customers") +public class Customer { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + @Column(name = "first_name") + private String firstName; + @Column(name = "last_name") + private String lastName; + + public Customer() {} + + public Customer(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public long getId() { + return id; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + @Override + public String toString() { + return "Customer{" + "id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + '}'; + } +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java new file mode 100644 index 0000000000..770906439c --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.tomcatconnectionpool.application.repositories; + +import com.baeldung.tomcatconnectionpool.application.entities.Customer; +import java.util.List; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface CustomerRepository extends CrudRepository { + + List findByLastName(String lastName); +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java new file mode 100644 index 0000000000..9666bac5a5 --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java @@ -0,0 +1,37 @@ +package com.baeldung.tomcatconnectionpool.application.runners; + +import com.baeldung.tomcatconnectionpool.application.entities.Customer; +import com.baeldung.tomcatconnectionpool.application.repositories.CustomerRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; + +@Component +public class CommandLineCrudRunner implements CommandLineRunner { + + private static final Logger logger = LoggerFactory.getLogger(CommandLineCrudRunner.class); + + @Autowired + private CustomerRepository customerRepository; + + @Override + public void run(String... args) throws Exception { + customerRepository.save(new Customer("John", "Doe")); + customerRepository.save(new Customer("Jennifer", "Wilson")); + + logger.info("Customers found with findAll():"); + customerRepository.findAll().forEach(c -> logger.info(c.toString())); + + logger.info("Customer found with findById(1L):"); + Customer customer = customerRepository.findById(1L) + .orElseGet(() -> new Customer("Non-existing customer", "")); + logger.info(customer.toString()); + + logger.info("Customer found with findByLastName('Wilson'):"); + customerRepository.findByLastName("Wilson").forEach(c -> { + logger.info(c.toString()); + }); + } +} diff --git a/spring-boot-persistence/src/main/java/org/baeldung/boot/domain/GenericEntity.java b/spring-boot-persistence/src/main/java/org/baeldung/boot/domain/GenericEntity.java new file mode 100644 index 0000000000..f1c936e432 --- /dev/null +++ b/spring-boot-persistence/src/main/java/org/baeldung/boot/domain/GenericEntity.java @@ -0,0 +1,42 @@ +package org.baeldung.boot.domain; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class GenericEntity { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + private String value; + + public GenericEntity() { + } + + public GenericEntity(String value) { + this.value = value; + } + + public GenericEntity(Long id, String value) { + this.id = id; + this.value = value; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/spring-boot-persistence/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java b/spring-boot-persistence/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java new file mode 100644 index 0000000000..d897e17afe --- /dev/null +++ b/spring-boot-persistence/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java @@ -0,0 +1,7 @@ +package org.baeldung.boot.repository; + +import org.baeldung.boot.domain.GenericEntity; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface GenericEntityRepository extends JpaRepository { +} diff --git a/spring-boot-persistence/src/main/resources/application.properties b/spring-boot-persistence/src/main/resources/application.properties new file mode 100644 index 0000000000..303ce33c25 --- /dev/null +++ b/spring-boot-persistence/src/main/resources/application.properties @@ -0,0 +1,16 @@ +spring.datasource.tomcat.initial-size=15 +spring.datasource.tomcat.max-wait=20000 +spring.datasource.tomcat.max-active=50 +spring.datasource.tomcat.max-idle=15 +spring.datasource.tomcat.min-idle=8 +spring.datasource.tomcat.default-auto-commit=true +spring.datasource.url=jdbc:h2:mem:test +spring.datasource.username=root +spring.datasource.password= +spring.datasource.driver-class-name=org.h2.Driver + +spring.jpa.show-sql=false +spring.jpa.hibernate.ddl-auto=update +spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect +spring.jpa.properties.hibernate.id.new_generator_mappings=false diff --git a/spring-boot-persistence/src/main/resources/data.sql b/spring-boot-persistence/src/main/resources/data.sql new file mode 100644 index 0000000000..feef02b6cf --- /dev/null +++ b/spring-boot-persistence/src/main/resources/data.sql @@ -0,0 +1,10 @@ +insert into users values (1, 'Alex', 1); +insert into users values (2, 'Bob', 1); +insert into users values (3, 'John', 0); +insert into users values (4, 'Harry', 0); +insert into users values (5, 'Smith', 1); + +INSERT INTO country (name) VALUES ('India'); +INSERT INTO country (name) VALUES ('Brazil'); +INSERT INTO country (name) VALUES ('USA'); +INSERT INTO country (name) VALUES ('Italy'); \ No newline at end of file diff --git a/spring-boot-persistence/src/main/resources/logback.xml b/spring-boot-persistence/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-persistence/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot-persistence/src/main/resources/persistence-generic-entity.properties b/spring-boot-persistence/src/main/resources/persistence-generic-entity.properties new file mode 100644 index 0000000000..b19304cb1f --- /dev/null +++ b/spring-boot-persistence/src/main/resources/persistence-generic-entity.properties @@ -0,0 +1,8 @@ +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +jdbc.user=sa +jdbc.pass=sa + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop diff --git a/spring-boot-persistence/src/main/resources/schema.sql b/spring-boot-persistence/src/main/resources/schema.sql new file mode 100644 index 0000000000..4cfc8a7927 --- /dev/null +++ b/spring-boot-persistence/src/main/resources/schema.sql @@ -0,0 +1,15 @@ +drop table if exists USERS; +drop table if exists country; + +create table USERS( + ID int not null AUTO_INCREMENT, + NAME varchar(100) not null, + STATUS int, + PRIMARY KEY ( ID ) +); + +CREATE TABLE country ( + id INTEGER NOT NULL AUTO_INCREMENT, + name VARCHAR(128) NOT NULL, + PRIMARY KEY (id) +); \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootH2IntegrationTest.java b/spring-boot-persistence/src/test/java/com/baeldung/SpringBootH2IntegrationTest.java similarity index 91% rename from spring-boot/src/test/java/org/baeldung/SpringBootH2IntegrationTest.java rename to spring-boot-persistence/src/test/java/com/baeldung/SpringBootH2IntegrationTest.java index 290cfbe081..6479e90113 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootH2IntegrationTest.java +++ b/spring-boot-persistence/src/test/java/com/baeldung/SpringBootH2IntegrationTest.java @@ -1,7 +1,8 @@ -package org.baeldung; +package com.baeldung; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; -import org.baeldung.boot.Application; -import org.baeldung.boot.config.H2JpaConfig; import org.baeldung.boot.domain.GenericEntity; import org.baeldung.boot.repository.GenericEntityRepository; import org.junit.Test; @@ -10,8 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import com.baeldung.boot.config.H2JpaConfig; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = { Application.class, H2JpaConfig.class }) diff --git a/spring-boot-persistence/src/test/java/com/baeldung/SpringBootJPAIntegrationTest.java b/spring-boot-persistence/src/test/java/com/baeldung/SpringBootJPAIntegrationTest.java new file mode 100644 index 0000000000..eef9ebe953 --- /dev/null +++ b/spring-boot-persistence/src/test/java/com/baeldung/SpringBootJPAIntegrationTest.java @@ -0,0 +1,27 @@ +package com.baeldung; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.baeldung.boot.domain.GenericEntity; +import org.baeldung.boot.repository.GenericEntityRepository; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringBootJPAIntegrationTest { + @Autowired + private GenericEntityRepository genericEntityRepository; + + @Test + public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() { + GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test")); + GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null); + assertNotNull(foundEntity); + assertEquals(genericEntity.getValue(), foundEntity.getValue()); + } +} \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootProfileIntegrationTest.java b/spring-boot-persistence/src/test/java/com/baeldung/SpringBootProfileIntegrationTest.java similarity index 95% rename from spring-boot/src/test/java/org/baeldung/SpringBootProfileIntegrationTest.java rename to spring-boot-persistence/src/test/java/com/baeldung/SpringBootProfileIntegrationTest.java index 128a05f103..4c68f1d4a0 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootProfileIntegrationTest.java +++ b/spring-boot-persistence/src/test/java/com/baeldung/SpringBootProfileIntegrationTest.java @@ -1,6 +1,8 @@ -package org.baeldung; +package com.baeldung; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; -import org.baeldung.boot.Application; import org.baeldung.boot.domain.GenericEntity; import org.baeldung.boot.repository.GenericEntityRepository; import org.baeldung.config.H2TestProfileJPAConfig; @@ -11,9 +13,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - @RunWith(SpringRunner.class) @SpringBootTest(classes = { Application.class, H2TestProfileJPAConfig.class }) @ActiveProfiles("test") diff --git a/spring-boot-persistence/src/test/java/com/baeldung/repository/UserRepositoryIntegrationTest.java b/spring-boot-persistence/src/test/java/com/baeldung/repository/UserRepositoryIntegrationTest.java new file mode 100644 index 0000000000..af5abc22d7 --- /dev/null +++ b/spring-boot-persistence/src/test/java/com/baeldung/repository/UserRepositoryIntegrationTest.java @@ -0,0 +1,30 @@ +package com.baeldung.repository; + +import com.baeldung.domain.User; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.Collection; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Created by adam. + */ +@RunWith(SpringRunner.class) +@DataJpaTest +public class UserRepositoryIntegrationTest { + + @Autowired private UserRepository userRepository; + + @Test + public void givenTwoImportFilesWhenFindAllShouldReturnSixUsers() { + Collection users = userRepository.findAll(); + + assertThat(users.size()).isEqualTo(9); + } + +} diff --git a/spring-boot-persistence/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java b/spring-boot-persistence/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java new file mode 100644 index 0000000000..c68e137fb0 --- /dev/null +++ b/spring-boot-persistence/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java @@ -0,0 +1,22 @@ +package com.baeldung.tomcatconnectionpool.test.application; + +import javax.sql.DataSource; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.junit4.SpringRunner; +import static org.assertj.core.api.Assertions.*; +import org.springframework.boot.test.context.SpringBootTest; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringBootTomcatConnectionPoolIntegrationTest { + + @Autowired + private DataSource dataSource; + + @Test + public void givenTomcatConnectionPoolInstance_whenCheckedPoolClassName_thenCorrect() { + assertThat(dataSource.getClass().getName()).isEqualTo("org.apache.tomcat.jdbc.pool.DataSource"); + } +} diff --git a/spring-boot/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java b/spring-boot-persistence/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java similarity index 94% rename from spring-boot/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java rename to spring-boot-persistence/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java index d0b92a7a93..7f962e1417 100644 --- a/spring-boot/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java +++ b/spring-boot-persistence/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java @@ -18,7 +18,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration -@EnableJpaRepositories(basePackages = { "org.baeldung.repository", "org.baeldung.boot.repository", "org.baeldung.boot.boottest" }) +@EnableJpaRepositories(basePackages = { "org.baeldung.repository", "org.baeldung.boot.repository" }) @EnableTransactionManagement public class H2TestProfileJPAConfig { @@ -41,7 +41,7 @@ public class H2TestProfileJPAConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.domain", "org.baeldung.boot.domain", "org.baeldung.boot.boottest", "org.baeldung.model" }); + em.setPackagesToScan(new String[] { "org.baeldung.domain", "org.baeldung.boot.domain" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/spring-boot-persistence/src/test/resources/application.properties b/spring-boot-persistence/src/test/resources/application.properties new file mode 100644 index 0000000000..a5c1d983cf --- /dev/null +++ b/spring-boot-persistence/src/test/resources/application.properties @@ -0,0 +1,16 @@ +# spring.datasource.x +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +spring.datasource.username=sa +spring.datasource.password=sa + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop +hibernate.cache.use_second_level_cache=true +hibernate.cache.use_query_cache=true +hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory + +spring.jpa.properties.hibernate.hbm2ddl.import_files=migrated_users.sql +spring.datasource.data=import_*_users.sql \ No newline at end of file diff --git a/spring-boot-persistence/src/test/resources/import_active_users.sql b/spring-boot-persistence/src/test/resources/import_active_users.sql new file mode 100644 index 0000000000..0ec3161d91 --- /dev/null +++ b/spring-boot-persistence/src/test/resources/import_active_users.sql @@ -0,0 +1,3 @@ +insert into USERS(name, status, id) values('Peter', 1, 1); +insert into USERS(name, status, id) values('David', 1, 2); +insert into USERS(name, status, id) values('Ed', 1, 3); diff --git a/spring-boot-persistence/src/test/resources/import_inactive_users.sql b/spring-boot-persistence/src/test/resources/import_inactive_users.sql new file mode 100644 index 0000000000..91bb759607 --- /dev/null +++ b/spring-boot-persistence/src/test/resources/import_inactive_users.sql @@ -0,0 +1,3 @@ +insert into users(name, status, id) values('Monica', 0, 4); +insert into users(name, status, id) values('Paul', 0, 5); +insert into users(name, status, id) values('George', 0, 6); \ No newline at end of file diff --git a/spring-boot-persistence/src/test/resources/migrated_users.sql b/spring-boot-persistence/src/test/resources/migrated_users.sql new file mode 100644 index 0000000000..11d1a69110 --- /dev/null +++ b/spring-boot-persistence/src/test/resources/migrated_users.sql @@ -0,0 +1,3 @@ +insert into USERS(name, status, id) values('Peter', 1, 7); +insert into USERS(name, status, id) values('David', 1, 8); +insert into USERS(name, status, id) values('Ed', 1, 9); diff --git a/spring-boot-property-exp/pom.xml b/spring-boot-property-exp/pom.xml index abf9f45d1c..7d8f2480ac 100644 --- a/spring-boot-property-exp/pom.xml +++ b/spring-boot-property-exp/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-boot-property-exp com.baeldung @@ -18,8 +18,4 @@ property-exp-custom-config - - UTF-8 - - diff --git a/spring-boot-property-exp/property-exp-custom-config/pom.xml b/spring-boot-property-exp/property-exp-custom-config/pom.xml index 019e2362a1..958a07a86b 100644 --- a/spring-boot-property-exp/property-exp-custom-config/pom.xml +++ b/spring-boot-property-exp/property-exp-custom-config/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 property-exp-custom @@ -14,13 +15,11 @@ - org.springframework.boot spring-boot-starter - 1.5.10.RELEASE + ${spring-boot.version} - @@ -68,7 +67,7 @@ - UTF-8 + 1.5.10.RELEASE Custom Property Value diff --git a/spring-boot-property-exp/property-exp-custom-config/src/main/resources/logback.xml b/spring-boot-property-exp/property-exp-custom-config/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-property-exp/property-exp-custom-config/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot-property-exp/property-exp-default-config/pom.xml b/spring-boot-property-exp/property-exp-default-config/pom.xml index e4cbaebf56..4ede36e61a 100644 --- a/spring-boot-property-exp/property-exp-default-config/pom.xml +++ b/spring-boot-property-exp/property-exp-default-config/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 property-exp-default @@ -8,10 +9,10 @@ jar - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 @@ -34,7 +35,6 @@ - UTF-8 Custom Property Value diff --git a/spring-boot-property-exp/property-exp-default-config/src/main/resources/logback.xml b/spring-boot-property-exp/property-exp-default-config/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-property-exp/property-exp-default-config/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot-security/pom.xml b/spring-boot-security/pom.xml index 8763c210c8..6bc013d1ed 100644 --- a/spring-boot-security/pom.xml +++ b/spring-boot-security/pom.xml @@ -1,8 +1,7 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-boot-security 0.0.1-SNAPSHOT jar @@ -20,7 +19,7 @@ org.springframework.boot spring-boot-dependencies - 1.5.9.RELEASE + ${spring-boot.version} pom import @@ -28,10 +27,6 @@ - - - - org.springframework.boot spring-boot-starter-security @@ -44,6 +39,23 @@ org.springframework.boot spring-boot-starter-web + + + + org.springframework.security + spring-security-taglibs + + + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + javax.servlet + jstl + org.springframework.boot @@ -62,13 +74,14 @@ org.springframework.boot spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} - UTF-8 - UTF-8 + 1.5.9.RELEASE + 2.0.4.RELEASE diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/MethodSecurityConfigurer.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/MethodSecurityConfigurer.java new file mode 100644 index 0000000000..dccbace106 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/MethodSecurityConfigurer.java @@ -0,0 +1,13 @@ +package com.baeldung.integrationtesting; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; + +@Configuration +@EnableGlobalMethodSecurity( + prePostEnabled = true, + securedEnabled = true) +public class MethodSecurityConfigurer extends GlobalMethodSecurityConfiguration { + +} diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredApplication.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredApplication.java new file mode 100644 index 0000000000..18469e4752 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.integrationtesting; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SecuredApplication { + + public static void main(String[] args) { + SpringApplication.run(SecuredApplication.class, args); + } + +} diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredController.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredController.java new file mode 100644 index 0000000000..495c358784 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredController.java @@ -0,0 +1,21 @@ +package com.baeldung.integrationtesting; + +import java.util.Arrays; +import java.util.List; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class SecuredController { + + @GetMapping("/public/hello") + public List publicHello() { + return Arrays.asList("Hello", "World", "from", "Public"); + } + + @GetMapping("/private/hello") + public List privateHello() { + return Arrays.asList("Hello", "World", "from", "Private"); + } + +} diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredService.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredService.java new file mode 100644 index 0000000000..25253f163a --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredService.java @@ -0,0 +1,13 @@ +package com.baeldung.integrationtesting; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; + +@Service +public class SecuredService { + + @PreAuthorize("authenticated") + public String sayHelloSecured() { + return "Hello user."; + } +} diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java new file mode 100644 index 0000000000..32a48ce612 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java @@ -0,0 +1,31 @@ +package com.baeldung.integrationtesting; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("spring") + .password("secret") + .roles("USER"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/private/**") + .hasRole("USER") + .antMatchers("/public/**") + .permitAll() + .and() + .httpBasic(); + } + + +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java new file mode 100644 index 0000000000..eca093a76f --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java @@ -0,0 +1,14 @@ +package com.baeldung.springsecuritytaglibs; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping("/") +public class HomeController { + + @RequestMapping + public String home() { + return "home"; + } +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java new file mode 100644 index 0000000000..397ea47f96 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java @@ -0,0 +1,9 @@ +package com.baeldung.springsecuritytaglibs; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; + +@SpringBootApplication +@PropertySource("classpath:application-taglibs.properties") +public class SpringBootSecurityTagLibsApplication { +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java new file mode 100644 index 0000000000..665dd0bce9 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java @@ -0,0 +1,31 @@ +package com.baeldung.springsecuritytaglibs.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SpringBootSecurityTagLibsConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("testUser") + .password("password") + .roles("ADMIN"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + // @formatter:off + http.csrf() + .and() + .authorizeRequests() + .antMatchers("/userManagement").hasRole("ADMIN") + .anyRequest().permitAll().and().httpBasic(); + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-boot-security/src/main/resources/application-taglibs.properties b/spring-boot-security/src/main/resources/application-taglibs.properties new file mode 100644 index 0000000000..218868405f --- /dev/null +++ b/spring-boot-security/src/main/resources/application-taglibs.properties @@ -0,0 +1,3 @@ +#jsp config +spring.mvc.view.prefix: /WEB-INF/views/ +spring.mvc.view.suffix: .jsp diff --git a/spring-boot-security/src/main/resources/application.properties b/spring-boot-security/src/main/resources/application.properties index c2b8d70dc6..e776132359 100644 --- a/spring-boot-security/src/main/resources/application.properties +++ b/spring-boot-security/src/main/resources/application.properties @@ -1,4 +1,4 @@ #spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration #security.user.password=password #security.oauth2.client.client-id=client -#security.oauth2.client.client-secret=secret +#security.oauth2.client.client-secret=secret \ No newline at end of file diff --git a/spring-boot-security/src/main/resources/logback.xml b/spring-boot-security/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-security/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp b/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp new file mode 100644 index 0000000000..80ecd61cb5 --- /dev/null +++ b/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp @@ -0,0 +1,38 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> +<%@ taglib prefix="sec" + uri="http://www.springframework.org/security/tags"%> + + + + + +Home Page + + + + Login + + + + Logout + + + +

    + Welcome back, +

    + + Manage Users + +
    + + Text Field:
    + + + + Manage Users + +
    + + \ No newline at end of file diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerRestTemplateIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerRestTemplateIntegrationTest.java new file mode 100644 index 0000000000..c224058155 --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerRestTemplateIntegrationTest.java @@ -0,0 +1,34 @@ +package com.baeldung.integrationtesting; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class SecuredControllerRestTemplateIntegrationTest { + + @Autowired + private TestRestTemplate template; + + @Test + public void givenRequestOnPrivateService_shouldFailWith401() throws Exception { + ResponseEntity result = template.getForEntity("/private/hello", String.class); + assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); + } + + @Test + public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception { + ResponseEntity result = template.withBasicAuth("spring", "secret") + .getForEntity("/private/hello", String.class); + assertEquals(HttpStatus.OK, result.getStatusCode()); + } + +} diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerSpringBootIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerSpringBootIntegrationTest.java new file mode 100644 index 0000000000..ce9e6de917 --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerSpringBootIntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.integrationtesting; + +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class SecuredControllerSpringBootIntegrationTest { + + @Autowired + private WebApplicationContext context; + + private MockMvc mvc; + + @Before + public void setup() { + mvc = MockMvcBuilders + .webAppContextSetup(context) + .apply(springSecurity()) + .build(); + } + + @Test + public void givenRequestOnPrivateService_shouldFailWith401() throws Exception { + mvc.perform(get("/private/hello") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isUnauthorized()); + } + + @WithMockUser("spring") + @Test + public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception { + mvc.perform(get("/private/hello") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + +} diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerWebMvcIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerWebMvcIntegrationTest.java new file mode 100644 index 0000000000..7281648856 --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerWebMvcIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.integrationtesting; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.integrationtesting.SecuredController; + +@RunWith(SpringRunner.class) +@WebMvcTest(SecuredController.class) +public class SecuredControllerWebMvcIntegrationTest { + + @Autowired + private MockMvc mvc; + + @Test + public void givenRequestOnPrivateService_shouldFailWith401() throws Exception { + mvc.perform(get("/private/hello") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isUnauthorized()); + } + + @WithMockUser(value = "spring") + @Test + public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception { + mvc.perform(get("/private/hello") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + +} diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredMethodSpringBootIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredMethodSpringBootIntegrationTest.java new file mode 100644 index 0000000000..816b05bd5a --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredMethodSpringBootIntegrationTest.java @@ -0,0 +1,32 @@ +package com.baeldung.integrationtesting; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.integrationtesting.SecuredService; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SecuredMethodSpringBootIntegrationTest { + + @Autowired + private SecuredService service; + + @Test(expected = AuthenticationCredentialsNotFoundException.class) + public void givenUnauthenticated_whenCallService_thenThrowsException() { + service.sayHelloSecured(); + } + + @WithMockUser(username="spring") + @Test + public void givenAuthenticated_whenCallServiceWithSecured_thenOk() { + assertThat(service.sayHelloSecured()).isNotBlank(); + } +} diff --git a/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java b/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java new file mode 100644 index 0000000000..0585c06a59 --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.springsecuritytaglibs; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SpringBootSecurityTagLibsApplication.class) +public class HomeControllerUnitTest { + + @Autowired + private TestRestTemplate restTemplate; + + @Test + public void whenUserIsAuthenticatedThenAuthenticatedSectionsShowOnSite() throws Exception { + String body = this.restTemplate.withBasicAuth("testUser", "password") + .getForEntity("/", String.class) + .getBody(); + + // test + assertFalse(body.contains("Login")); + + // test + assertTrue(body.contains("Logout")); + + // test + assertTrue(body.contains("Manage Users")); + + // test + assertTrue(body.contains("testUser")); + + // test + assertTrue(body.contains("")); + + // test + assertTrue(body.contains(" + assertTrue(body.contains("")); + } + + @Test + public void whenUserIsNotAuthenticatedThenOnlyAnonymousSectionsShowOnSite() throws Exception { + String body = this.restTemplate.getForEntity("/", String.class) + .getBody(); + + // test + assertTrue(body.contains("Login")); + + // test + assertFalse(body.contains("Logout")); + } +} diff --git a/spring-boot-vue/.gitignore b/spring-boot-vue/.gitignore new file mode 100644 index 0000000000..82eca336e3 --- /dev/null +++ b/spring-boot-vue/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/spring-boot-vue/README.md b/spring-boot-vue/README.md new file mode 100644 index 0000000000..e68f961e51 --- /dev/null +++ b/spring-boot-vue/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Vue.js Frontend with a Spring Boot Backend](http://www.baeldung.com/spring-boot-vue-js) diff --git a/spring-boot-vue/pom.xml b/spring-boot-vue/pom.xml new file mode 100644 index 0000000000..d581b11d68 --- /dev/null +++ b/spring-boot-vue/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + + com.baeldung + spring-boot-vue + 0.0.1-SNAPSHOT + jar + + spring-boot-vue + Demo project for Spring Boot Vue project + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-boot-vue/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java b/spring-boot-vue/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java new file mode 100644 index 0000000000..c4213af0a3 --- /dev/null +++ b/spring-boot-vue/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.springbootmvc; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +@SpringBootApplication +public class SpringBootMvcApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootMvcApplication.class, args); + } +} diff --git a/spring-boot-vue/src/main/java/com/baeldung/springbootmvc/controllers/MainController.java b/spring-boot-vue/src/main/java/com/baeldung/springbootmvc/controllers/MainController.java new file mode 100644 index 0000000000..37b74876cf --- /dev/null +++ b/spring-boot-vue/src/main/java/com/baeldung/springbootmvc/controllers/MainController.java @@ -0,0 +1,18 @@ +package com.baeldung.springbootmvc.controllers; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +public class MainController { + + @RequestMapping(value = "/", method = RequestMethod.GET) + public String index(Model model) { + // this attribute will be available in the view index.html as a thymeleaf variable + model.addAttribute("eventName", "FIFA 2018"); + // this just means render index.html from static/ area + return "index"; + } +} diff --git a/spring-boot-vue/src/main/resources/application.properties b/spring-boot-vue/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-vue/src/main/resources/logback.xml b/spring-boot-vue/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-vue/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot-vue/src/main/resources/static/favicon.ico b/spring-boot-vue/src/main/resources/static/favicon.ico new file mode 100644 index 0000000000..64105ac11c Binary files /dev/null and b/spring-boot-vue/src/main/resources/static/favicon.ico differ diff --git a/spring-boot-vue/src/main/resources/templates/index.html b/spring-boot-vue/src/main/resources/templates/index.html new file mode 100644 index 0000000000..9fa374282a --- /dev/null +++ b/spring-boot-vue/src/main/resources/templates/index.html @@ -0,0 +1,98 @@ + + + + + + + + + + + + + +
    +

    This is an example Vue.js application developed with Spring Boot

    +

    This file is rendered by a Spring built-in default controller for index.html (/) using + Spring's built-in + Thymeleaf templating engine. + Although we don't need it per se, we customized the information passed to this + view from thymeleaf by adding a controller method for "/" route to demonstrate how to pass information from + Thymeleaf to this page. + The combination of template engine and frontend framework like Vue can make this a powerful approach to build + more complex applications while leveraging the benefits of a framework like Vue.js. + You can use thymeleaf features too but this project focuses mainly on using Vue.js on the + frontend as the framework and makes minimal use of Thymeleaf. + Also we don't use any routing and multiple components in this example, so what you see is technically a + Single Page Application (SPA) without any routes configured. +

    + +
    +
    + Name of Event: + +
    +
    + +
      +
    • + + +
    • +
    +
    +
    +
    + + + + + + + + \ No newline at end of file diff --git a/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationUnitTest.java b/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationUnitTest.java new file mode 100644 index 0000000000..567b239ed2 --- /dev/null +++ b/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.springbootmvc; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +public class SpringBootMvcApplicationUnitTest { + + @Autowired + private MockMvc mockMvc; + + /** + * If this test passes, we got a page with the thymeleaf provided variable + * value for eventName + */ + @Test + public void shouldLoadCorrectIndexPage() throws Exception { + mockMvc.perform(get("/")).andExpect(status().isOk()). + andExpect(MockMvcResultMatchers.content() + .string(containsString("FIFA 2018"))); + } + +} diff --git a/spring-boot/.factorypath b/spring-boot/.factorypath index 88c3910e93..22b8a1ce95 100644 --- a/spring-boot/.factorypath +++ b/spring-boot/.factorypath @@ -1,4 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + @@ -16,7 +38,6 @@ - @@ -32,9 +53,7 @@ - - @@ -48,9 +67,6 @@ - - - @@ -101,19 +117,10 @@ - - - - - - - - - - + @@ -162,7 +169,6 @@ - diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 79f66b4a38..54382992d4 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -3,37 +3,33 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: -- [Quick Guide to @RestClientTest in Spring Boot](http://www.baeldung.com/restclienttest-in-spring-boot) -- [Intro to Spring Boot Starters](http://www.baeldung.com/spring-boot-starters) - [A Guide to Spring in Eclipse STS](http://www.baeldung.com/eclipse-sts-spring) -- [Introduction to WebJars](http://www.baeldung.com/maven-webjars) -- [Create a Fat Jar App with Spring Boot](http://www.baeldung.com/deployable-fat-jar-spring-boot) - [The @ServletComponentScan Annotation in Spring Boot](http://www.baeldung.com/spring-servletcomponentscan) -- [A Custom Data Binder in Spring MVC](http://www.baeldung.com/spring-mvc-custom-data-binder) - [Intro to Building an Application with Spring Boot](http://www.baeldung.com/intro-to-spring-boot) - [How to Register a Servlet in a Java Web Application](http://www.baeldung.com/register-servlet) - [Guide to Spring WebUtils and ServletRequestUtils](http://www.baeldung.com/spring-webutils-servletrequestutils) - [Using Custom Banners in Spring Boot](http://www.baeldung.com/spring-boot-custom-banners) - [Guide to Internationalization in Spring Boot](http://www.baeldung.com/spring-boot-internationalization) - [Create a Custom FailureAnalyzer with Spring Boot](http://www.baeldung.com/spring-boot-failure-analyzer) -- [Configuring Separate Spring DataSource for Tests](http://www.baeldung.com/spring-testing-separate-data-source) - [Dynamic DTO Validation Config Retrieved from DB](http://www.baeldung.com/spring-dynamic-dto-validation) - [Custom Information in Spring Boot Info Endpoint](http://www.baeldung.com/spring-boot-info-actuator-custom) - [Using @JsonComponent in Spring Boot](http://www.baeldung.com/spring-boot-jsoncomponent) - [Testing in Spring Boot](http://www.baeldung.com/spring-boot-testing) - [Guide to @ConfigurationProperties in Spring Boot](http://www.baeldung.com/configuration-properties-in-spring-boot) - [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) - [Guide to Spring Type Conversions](http://www.baeldung.com/spring-type-conversions) -- [Quick Guide on data.sql and schema.sql Files in Spring Boot](http://www.baeldung.com/spring-boot-data-sql-and-schema-sql) -- [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8) -- [A Quick Guide to Maven Wrapper](http://www.baeldung.com/maven-wrapper) - [An Introduction to Kong](http://www.baeldung.com/kong) - [Spring Boot Customize Whitelabel Error Page](http://www.baeldung.com/spring-boot-custom-error-page) - [Spring Boot: Configuring a Main Class](http://www.baeldung.com/spring-boot-main-class) -- [Shutdown a Spring Boot Application](http://www.baeldung.com/spring-boot-shutdown) - [A Quick Intro to the SpringBootServletInitializer](http://www.baeldung.com/spring-boot-servlet-initializer) +- [How to Define a Spring Boot Filter?](http://www.baeldung.com/spring-boot-add-filter) - [How to Change the Default Port in Spring Boot](http://www.baeldung.com/spring-boot-change-port) - +- [Spring Boot Exit Codes](http://www.baeldung.com/spring-boot-exit-codes) +- [Guide to the Favicon in Spring Boot](http://www.baeldung.com/spring-boot-favicon) +- [Spring Shutdown Callbacks](http://www.baeldung.com/spring-shutdown-callbacks) +- [Spring Boot Integration Testing with Embedded MongoDB](http://www.baeldung.com/spring-boot-embedded-mongodb) +- [Container Configuration in Spring Boot 2](http://www.baeldung.com/embeddedservletcontainercustomizer-configurableembeddedservletcontainer-spring-boot) +- [Introduction to Chaos Monkey](https://www.baeldung.com/spring-boot-chaos-monkey) +- [Spring Component Scanning](https://www.baeldung.com/spring-component-scanning) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index afc80eb68b..50859f674c 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -1,5 +1,5 @@ + 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-boot @@ -16,6 +16,35 @@ + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + test + + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + org.junit.platform + junit-platform-launcher + ${junit-platform.version} + test + org.springframework.boot spring-boot-starter-thymeleaf @@ -36,17 +65,12 @@ com.graphql-java graphql-spring-boot-starter - 3.6.0 - - - com.graphql-java - graphiql-spring-boot-starter - 3.6.0 + ${graphql-spring-boot-starter.version} com.graphql-java graphql-java-tools - 3.2.0 + ${graphql-java-tools.version} @@ -60,11 +84,6 @@ test - - io.dropwizard.metrics metrics-core @@ -84,32 +103,11 @@ json-path test - - org.springframework.boot - spring-boot-starter-mail - - - org.subethamail - subethasmtp - ${subethasmtp.version} - test - - - - org.webjars - bootstrap - ${bootstrap.version} - - - org.webjars - jquery - ${jquery.version} - com.google.guava guava - 18.0 + ${guava.version} @@ -119,16 +117,6 @@ provided - - org.springframework - spring-websocket - - - - org.springframework - spring-messaging - - org.togglz togglz-spring-boot-starter @@ -151,6 +139,12 @@ rome ${rome.version} + + + de.codecentric + chaos-monkey-spring-boot + ${chaos.monkey.version} + @@ -172,6 +166,7 @@ pl.project13.maven git-commit-id-plugin + ${git-commit-id-plugin.version} @@ -196,6 +191,7 @@ **/*LiveTest.java **/*IntegrationTest.java + **/*IntTest.java **/AutoconfigurationTest.java @@ -214,16 +210,18 @@ - org.baeldung.demo.DemoApplication - 3.1.1 - 3.3.7-1 - 3.1.7 8.5.11 2.4.1.Final 1.9.0 + 2.0.0 + 3.6.0 + 3.2.0 + 18.0 + 1.2.0 + 2.2.4 \ No newline at end of file diff --git a/spring-boot/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java b/spring-boot/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java new file mode 100644 index 0000000000..aa794182de --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java @@ -0,0 +1,25 @@ +package com.baeldung.bootcustomfilters; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.bootcustomfilters.filters.RequestResponseLoggingFilter; + +@Configuration +public class FilterConfig { + + // uncomment this and comment the @Component in the filter class definition to register only for a url pattern + // @Bean + public FilterRegistrationBean loggingFilter() { + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + + registrationBean.setFilter(new RequestResponseLoggingFilter()); + + registrationBean.addUrlPatterns("/users/*"); + + return registrationBean; + + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/chaosmonkey/SpringBootChaosMonkeyApp.java b/spring-boot/src/main/java/com/baeldung/chaosmonkey/SpringBootChaosMonkeyApp.java new file mode 100644 index 0000000000..16a0aea13b --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/chaosmonkey/SpringBootChaosMonkeyApp.java @@ -0,0 +1,15 @@ +package com.baeldung.chaosmonkey; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * Created by adi on 8/2/18. + */ +@SpringBootApplication(scanBasePackages = { "com.baeldung.chaosmonkey" }) +public class SpringBootChaosMonkeyApp { + + public static void main(String[] args) { + SpringApplication.run(SpringBootChaosMonkeyApp.class, args); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/chaosmonkey/controller/PermissionsController.java b/spring-boot/src/main/java/com/baeldung/chaosmonkey/controller/PermissionsController.java new file mode 100644 index 0000000000..6ceb117f4e --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/chaosmonkey/controller/PermissionsController.java @@ -0,0 +1,25 @@ +package com.baeldung.chaosmonkey.controller; + +import com.baeldung.chaosmonkey.service.PermissionsService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + * Created by adi on 8/2/18. + */ +@RestController +@RequestMapping("/permissions") +public class PermissionsController { + + @Autowired private PermissionsService permissionsService; + + @GetMapping + public List getAllPermissions() { + return permissionsService.getAllPermissions(); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/chaosmonkey/service/PermissionsService.java b/spring-boot/src/main/java/com/baeldung/chaosmonkey/service/PermissionsService.java new file mode 100644 index 0000000000..435e262901 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/chaosmonkey/service/PermissionsService.java @@ -0,0 +1,17 @@ +package com.baeldung.chaosmonkey.service; + +import org.springframework.stereotype.Service; + +import java.util.Arrays; +import java.util.List; + +/** + * Created by adi on 8/2/18. + */ +@Service +public class PermissionsService { + + public List getAllPermissions() { + return Arrays.asList("CREATE", "READ", "UPDATE", "DELETE"); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/ExampleBean.java b/spring-boot/src/main/java/com/baeldung/componentscan/ExampleBean.java new file mode 100644 index 0000000000..9ddcf12d4e --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/componentscan/ExampleBean.java @@ -0,0 +1,5 @@ +package com.baeldung.componentscan; + +public class ExampleBean { + +} diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java new file mode 100644 index 0000000000..2377ed7a56 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java @@ -0,0 +1,38 @@ +package com.baeldung.componentscan.springapp; + +import org.springframework.context.annotation.FilterType; +import org.springframework.stereotype.Component; + +import com.baeldung.componentscan.ExampleBean; +import com.baeldung.componentscan.springapp.flowers.Rose; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan +//@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = Rose.class)) +//@ComponentScan(basePackages = "com.baeldung.componentscan.springapp") +//@ComponentScan(basePackages = "com.baeldung.componentscan.springapp.animals") +//@ComponentScan (excludeFilters = @ComponentScan.Filter(type=FilterType.REGEX,pattern="com\\.baeldung\\.componentscan\\.springapp\\.flowers\\..*")) +public class SpringComponentScanApp { + + private static ApplicationContext applicationContext; + + @Bean + public ExampleBean exampleBean() { + return new ExampleBean(); + } + + public static void main(String[] args) { + applicationContext = new AnnotationConfigApplicationContext(SpringComponentScanApp.class); + + for (String beanName : applicationContext.getBeanDefinitionNames()) { + System.out.println(beanName); + } + } + +} \ No newline at end of file diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java new file mode 100644 index 0000000000..5f5b482972 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java @@ -0,0 +1,8 @@ +package com.baeldung.componentscan.springapp.animals; + +import org.springframework.stereotype.Component; + +@Component +public class Cat { + +} diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java new file mode 100644 index 0000000000..009162b57f --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java @@ -0,0 +1,8 @@ +package com.baeldung.componentscan.springapp.animals; + +import org.springframework.stereotype.Component; + +@Component +public class Dog { + +} diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java new file mode 100644 index 0000000000..b777b073b9 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java @@ -0,0 +1,8 @@ +package com.baeldung.componentscan.springapp.flowers; + +import org.springframework.stereotype.Component; + +@Component +public class Rose { + +} diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java new file mode 100644 index 0000000000..ba29a4e1f5 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java @@ -0,0 +1,37 @@ +package com.baeldung.componentscan.springbootapp; + +import org.springframework.boot.SpringApplication; +import org.springframework.context.annotation.FilterType; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; + +import com.baeldung.componentscan.ExampleBean; +import com.baeldung.componentscan.springbootapp.flowers.Rose; + +@SpringBootApplication +//@ComponentScan(basePackages = "com.baeldung.componentscan.springbootapp.animals") +//@ComponentScan ( excludeFilters = @ComponentScan.Filter(type=FilterType.REGEX,pattern="com\\.baeldung\\.componentscan\\.springbootapp\\.flowers\\..*")) +//@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = Rose.class)) + +public class SpringBootComponentScanApp { + private static ApplicationContext applicationContext; + + @Bean + public ExampleBean exampleBean() { + return new ExampleBean(); + } + + public static void main(String[] args) { + applicationContext = SpringApplication.run(SpringBootComponentScanApp.class, args); + checkBeansPresence("cat", "dog", "rose", "exampleBean", "springBootApp"); + + } + + private static void checkBeansPresence(String... beans) { + for (String beanName : beans) { + System.out.println("Is " + beanName + " in ApplicationContext: " + applicationContext.containsBean(beanName)); + } + } +} diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java new file mode 100644 index 0000000000..7c43d6a24c --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java @@ -0,0 +1,8 @@ +package com.baeldung.componentscan.springbootapp.animals; + +import org.springframework.stereotype.Component; + +@Component +public class Cat { + +} diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java new file mode 100644 index 0000000000..145430cb54 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java @@ -0,0 +1,8 @@ +package com.baeldung.componentscan.springbootapp.animals; + +import org.springframework.stereotype.Component; + +@Component +public class Dog { + +} diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java new file mode 100644 index 0000000000..0ccf782685 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java @@ -0,0 +1,8 @@ +package com.baeldung.componentscan.springbootapp.flowers; + +import org.springframework.stereotype.Component; + +@Component +public class Rose { + +} diff --git a/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java b/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java index c4a83cc2d9..630820ff9f 100644 --- a/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java +++ b/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java @@ -3,6 +3,7 @@ package com.baeldung.displayallbeans.controller; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @@ -14,9 +15,9 @@ public class FooController { private FooService fooService; @GetMapping(value = "/displayallbeans") - public String getHeaderAndBody(Map model) { + public ResponseEntity getHeaderAndBody(Map model) { model.put("header", fooService.getHeader()); model.put("message", fooService.getBody()); - return "displayallbeans"; + return ResponseEntity.ok("displayallbeans"); } } diff --git a/spring-boot/src/main/java/com/baeldung/mongodb/Application.java b/spring-boot/src/main/java/com/baeldung/mongodb/Application.java new file mode 100644 index 0000000000..092ce3352b --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/mongodb/Application.java @@ -0,0 +1,11 @@ +package com.baeldung.mongodb; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/properties/ConfigProperties.java b/spring-boot/src/main/java/com/baeldung/properties/ConfigProperties.java new file mode 100644 index 0000000000..863510738b --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/ConfigProperties.java @@ -0,0 +1,117 @@ +package com.baeldung.properties; + +import java.util.List; +import java.util.Map; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.Pattern; + +import org.hibernate.validator.constraints.Length; +import org.hibernate.validator.constraints.NotBlank; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.validation.annotation.Validated; + +@Configuration +@PropertySource("classpath:configprops.properties") +@ConfigurationProperties(prefix = "mail") +@Validated +public class ConfigProperties { + + @Validated + public static class Credentials { + + @Length(max = 4, min = 1) + private String authMethod; + private String username; + private String password; + + public String getAuthMethod() { + return authMethod; + } + + public void setAuthMethod(String authMethod) { + this.authMethod = authMethod; + } + + 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; + } + } + + @NotBlank + private String host; + + @Min(1025) + @Max(65536) + private int port; + + @Pattern(regexp = "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,6}$") + private String from; + + private Credentials credentials; + private List defaultRecipients; + private Map additionalHeaders; + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public String getFrom() { + return from; + } + + public void setFrom(String from) { + this.from = from; + } + + public Credentials getCredentials() { + return credentials; + } + + public void setCredentials(Credentials credentials) { + this.credentials = credentials; + } + + public List getDefaultRecipients() { + return defaultRecipients; + } + + public void setDefaultRecipients(List defaultRecipients) { + this.defaultRecipients = defaultRecipients; + } + + public Map getAdditionalHeaders() { + return additionalHeaders; + } + + public void setAdditionalHeaders(Map additionalHeaders) { + this.additionalHeaders = additionalHeaders; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java b/spring-boot/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java new file mode 100644 index 0000000000..ee9671c755 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.properties; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class }) +public class ConfigPropertiesDemoApplication { + public static void main(String[] args) { + new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer()) + .run(); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/properties/CustomJsonProperties.java b/spring-boot/src/main/java/com/baeldung/properties/CustomJsonProperties.java new file mode 100644 index 0000000000..084138ec6f --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/CustomJsonProperties.java @@ -0,0 +1,71 @@ +package com.baeldung.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties(prefix = "custom") +public class CustomJsonProperties { + + private String host; + + private int port; + + private boolean resend; + + private Person sender; + + public static class Person { + + private String name; + private String address; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public boolean isResend() { + return resend; + } + + public void setResend(boolean resend) { + this.resend = resend; + } + + public Person getSender() { + return sender; + } + + public void setSender(Person sender) { + this.sender = sender; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/properties/JsonProperties.java b/spring-boot/src/main/java/com/baeldung/properties/JsonProperties.java new file mode 100644 index 0000000000..31b3be14b4 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/JsonProperties.java @@ -0,0 +1,64 @@ +package com.baeldung.properties; + +import java.util.LinkedHashMap; +import java.util.List; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; + +@Component +@PropertySource(value = "classpath:configprops.json", factory = JsonPropertySourceFactory.class) +@ConfigurationProperties +public class JsonProperties { + + private String host; + + private int port; + + private boolean resend; + + private List topics; + + private LinkedHashMap sender; + + public LinkedHashMap getSender() { + return sender; + } + + public void setSender(LinkedHashMap sender) { + this.sender = sender; + } + + public List getTopics() { + return topics; + } + + public void setTopics(List topics) { + this.topics = topics; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public boolean isResend() { + return resend; + } + + public void setResend(boolean resend) { + this.resend = resend; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/properties/JsonPropertyContextInitializer.java b/spring-boot/src/main/java/com/baeldung/properties/JsonPropertyContextInitializer.java new file mode 100644 index 0000000000..0aee149123 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/JsonPropertyContextInitializer.java @@ -0,0 +1,68 @@ +package com.baeldung.properties; + +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.Resource; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JsonPropertyContextInitializer implements ApplicationContextInitializer { + + private final static String CUSTOM_PREFIX = "custom."; + + @Override + @SuppressWarnings("unchecked") + public void initialize(ConfigurableApplicationContext configurableApplicationContext) { + try { + Resource resource = configurableApplicationContext.getResource("classpath:configprops.json"); + Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class); + Set set = readValue.entrySet(); + List propertySources = convertEntrySet(set, Optional.empty()); + for (PropertySource propertySource : propertySources) { + configurableApplicationContext.getEnvironment() + .getPropertySources() + .addFirst(propertySource); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private static List convertEntrySet(Set entrySet, Optional parentKey) { + return entrySet.stream() + .map((Map.Entry e) -> convertToPropertySourceList(e, parentKey)) + .flatMap(Collection::stream) + .collect(Collectors.toList()); + } + + private static List convertToPropertySourceList(Map.Entry e, Optional parentKey) { + String key = parentKey.map(s -> s + ".") + .orElse("") + (String) e.getKey(); + Object value = e.getValue(); + return covertToPropertySourceList(key, value); + } + + @SuppressWarnings("unchecked") + private static List covertToPropertySourceList(String key, Object value) { + if (value instanceof LinkedHashMap) { + LinkedHashMap map = (LinkedHashMap) value; + Set entrySet = map.entrySet(); + return convertEntrySet(entrySet, Optional.ofNullable(key)); + } + String finalKey = CUSTOM_PREFIX + key; + return Collections.singletonList(new MapPropertySource(finalKey, Collections.singletonMap(finalKey, value))); + } + +} \ No newline at end of file diff --git a/spring-boot/src/main/java/com/baeldung/properties/JsonPropertySourceFactory.java b/spring-boot/src/main/java/com/baeldung/properties/JsonPropertySourceFactory.java new file mode 100644 index 0000000000..c14d3faea5 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/JsonPropertySourceFactory.java @@ -0,0 +1,21 @@ +package com.baeldung.properties; + +import java.io.IOException; +import java.util.Map; + +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.support.EncodedResource; +import org.springframework.core.io.support.PropertySourceFactory; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JsonPropertySourceFactory implements PropertySourceFactory { + + @Override + public PropertySource createPropertySource(String name, EncodedResource resource) throws IOException { + Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class); + return new MapPropertySource("json-property", readValue); + } + +} \ No newline at end of file diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java new file mode 100644 index 0000000000..7cce34a06c --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.shutdownhooks; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@EnableAutoConfiguration +public class ShutdownHookApplication { + + public static void main(String args[]) { + SpringApplication.run(ShutdownHookApplication.class, args); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java new file mode 100644 index 0000000000..e85b9395d3 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java @@ -0,0 +1,14 @@ +package com.baeldung.shutdownhooks.beans; + +import javax.annotation.PreDestroy; + +import org.springframework.stereotype.Component; + +@Component +public class Bean1 { + + @PreDestroy + public void destroy() { + System.out.println("Shutdown triggered using @PreDestroy."); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java new file mode 100644 index 0000000000..e85d12e791 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java @@ -0,0 +1,14 @@ +package com.baeldung.shutdownhooks.beans; + +import org.springframework.beans.factory.DisposableBean; +import org.springframework.stereotype.Component; + +@Component +public class Bean2 implements DisposableBean { + + @Override + public void destroy() throws Exception { + System.out.println("Shutdown triggered using DisposableBean."); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java new file mode 100644 index 0000000000..bed1d50ee7 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java @@ -0,0 +1,8 @@ +package com.baeldung.shutdownhooks.beans; + +public class Bean3 { + + public void destroy() { + System.out.println("Shutdown triggered using bean destroy method."); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java new file mode 100644 index 0000000000..07d729cb83 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java @@ -0,0 +1,18 @@ +package com.baeldung.shutdownhooks.config; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +public class ExampleServletContextListener implements ServletContextListener { + + @Override + public void contextDestroyed(ServletContextEvent event) { + System.out.println("Shutdown triggered using ServletContextListener."); + } + + @Override + public void contextInitialized(ServletContextEvent event) { + // Triggers when context initializes + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java new file mode 100644 index 0000000000..2d0712e19b --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java @@ -0,0 +1,25 @@ +package com.baeldung.shutdownhooks.config; + +import javax.servlet.ServletContextListener; + +import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.shutdownhooks.beans.Bean3; + +@Configuration +public class ShutdownHookConfiguration { + + @Bean(destroyMethod = "destroy") + public Bean3 initializeBean3() { + return new Bean3(); + } + + @Bean + ServletListenerRegistrationBean servletListener() { + ServletListenerRegistrationBean srb = new ServletListenerRegistrationBean<>(); + srb.setListener(new ExampleServletContextListener()); + return srb; + } +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java b/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java index 6d8708b06a..9554facb12 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java +++ b/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java @@ -1,24 +1,15 @@ package org.baeldung.boot.config; -import org.baeldung.boot.converter.GenericBigDecimalConverter; import org.baeldung.boot.converter.StringToEmployeeConverter; import org.baeldung.boot.converter.StringToEnumConverterFactory; -import org.baeldung.boot.web.resolver.HeaderVersionArgumentResolver; +import org.baeldung.boot.converter.GenericBigDecimalConverter; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; -import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import java.util.List; - @Configuration public class WebConfig implements WebMvcConfigurer { - - @Override - public void addArgumentResolvers(final List argumentResolvers) { - argumentResolvers.add(new HeaderVersionArgumentResolver()); - } - + @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(new StringToEmployeeConverter()); @@ -26,3 +17,4 @@ public class WebConfig implements WebMvcConfigurer { registry.addConverter(new GenericBigDecimalConverter()); } } + diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java b/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java index f756a25f67..8add28fc2d 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java +++ b/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java @@ -3,32 +3,29 @@ package org.baeldung.boot.converter; import com.google.common.collect.ImmutableSet; import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.converter.GenericConverter; - import java.math.BigDecimal; import java.util.Set; - public class GenericBigDecimalConverter implements GenericConverter { - @Override - public Set getConvertibleTypes() { - - ConvertiblePair[] pairs = new ConvertiblePair[] { new ConvertiblePair(Number.class, BigDecimal.class), new ConvertiblePair(String.class, BigDecimal.class) }; - + @Override + public Set getConvertibleTypes () { + ConvertiblePair[] pairs = new ConvertiblePair[] { + new ConvertiblePair(Number.class, BigDecimal.class), + new ConvertiblePair(String.class, BigDecimal.class)}; return ImmutableSet.copyOf(pairs); - } - + } @Override - public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { - if (sourceType.getType() == BigDecimal.class) { - return source; - } - - if (sourceType.getType() == String.class) { - String number = (String) source; - return new BigDecimal(number); - } else { - Number number = (Number) source; - BigDecimal converted = new BigDecimal(number.doubleValue()); - return converted.setScale(2, BigDecimal.ROUND_HALF_EVEN); - } - } + public Object convert (Object source, TypeDescriptor sourceType, + TypeDescriptor targetType) { + if (sourceType.getType() == BigDecimal.class) { + return source; + } + if(sourceType.getType() == String.class) { + String number = (String) source; + return new BigDecimal(number); + } else { + Number number = (Number) source; + BigDecimal converted = new BigDecimal(number.doubleValue()); + return converted.setScale(2, BigDecimal.ROUND_HALF_EVEN); + } + } } \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java b/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java index b07e11e01a..1bf75b38f0 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java +++ b/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java @@ -1,13 +1,14 @@ package org.baeldung.boot.converter; -import com.baeldung.toggle.Employee; import org.springframework.core.convert.converter.Converter; +import com.baeldung.toggle.Employee; + public class StringToEmployeeConverter implements Converter { - @Override - public Employee convert(String from) { - String[] data = from.split(","); - return new Employee(Long.parseLong(data[0]), Double.parseDouble(data[1])); - } -} \ No newline at end of file + @Override + public Employee convert(String from) { + String[] data = from.split(","); + return new Employee(Long.parseLong(data[0]), Double.parseDouble(data[1])); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java b/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java index 6fa51bfdcc..ddb2cd2b08 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java +++ b/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java @@ -5,23 +5,26 @@ import org.springframework.core.convert.converter.ConverterFactory; import org.springframework.stereotype.Component; @Component -public class StringToEnumConverterFactory implements ConverterFactory { - - private static class StringToEnumConverter implements Converter { - +public class StringToEnumConverterFactory + implements ConverterFactory { + + private static class StringToEnumConverter + implements Converter { + private Class enumType; - + public StringToEnumConverter(Class enumType) { this.enumType = enumType; } - + public T convert(String source) { return (T) Enum.valueOf(this.enumType, source.trim()); } } - + @Override - public Converter getConverter(final Class targetType) { + public Converter getConverter( + Class targetType) { return new StringToEnumConverter(targetType); } -} +} \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java b/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java index a6e0400845..27bad4c387 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java +++ b/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java @@ -1,14 +1,16 @@ package org.baeldung.boot.converter.controller; -import com.baeldung.toggle.Employee; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.toggle.Employee; @RestController -@RequestMapping("/string-to-employee") public class StringToEmployeeConverterController { - - @GetMapping + + @GetMapping("/string-to-employee") public ResponseEntity getStringToEmployee(@RequestParam("employee") Employee employee) { return ResponseEntity.ok(employee); } diff --git a/spring-boot/src/main/java/org/baeldung/common/error/MyCustomErrorController.java b/spring-boot/src/main/java/org/baeldung/common/error/MyCustomErrorController.java index e4e20de671..6b342a1bfb 100644 --- a/spring-boot/src/main/java/org/baeldung/common/error/MyCustomErrorController.java +++ b/spring-boot/src/main/java/org/baeldung/common/error/MyCustomErrorController.java @@ -13,7 +13,7 @@ public class MyCustomErrorController implements ErrorController { @GetMapping(value = PATH) public String error() { - return "Error heaven"; + return "Error haven"; } @Override diff --git a/spring-boot/src/main/java/org/baeldung/common/error/controller/ErrorController.java b/spring-boot/src/main/java/org/baeldung/common/error/controller/ErrorController.java index d503f5da6d..3e26f8c9d8 100644 --- a/spring-boot/src/main/java/org/baeldung/common/error/controller/ErrorController.java +++ b/spring-boot/src/main/java/org/baeldung/common/error/controller/ErrorController.java @@ -14,9 +14,9 @@ public class ErrorController { return "Error Code: 400 occured."; } - @GetMapping("/errorHeaven") + @GetMapping("/errorHaven") String errorHeaven() { - return "You have reached the heaven of errors!!!"; + return "You have reached the haven of errors!!!"; } } diff --git a/spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java b/spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java index 2d955bac9b..f6ab017298 100644 --- a/spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java +++ b/spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java @@ -19,7 +19,7 @@ public class MyServletContainerCustomizationBean implements WebServerFactoryCust container.setContextPath("/springbootapp"); container.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400")); - container.addErrorPages(new ErrorPage("/errorHeaven")); + container.addErrorPages(new ErrorPage("/errorHaven")); } } diff --git a/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java b/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java index cb0304fc41..395d68060b 100644 --- a/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java +++ b/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java @@ -1,13 +1,15 @@ package org.baeldung.properties; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.ComponentScan; -@EnableAutoConfiguration -@ComponentScan(basePackageClasses = ConfigProperties.class) +@SpringBootApplication +@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class }) public class ConfigPropertiesDemoApplication { public static void main(String[] args) { - SpringApplication.run(ConfigPropertiesDemoApplication.class); + new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer()) + .run(); } + } diff --git a/spring-boot/src/main/java/org/baeldung/properties/CustomJsonProperties.java b/spring-boot/src/main/java/org/baeldung/properties/CustomJsonProperties.java new file mode 100644 index 0000000000..3fae8a8e98 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/properties/CustomJsonProperties.java @@ -0,0 +1,71 @@ +package org.baeldung.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties(prefix = "custom") +public class CustomJsonProperties { + + private String host; + + private int port; + + private boolean resend; + + private Person sender; + + public static class Person { + + private String name; + private String address; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public boolean isResend() { + return resend; + } + + public void setResend(boolean resend) { + this.resend = resend; + } + + public Person getSender() { + return sender; + } + + public void setSender(Person sender) { + this.sender = sender; + } +} diff --git a/spring-boot/src/main/java/org/baeldung/properties/JsonProperties.java b/spring-boot/src/main/java/org/baeldung/properties/JsonProperties.java new file mode 100644 index 0000000000..5c31cd1344 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/properties/JsonProperties.java @@ -0,0 +1,64 @@ +package org.baeldung.properties; + +import java.util.LinkedHashMap; +import java.util.List; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; + +@Component +@PropertySource(value = "classpath:configprops.json", factory = JsonPropertySourceFactory.class) +@ConfigurationProperties +public class JsonProperties { + + private String host; + + private int port; + + private boolean resend; + + private List topics; + + private LinkedHashMap sender; + + public LinkedHashMap getSender() { + return sender; + } + + public void setSender(LinkedHashMap sender) { + this.sender = sender; + } + + public List getTopics() { + return topics; + } + + public void setTopics(List topics) { + this.topics = topics; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public boolean isResend() { + return resend; + } + + public void setResend(boolean resend) { + this.resend = resend; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } +} diff --git a/spring-boot/src/main/java/org/baeldung/properties/JsonPropertyContextInitializer.java b/spring-boot/src/main/java/org/baeldung/properties/JsonPropertyContextInitializer.java new file mode 100644 index 0000000000..fd9b3f35a5 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/properties/JsonPropertyContextInitializer.java @@ -0,0 +1,68 @@ +package org.baeldung.properties; + +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.Resource; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JsonPropertyContextInitializer implements ApplicationContextInitializer { + + private final static String CUSTOM_PREFIX = "custom."; + + @Override + @SuppressWarnings("unchecked") + public void initialize(ConfigurableApplicationContext configurableApplicationContext) { + try { + Resource resource = configurableApplicationContext.getResource("classpath:configprops.json"); + Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class); + Set set = readValue.entrySet(); + List propertySources = convertEntrySet(set, Optional.empty()); + for (PropertySource propertySource : propertySources) { + configurableApplicationContext.getEnvironment() + .getPropertySources() + .addFirst(propertySource); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private static List convertEntrySet(Set entrySet, Optional parentKey) { + return entrySet.stream() + .map((Map.Entry e) -> convertToPropertySourceList(e, parentKey)) + .flatMap(Collection::stream) + .collect(Collectors.toList()); + } + + private static List convertToPropertySourceList(Map.Entry e, Optional parentKey) { + String key = parentKey.map(s -> s + ".") + .orElse("") + (String) e.getKey(); + Object value = e.getValue(); + return covertToPropertySourceList(key, value); + } + + @SuppressWarnings("unchecked") + private static List covertToPropertySourceList(String key, Object value) { + if (value instanceof LinkedHashMap) { + LinkedHashMap map = (LinkedHashMap) value; + Set entrySet = map.entrySet(); + return convertEntrySet(entrySet, Optional.ofNullable(key)); + } + String finalKey = CUSTOM_PREFIX + key; + return Collections.singletonList(new MapPropertySource(finalKey, Collections.singletonMap(finalKey, value))); + } + +} \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/properties/JsonPropertySourceFactory.java b/spring-boot/src/main/java/org/baeldung/properties/JsonPropertySourceFactory.java new file mode 100644 index 0000000000..9578179519 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/properties/JsonPropertySourceFactory.java @@ -0,0 +1,21 @@ +package org.baeldung.properties; + +import java.io.IOException; +import java.util.Map; + +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.support.EncodedResource; +import org.springframework.core.io.support.PropertySourceFactory; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JsonPropertySourceFactory implements PropertySourceFactory { + + @Override + public PropertySource createPropertySource(String name, EncodedResource resource) throws IOException { + Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class); + return new MapPropertySource("json-property", readValue); + } + +} \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java index cba504b6c6..7335af2616 100644 --- a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java +++ b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java @@ -24,8 +24,6 @@ public interface UserRepository extends JpaRepository { Optional findOneByName(String name); - Stream findAllByName(String name); - @Async CompletableFuture findOneByStatus(Integer status); diff --git a/spring-boot/src/main/resources/application.properties b/spring-boot/src/main/resources/application.properties index 8c02e528ab..629e880940 100644 --- a/spring-boot/src/main/resources/application.properties +++ b/spring-boot/src/main/resources/application.properties @@ -43,3 +43,34 @@ servlet.mapping=/dispatcherExampleURL #spring.banner.image.invert= //TODO contactInfoType=email + +#chaos monkey for spring boot props +management.endpoint.chaosmonkey.enabled=true +management.endpoint.chaosmonkeyjmx.enabled=true + +spring.profiles.active=chaos-monkey +#Determine whether should execute or not +chaos.monkey.enabled=true +#How many requests are to be attacked. 1: attack each request; 5: each 5th request is attacked +chaos.monkey.assaults.level=1 +#Minimum latency in ms added to the request +chaos.monkey.assaults.latencyRangeStart=3000 +#Maximum latency in ms added to the request +chaos.monkey.assaults.latencyRangeEnd=15000 +#Latency assault active +chaos.monkey.assaults.latencyActive=true +#Exception assault active +chaos.monkey.assaults.exceptionsActive=false +#AppKiller assault active +chaos.monkey.assaults.killApplicationActive=false +#Controller watcher active +chaos.monkey.watcher.controller=false +#RestController watcher active +chaos.monkey.watcher.restController=false +#Service watcher active +chaos.monkey.watcher.service=true +#Repository watcher active +chaos.monkey.watcher.repository=false +#Component watcher active +chaos.monkey.watcher.component=false + diff --git a/spring-boot/src/main/resources/configprops.json b/spring-boot/src/main/resources/configprops.json new file mode 100644 index 0000000000..1602663775 --- /dev/null +++ b/spring-boot/src/main/resources/configprops.json @@ -0,0 +1,10 @@ +{ + "host" : "mailer@mail.com", + "port" : 9090, + "resend" : true, + "topics" : ["spring", "boot"], + "sender" : { + "name": "sender", + "address": "street" + } +} diff --git a/spring-boot/src/main/resources/logback.xml b/spring-boot/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-boot/src/main/resources/logback.xml +++ b/spring-boot/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-boot/src/main/resources/templates/customer.html b/spring-boot/src/main/resources/templates/customer.html deleted file mode 100644 index c8f5a25d5e..0000000000 --- a/spring-boot/src/main/resources/templates/customer.html +++ /dev/null @@ -1,16 +0,0 @@ - - - -Customer Page - - - -
    -
    -Contact Info:
    - -
    -

    -
    - - \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/customers.html b/spring-boot/src/main/resources/templates/customers.html deleted file mode 100644 index 5a060d31da..0000000000 --- a/spring-boot/src/main/resources/templates/customers.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - -
    -

    - Hello, --name--. -

    - - - - - - - - - - - - - - - - - -
    IDNameAddressService Rendered
    Text ...Text ...Text ...Text...
    - -
    - - - diff --git a/spring-boot/src/main/resources/templates/displayallbeans.html b/spring-boot/src/main/resources/templates/displayallbeans.html deleted file mode 100644 index 5fc78a7fca..0000000000 --- a/spring-boot/src/main/resources/templates/displayallbeans.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - Baeldung - - -

    -

    - - diff --git a/spring-boot/src/main/resources/templates/error-404.html b/spring-boot/src/main/resources/templates/error-404.html deleted file mode 100644 index cf68032596..0000000000 --- a/spring-boot/src/main/resources/templates/error-404.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - -
    -
    -

    Sorry, we couldn't find the page you were looking for.

    -

    Go Home

    -
    - - \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/error-500.html b/spring-boot/src/main/resources/templates/error-500.html deleted file mode 100644 index 5ddf458229..0000000000 --- a/spring-boot/src/main/resources/templates/error-500.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - -
    -
    -

    Sorry, something went wrong!

    - -

    We're fixing it.

    -

    Go Home

    -
    - - \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/error.html b/spring-boot/src/main/resources/templates/error.html deleted file mode 100644 index bc517913b2..0000000000 --- a/spring-boot/src/main/resources/templates/error.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - -
    -
    -

    Something went wrong!

    - -

    Our Engineers are on it.

    -

    Go Home

    -
    - - diff --git a/spring-boot/src/main/resources/templates/error/404.html b/spring-boot/src/main/resources/templates/error/404.html deleted file mode 100644 index df83ce219b..0000000000 --- a/spring-boot/src/main/resources/templates/error/404.html +++ /dev/null @@ -1,8 +0,0 @@ - - - RESOURCE NOT FOUND - - -

    404 RESOURCE NOT FOUND

    - - \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/external.html b/spring-boot/src/main/resources/templates/external.html deleted file mode 100644 index 2f9cc76961..0000000000 --- a/spring-boot/src/main/resources/templates/external.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - -
    -
    -

    Customer Portal

    -
    -
    -

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

    - -

    Existing Customers

    -
    - Enter the intranet: customers -
    -
    - -
    - - - - diff --git a/spring-boot/src/main/resources/templates/international.html b/spring-boot/src/main/resources/templates/international.html deleted file mode 100644 index e0cfb5143b..0000000000 --- a/spring-boot/src/main/resources/templates/international.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - -Home - - - - -

    - -

    -: - - - \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/layout.html b/spring-boot/src/main/resources/templates/layout.html deleted file mode 100644 index bab0c2982b..0000000000 --- a/spring-boot/src/main/resources/templates/layout.html +++ /dev/null @@ -1,18 +0,0 @@ - - - -Customer Portal - - - - - \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/other.html b/spring-boot/src/main/resources/templates/other.html deleted file mode 100644 index d13373f9fe..0000000000 --- a/spring-boot/src/main/resources/templates/other.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - -Spring Utils Demo - - - - Parameter set by you:

    - - \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/utils.html b/spring-boot/src/main/resources/templates/utils.html deleted file mode 100644 index 93030f424f..0000000000 --- a/spring-boot/src/main/resources/templates/utils.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - -Spring Utils Demo - - - -

    -

    Set Parameter:

    -

    - - -

    -
    -Another Page - - \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/mongodb/ManualEmbeddedMongoDbIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/mongodb/ManualEmbeddedMongoDbIntegrationTest.java new file mode 100644 index 0000000000..30a4d61fbd --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/mongodb/ManualEmbeddedMongoDbIntegrationTest.java @@ -0,0 +1,62 @@ +package com.baeldung.mongodb; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.data.mongodb.core.MongoTemplate; + +import com.mongodb.BasicDBObjectBuilder; +import com.mongodb.DBObject; +import com.mongodb.MongoClient; + +import de.flapdoodle.embed.mongo.MongodExecutable; +import de.flapdoodle.embed.mongo.MongodStarter; +import de.flapdoodle.embed.mongo.config.IMongodConfig; +import de.flapdoodle.embed.mongo.config.MongodConfigBuilder; +import de.flapdoodle.embed.mongo.config.Net; +import de.flapdoodle.embed.mongo.distribution.Version; +import de.flapdoodle.embed.process.runtime.Network; + +class ManualEmbeddedMongoDbIntegrationTest { + private MongodExecutable mongodExecutable; + private MongoTemplate mongoTemplate; + + @AfterEach + void clean() { + mongodExecutable.stop(); + } + + @BeforeEach + void setup() throws Exception { + String ip = "localhost"; + int port = 27017; + + IMongodConfig mongodConfig = new MongodConfigBuilder().version(Version.Main.PRODUCTION) + .net(new Net(ip, port, Network.localhostIsIPv6())) + .build(); + + MongodStarter starter = MongodStarter.getDefaultInstance(); + mongodExecutable = starter.prepare(mongodConfig); + mongodExecutable.start(); + mongoTemplate = new MongoTemplate(new MongoClient(ip, port), "test"); + } + + @DisplayName("Given object When save object using MongoDB template Then object can be found") + @Test + void test() throws Exception { + // given + DBObject objectToSave = BasicDBObjectBuilder.start() + .add("key", "value") + .get(); + + // when + mongoTemplate.save(objectToSave, "collection"); + + // then + assertThat(mongoTemplate.findAll(DBObject.class, "collection")).extracting("key") + .containsOnly("value"); + } +} diff --git a/spring-boot/src/test/java/com/baeldung/mongodb/MongoDbSpringIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/mongodb/MongoDbSpringIntegrationTest.java new file mode 100644 index 0000000000..5431217c3e --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/mongodb/MongoDbSpringIntegrationTest.java @@ -0,0 +1,36 @@ +package com.baeldung.mongodb; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.mongodb.BasicDBObjectBuilder; +import com.mongodb.DBObject; + +@ContextConfiguration(classes = Application.class) +@DataMongoTest +@ExtendWith(SpringExtension.class) +public class MongoDbSpringIntegrationTest { + @DisplayName("Given object When save object using MongoDB template Then object can be found") + @Test + public void test(@Autowired MongoTemplate mongoTemplate) { + // given + DBObject objectToSave = BasicDBObjectBuilder.start() + .add("key", "value") + .get(); + + // when + mongoTemplate.save(objectToSave, "collection"); + + // then + assertThat(mongoTemplate.findAll(DBObject.class, "collection")).extracting("key") + .containsOnly("value"); + } +} diff --git a/spring-boot/src/test/java/com/baeldung/properties/ConfigPropertiesIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/properties/ConfigPropertiesIntegrationTest.java new file mode 100644 index 0000000000..3a4b6551b1 --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/properties/ConfigPropertiesIntegrationTest.java @@ -0,0 +1,45 @@ +package com.baeldung.properties; + +import org.baeldung.properties.ConfigProperties; +import org.baeldung.properties.ConfigPropertiesDemoApplication; +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.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ConfigPropertiesDemoApplication.class) +@TestPropertySource("classpath:configprops-test.properties") +public class ConfigPropertiesIntegrationTest { + + @Autowired + private ConfigProperties properties; + + @Test + public void whenSimplePropertyQueriedthenReturnsProperty() throws Exception { + Assert.assertTrue("From address is read as null!", properties.getFrom() != null); + } + + @Test + public void whenListPropertyQueriedthenReturnsProperty() throws Exception { + Assert.assertTrue("Couldn't bind list property!", properties.getDefaultRecipients().size() == 2); + Assert.assertTrue("Incorrectly bound list property. Expected 2 entries!", properties.getDefaultRecipients().size() == 2); + } + + @Test + public void whenMapPropertyQueriedthenReturnsProperty() throws Exception { + Assert.assertTrue("Couldn't bind map property!", properties.getAdditionalHeaders() != null); + Assert.assertTrue("Incorrectly bound map property. Expected 3 Entries!", properties.getAdditionalHeaders().size() == 3); + } + + @Test + public void whenObjectPropertyQueriedthenReturnsProperty() throws Exception { + Assert.assertTrue("Couldn't bind map property!", properties.getCredentials() != null); + Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getAuthMethod().equals("SHA1")); + Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getUsername().equals("john")); + Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getPassword().equals("password")); + } +} diff --git a/spring-boot/src/test/java/com/baeldung/properties/JsonPropertiesIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/properties/JsonPropertiesIntegrationTest.java new file mode 100644 index 0000000000..48c551d1dd --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/properties/JsonPropertiesIntegrationTest.java @@ -0,0 +1,63 @@ +package com.baeldung.properties; + +import java.util.Arrays; + +import org.baeldung.properties.ConfigPropertiesDemoApplication; +import org.baeldung.properties.CustomJsonProperties; +import org.baeldung.properties.JsonProperties; +import org.baeldung.properties.JsonPropertyContextInitializer; +import org.hamcrest.Matchers; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = ConfigPropertiesDemoApplication.class, initializers = JsonPropertyContextInitializer.class) +public class JsonPropertiesIntegrationTest { + + @Autowired + private JsonProperties jsonProperties; + + @Autowired + private CustomJsonProperties customJsonProperties; + + @Test + public void whenPropertiesLoadedViaJsonPropertySource_thenLoadFlatValues() { + Assert.assertEquals("mailer@mail.com", jsonProperties.getHost()); + Assert.assertEquals(9090, jsonProperties.getPort()); + Assert.assertTrue(jsonProperties.isResend()); + } + + @Test + public void whenPropertiesLoadedViaJsonPropertySource_thenLoadListValues() { + Assert.assertThat(jsonProperties.getTopics(), Matchers.is(Arrays.asList("spring", "boot"))); + } + + @Test + public void whenPropertiesLoadedViaJsonPropertySource_thenNestedLoadedAsMap() { + Assert.assertEquals("sender", jsonProperties.getSender() + .get("name")); + Assert.assertEquals("street", jsonProperties.getSender() + .get("address")); + } + + @Test + public void whenLoadedIntoEnvironment_thenFlatValuesPopulated() { + Assert.assertEquals("mailer@mail.com", customJsonProperties.getHost()); + Assert.assertEquals(9090, customJsonProperties.getPort()); + Assert.assertTrue(customJsonProperties.isResend()); + } + + @Test + public void whenLoadedIntoEnvironment_thenValuesLoadedIntoClassObject() { + Assert.assertNotNull(customJsonProperties.getSender()); + Assert.assertEquals("sender", customJsonProperties.getSender() + .getName()); + Assert.assertEquals("street", customJsonProperties.getSender() + .getAddress()); + } + +} diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java index 4658861162..baa4f70e83 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java @@ -4,17 +4,15 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; -import org.baeldung.boot.ApplicationIntegrationTest; +import org.baeldung.boot.DemoApplicationIntegrationTest; import org.baeldung.demo.model.Foo; -import org.baeldung.session.exception.repository.FooRepository; +import org.baeldung.demo.repository.FooRepository; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.TestPropertySource; import org.springframework.transaction.annotation.Transactional; @Transactional -@TestPropertySource("classpath:exception-hibernate.properties") -public class HibernateSessionIntegrationTest extends ApplicationIntegrationTest { +public class HibernateSessionIntegrationTest extends DemoApplicationIntegrationTest { @Autowired private FooRepository fooRepository; @@ -23,7 +21,7 @@ public class HibernateSessionIntegrationTest extends ApplicationIntegrationTest Foo foo = new Foo("Exception Solved"); fooRepository.save(foo); foo = null; - foo = fooRepository.get(1); + foo = fooRepository.findByName("Exception Solved"); assertThat(foo, notNullValue()); assertThat(foo.getId(), is(1)); diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java index 8de7068949..5c8d10223b 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java @@ -6,9 +6,11 @@ import org.baeldung.session.exception.repository.FooRepository; import org.hibernate.HibernateException; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.TestPropertySource; import org.springframework.transaction.annotation.Transactional; @Transactional +@TestPropertySource("classpath:exception-hibernate.properties") public class NoHibernateSessionIntegrationTest extends ApplicationIntegrationTest { @Autowired private FooRepository fooRepository; diff --git a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java index 4eec62db13..df28111a57 100644 --- a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java @@ -1,9 +1,11 @@ package org.baeldung.demo.boottest; -import org.baeldung.demo.boottest.Employee; -import org.baeldung.demo.boottest.EmployeeRepository; -import org.baeldung.demo.boottest.EmployeeService; -import org.baeldung.demo.boottest.EmployeeServiceImpl; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -15,11 +17,6 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit4.SpringRunner; -import java.util.Arrays; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - @RunWith(SpringRunner.class) public class EmployeeServiceImplIntegrationTest { @@ -50,9 +47,9 @@ public class EmployeeServiceImplIntegrationTest { Mockito.when(employeeRepository.findByName(john.getName())).thenReturn(john); Mockito.when(employeeRepository.findByName(alex.getName())).thenReturn(alex); Mockito.when(employeeRepository.findByName("wrong_name")).thenReturn(null); - Mockito.when(employeeRepository.findById(john.getId()).orElse(null)).thenReturn(john); + Mockito.when(employeeRepository.findById(john.getId())).thenReturn(Optional.of(john)); Mockito.when(employeeRepository.findAll()).thenReturn(allEmployees); - Mockito.when(employeeRepository.findById(-99L).orElse(null)).thenReturn(null); + Mockito.when(employeeRepository.findById(-99L)).thenReturn(Optional.empty()); } @Test diff --git a/spring-boot/src/test/java/org/baeldung/properties/JsonPropertiesIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/properties/JsonPropertiesIntegrationTest.java new file mode 100644 index 0000000000..e3d4c62953 --- /dev/null +++ b/spring-boot/src/test/java/org/baeldung/properties/JsonPropertiesIntegrationTest.java @@ -0,0 +1,59 @@ +package org.baeldung.properties; + +import java.util.Arrays; + +import org.hamcrest.Matchers; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = ConfigPropertiesDemoApplication.class, initializers = JsonPropertyContextInitializer.class) +public class JsonPropertiesIntegrationTest { + + @Autowired + private JsonProperties jsonProperties; + + @Autowired + private CustomJsonProperties customJsonProperties; + + @Test + public void whenPropertiesLoadedViaJsonPropertySource_thenLoadFlatValues() { + Assert.assertEquals("mailer@mail.com", jsonProperties.getHost()); + Assert.assertEquals(9090, jsonProperties.getPort()); + Assert.assertTrue(jsonProperties.isResend()); + } + + @Test + public void whenPropertiesLoadedViaJsonPropertySource_thenLoadListValues() { + Assert.assertThat(jsonProperties.getTopics(), Matchers.is(Arrays.asList("spring", "boot"))); + } + + @Test + public void whenPropertiesLoadedViaJsonPropertySource_thenNestedLoadedAsMap() { + Assert.assertEquals("sender", jsonProperties.getSender() + .get("name")); + Assert.assertEquals("street", jsonProperties.getSender() + .get("address")); + } + + @Test + public void whenLoadedIntoEnvironment_thenFlatValuesPopulated() { + Assert.assertEquals("mailer@mail.com", customJsonProperties.getHost()); + Assert.assertEquals(9090, customJsonProperties.getPort()); + Assert.assertTrue(customJsonProperties.isResend()); + } + + @Test + public void whenLoadedIntoEnvironment_thenValuesLoadedIntoClassObject() { + Assert.assertNotNull(customJsonProperties.getSender()); + Assert.assertEquals("sender", customJsonProperties.getSender() + .getName()); + Assert.assertEquals("street", customJsonProperties.getSender() + .getAddress()); + } + +} diff --git a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java index 72d204820e..04bb1170f8 100644 --- a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java @@ -52,30 +52,6 @@ public class UserRepositoryIntegrationTest { .getName()).isEqualTo(USER_NAME_ADAM); } - @Test - @Transactional - public void givenUsersWithSameNameInDBWhenFindAllByNameThenReturnStreamOfUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - userRepository.save(user3); - - User user4 = new User(); - user4.setName("SAMPLE"); - userRepository.save(user4); - - try (Stream foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) { - assertThat(foundUsersStream.count()).isEqualTo(3l); - } - } - @Test public void givenUserInDBWhenFindOneByStatusAsyncThenReturnCompletableFutureUser() throws ExecutionException, InterruptedException { User user = new User(); diff --git a/spring-cloud-bus/spring-cloud-config-client/pom.xml b/spring-cloud-bus/spring-cloud-config-client/pom.xml index 61660b6d8f..bd9fb45587 100644 --- a/spring-cloud-bus/spring-cloud-config-client/pom.xml +++ b/spring-cloud-bus/spring-cloud-config-client/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.spring.cloud @@ -12,47 +12,36 @@ Demo Spring Cloud Config Client - org.springframework.boot - spring-boot-starter-parent - 1.5.4.RELEASE + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-1 - - UTF-8 - UTF-8 - 1.8 - Dalston.SR1 - - org.springframework.cloud spring-cloud-starter-config - 1.3.1.RELEASE org.springframework.boot spring-boot-starter-web - 1.5.4.RELEASE org.springframework.boot spring-boot-starter-test - 1.5.4.RELEASE test org.springframework.boot spring-boot-actuator - 1.5.4.RELEASE org.springframework.cloud spring-cloud-starter-bus-amqp - 1.3.1.RELEASE @@ -73,9 +62,15 @@ org.springframework.boot spring-boot-maven-plugin - 1.5.4.RELEASE + + UTF-8 + UTF-8 + 1.8 + Dalston.SR1 + + diff --git a/spring-cloud-bus/spring-cloud-config-client/src/main/resources/logback.xml b/spring-cloud-bus/spring-cloud-config-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud-bus/spring-cloud-config-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud-bus/spring-cloud-config-client/src/test/java/com/baeldung/SpringCloudConfigClientApplicationTests.java b/spring-cloud-bus/spring-cloud-config-client/src/test/java/com/baeldung/SpringCloudConfigClientApplicationTests.java deleted file mode 100644 index 3b361f385a..0000000000 --- a/spring-cloud-bus/spring-cloud-config-client/src/test/java/com/baeldung/SpringCloudConfigClientApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class SpringCloudConfigClientApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud-bus/spring-cloud-config-client/src/test/java/com/baeldung/SpringCloudConfigClientLiveTest.java b/spring-cloud-bus/spring-cloud-config-client/src/test/java/com/baeldung/SpringCloudConfigClientLiveTest.java new file mode 100644 index 0000000000..364368713a --- /dev/null +++ b/spring-cloud-bus/spring-cloud-config-client/src/test/java/com/baeldung/SpringCloudConfigClientLiveTest.java @@ -0,0 +1,16 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringCloudConfigClientLiveTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-bus/spring-cloud-config-server/pom.xml b/spring-cloud-bus/spring-cloud-config-server/pom.xml index 2fb6afb5a0..194289ea1e 100644 --- a/spring-cloud-bus/spring-cloud-config-server/pom.xml +++ b/spring-cloud-bus/spring-cloud-config-server/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.spring.cloud @@ -12,48 +12,37 @@ Demo Spring Cloud Config Server - org.springframework.boot - spring-boot-starter-parent - 1.5.4.RELEASE + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-1 - - UTF-8 - UTF-8 - 1.8 - Dalston.SR1 - - org.springframework.cloud spring-cloud-config-server - 1.3.1.RELEASE org.springframework.boot spring-boot-starter-security - 1.5.4.RELEASE org.springframework.boot spring-boot-starter-test - 1.5.4.RELEASE test org.springframework.cloud spring-cloud-config-monitor - 1.3.1.RELEASE org.springframework.cloud spring-cloud-starter-stream-rabbit - 1.2.1.RELEASE @@ -74,9 +63,15 @@ org.springframework.boot spring-boot-maven-plugin - 1.5.4.RELEASE + + UTF-8 + UTF-8 + 1.8 + Dalston.SR1 + + diff --git a/spring-cloud-bus/spring-cloud-config-server/src/main/resources/logback.xml b/spring-cloud-bus/spring-cloud-config-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud-bus/spring-cloud-config-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud-data-flow/batch-job/pom.xml b/spring-cloud-data-flow/batch-job/pom.xml index 123c4aeda6..7bc2909f4c 100644 --- a/spring-cloud-data-flow/batch-job/pom.xml +++ b/spring-cloud-data-flow/batch-job/pom.xml @@ -1,27 +1,21 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - org.baeldung.spring.cloud batch-job 0.0.1-SNAPSHOT jar - batch-job Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 - - 1.0.3.RELEASE - - org.springframework.cloud @@ -53,4 +47,8 @@ + + 1.0.3.RELEASE + + diff --git a/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/BatchJobApplication.java b/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/BatchJobApplication.java index f717f0f644..30f6ff6897 100644 --- a/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/BatchJobApplication.java +++ b/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/BatchJobApplication.java @@ -1,12 +1,10 @@ package org.baeldung.spring.cloud; -import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.task.configuration.EnableTask; @EnableTask -@EnableBatchProcessing @SpringBootApplication public class BatchJobApplication { diff --git a/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/JobConfiguration.java b/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/JobConfiguration.java index dc6a5e2827..7ce867b60a 100644 --- a/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/JobConfiguration.java +++ b/spring-cloud-data-flow/batch-job/src/main/java/org/baeldung/spring/cloud/JobConfiguration.java @@ -2,9 +2,9 @@ package org.baeldung.spring.cloud; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import org.springframework.batch.core.Job; import org.springframework.batch.core.StepContribution; +import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.core.scope.context.ChunkContext; @@ -15,6 +15,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration +@EnableBatchProcessing public class JobConfiguration { private static final Log logger = LogFactory.getLog(JobConfiguration.class); diff --git a/spring-cloud-data-flow/batch-job/src/main/resources/logback.xml b/spring-cloud-data-flow/batch-job/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud-data-flow/batch-job/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationIntegrationTest.java b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationIntegrationTest.java index f8dfdec197..1f77351acc 100644 --- a/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationIntegrationTest.java +++ b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationIntegrationTest.java @@ -3,10 +3,12 @@ package org.baeldung.spring.cloud; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest +@ContextConfiguration(classes = JobConfiguration.class) public class BatchJobApplicationIntegrationTest { @Test diff --git a/spring-cloud-data-flow/data-flow-server/pom.xml b/spring-cloud-data-flow/data-flow-server/pom.xml index f0d513ce4d..0133d65978 100644 --- a/spring-cloud-data-flow/data-flow-server/pom.xml +++ b/spring-cloud-data-flow/data-flow-server/pom.xml @@ -1,28 +1,22 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung.spring.cloud data-flow-server 0.0.1-SNAPSHOT jar - data-flow-server Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 - - 1.1.0.RELEASE - Brixton.SR7 - - org.springframework.cloud @@ -49,4 +43,9 @@ + + 1.1.0.RELEASE + Brixton.SR7 + + diff --git a/spring-cloud-data-flow/data-flow-server/src/main/resources/logback.xml b/spring-cloud-data-flow/data-flow-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud-data-flow/data-flow-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java index bb8660b816..9eba12fc12 100644 --- a/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java +++ b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java @@ -2,7 +2,14 @@ package org.baeldung.spring.cloud; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mockito; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @@ -13,4 +20,24 @@ public class DataFlowServerApplicationIntegrationTest { public void contextLoads() { } + @EnableRedisHttpSession + @Configuration + static class Config { + + @Bean + @SuppressWarnings("unchecked") + public RedisSerializer defaultRedisSerializer() { + return Mockito.mock(RedisSerializer.class); + } + + @Bean + public RedisConnectionFactory connectionFactory() { + + RedisConnectionFactory factory = Mockito.mock(RedisConnectionFactory.class); + RedisConnection connection = Mockito.mock(RedisConnection.class); + Mockito.when(factory.getConnection()).thenReturn(connection); + + return factory; + } + } } diff --git a/spring-cloud-data-flow/data-flow-shell/pom.xml b/spring-cloud-data-flow/data-flow-shell/pom.xml index debbe44a4a..e4ec145277 100644 --- a/spring-cloud-data-flow/data-flow-shell/pom.xml +++ b/spring-cloud-data-flow/data-flow-shell/pom.xml @@ -1,28 +1,22 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung.spring.cloud data-flow-shell 0.0.1-SNAPSHOT jar - data-flow-shell Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 - - Brixton.SR7 - 1.1.0.RELEASE - - org.springframework.cloud @@ -49,4 +43,9 @@ + + Brixton.SR7 + 1.1.0.RELEASE + + diff --git a/spring-cloud-data-flow/data-flow-shell/src/main/resources/logback.xml b/spring-cloud-data-flow/data-flow-shell/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud-data-flow/data-flow-shell/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud-data-flow/log-sink/pom.xml b/spring-cloud-data-flow/log-sink/pom.xml index 6e541ae3fa..33a0a4df45 100644 --- a/spring-cloud-data-flow/log-sink/pom.xml +++ b/spring-cloud-data-flow/log-sink/pom.xml @@ -1,27 +1,22 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung.spring.cloud log-sink 0.0.1-SNAPSHOT jar - log-sink Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 - - Brixton.SR7 - - org.springframework.cloud @@ -41,4 +36,8 @@ + + Brixton.SR7 + + diff --git a/spring-cloud-data-flow/log-sink/src/main/resources/logback.xml b/spring-cloud-data-flow/log-sink/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud-data-flow/log-sink/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud-data-flow/pom.xml b/spring-cloud-data-flow/pom.xml index 9ff23305fd..5f24aa2cbd 100644 --- a/spring-cloud-data-flow/pom.xml +++ b/spring-cloud-data-flow/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung.spring.cloud spring-cloud-data-flow diff --git a/spring-cloud-data-flow/time-processor/pom.xml b/spring-cloud-data-flow/time-processor/pom.xml index 42d0fa434f..4f31e55b96 100644 --- a/spring-cloud-data-flow/time-processor/pom.xml +++ b/spring-cloud-data-flow/time-processor/pom.xml @@ -1,27 +1,22 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung.spring.cloud time-processor 0.0.1-SNAPSHOT jar - time-processor Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 - - Brixton.SR7 - - org.springframework.cloud @@ -41,4 +36,8 @@ + + Brixton.SR7 + + diff --git a/spring-cloud-data-flow/time-processor/src/main/resources/logback.xml b/spring-cloud-data-flow/time-processor/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud-data-flow/time-processor/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud-data-flow/time-source/pom.xml b/spring-cloud-data-flow/time-source/pom.xml index 2a50c9b0d0..dc593fdb14 100644 --- a/spring-cloud-data-flow/time-source/pom.xml +++ b/spring-cloud-data-flow/time-source/pom.xml @@ -1,27 +1,22 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - + org.baeldung.spring.cloud time-source 0.0.1-SNAPSHOT jar - time-source Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 - - Brixton.SR7 - - org.springframework.cloud @@ -41,4 +36,8 @@ + + Brixton.SR7 + + diff --git a/spring-cloud-data-flow/time-source/src/main/resources/logback.xml b/spring-cloud-data-flow/time-source/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud-data-flow/time-source/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/README.md b/spring-cloud/README.md index b7a0a5fad7..805052e4db 100644 --- a/spring-cloud/README.md +++ b/spring-cloud/README.md @@ -26,3 +26,5 @@ - [Instance Profile Credentials using Spring Cloud](http://www.baeldung.com/spring-cloud-instance-profiles) - [An Intro to Spring Cloud Security](http://www.baeldung.com/spring-cloud-security) - [An Intro to Spring Cloud Task](http://www.baeldung.com/spring-cloud-task) +- [Running Spring Boot Applications With Minikube](http://www.baeldung.com/spring-boot-minikube) +- [Introduction to Netflix Archaius with Spring Cloud](https://www.baeldung.com/netflix-archaius-spring-cloud-integration) diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 7c739d656e..7d180047de 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.baeldung.spring.cloud spring-cloud @@ -26,30 +25,16 @@ spring-cloud-zookeeper spring-cloud-gateway spring-cloud-stream + spring-cloud-stream-starters/twitterhdfs spring-cloud-connectors-heroku spring-cloud-aws spring-cloud-consul spring-cloud-zuul-eureka-integration spring-cloud-contract spring-cloud-kubernetes + spring-cloud-archaius - - UTF-8 - 1.2.2.RELEASE - Brixton.SR7 - 1.2.2.RELEASE - 1.2.2.RELEASE - 1.2.3.RELEASE - 1.2.3.RELEASE - 1.2.3.RELEASE - 1.3.0.RELEASE - 1.4.2.RELEASE - 3.7.0 - 1.4.2.RELEASE - 1.2.3.RELEASE - - @@ -62,4 +47,18 @@ + + 1.2.2.RELEASE + Brixton.SR7 + 1.2.2.RELEASE + 1.2.2.RELEASE + 1.2.3.RELEASE + 1.2.3.RELEASE + 1.2.3.RELEASE + 1.3.0.RELEASE + 1.4.2.RELEASE + 1.4.2.RELEASE + 1.2.3.RELEASE + + diff --git a/spring-cloud/spring-cloud-archaius/README.md b/spring-cloud/spring-cloud-archaius/README.md new file mode 100644 index 0000000000..9de26352e1 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/README.md @@ -0,0 +1,14 @@ +# Spring Cloud Archaius + +#### Basic Config +This service has the basic, out-of-the-box Spring Cloud Netflix Archaius configuration. + +#### Extra Configs +This service customizes some properties supported by Archaius. + +These properties are set up on the main method, since Archaius uses System properties, but they could be added as command line arguments when launching the app. + +#### Additional Sources +In this service we create a new AbstractConfiguration bean, setting up a new Configuration Properties source. + +These properties have precedence over all the other properties in the Archaius Composite Configuration. \ No newline at end of file diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/pom.xml b/spring-cloud/spring-cloud-archaius/additional-sources-simple/pom.xml new file mode 100644 index 0000000000..1ae6d543fb --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + additional-sources-simple + 1.0.0-SNAPSHOT + jar + additional-sources-simple + + + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/AdditionalSourcesSimpleApplication.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/AdditionalSourcesSimpleApplication.java new file mode 100644 index 0000000000..e1a1d106cf --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/AdditionalSourcesSimpleApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.cloud.archaius.additionalsources; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AdditionalSourcesSimpleApplication { + + public static void main(String[] args) { + SpringApplication.run(AdditionalSourcesSimpleApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/config/ApplicationPropertiesConfigurations.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/config/ApplicationPropertiesConfigurations.java new file mode 100644 index 0000000000..f2d8ca2638 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/config/ApplicationPropertiesConfigurations.java @@ -0,0 +1,21 @@ +package com.baeldung.spring.cloud.archaius.additionalsources.config; + +import org.apache.commons.configuration.AbstractConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.netflix.config.DynamicConfiguration; +import com.netflix.config.FixedDelayPollingScheduler; +import com.netflix.config.PolledConfigurationSource; +import com.netflix.config.sources.URLConfigurationSource; + +@Configuration +public class ApplicationPropertiesConfigurations { + + @Bean + public AbstractConfiguration addApplicationPropertiesSource() { + PolledConfigurationSource source = new URLConfigurationSource("classpath:other-config.properties"); + return new DynamicConfiguration(source, new FixedDelayPollingScheduler()); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/controller/ConfigPropertiesController.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/controller/ConfigPropertiesController.java new file mode 100644 index 0000000000..304369a036 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/controller/ConfigPropertiesController.java @@ -0,0 +1,37 @@ +package com.baeldung.spring.cloud.archaius.additionalsources.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RestController +public class ConfigPropertiesController { + + private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.one", "not found!"); + + private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.two", "not found!"); + + private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.three", "not found!"); + + private DynamicStringProperty propertyFourWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.four", "not found!"); + + @GetMapping("/properties-from-dynamic") + public Map getPropertiesFromDynamic() { + Map properties = new HashMap<>(); + properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get()); + properties.put(propertyTwoWithDynamic.getName(), propertyTwoWithDynamic.get()); + properties.put(propertyThreeWithDynamic.getName(), propertyThreeWithDynamic.get()); + properties.put(propertyFourWithDynamic.getName(), propertyFourWithDynamic.get()); + return properties; + } +} diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/application.properties b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/application.properties new file mode 100644 index 0000000000..bf55e89a27 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8082 +baeldung.archaius.properties.one=one FROM:application.properties +baeldung.archaius.properties.two=two FROM:application.properties diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/config.properties b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/config.properties new file mode 100644 index 0000000000..b104c0c488 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/config.properties @@ -0,0 +1,2 @@ +baeldung.archaius.properties.one=one FROM:config.properties +baeldung.archaius.properties.three=three FROM:config.properties diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/other-config.properties b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/other-config.properties new file mode 100644 index 0000000000..00fe8ff2aa --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/other-config.properties @@ -0,0 +1,2 @@ +baeldung.archaius.properties.one=one FROM:other-config.properties +baeldung.archaius.properties.four=four FROM:other-config.properties diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/ArchaiusAdditionalSourcesLiveTest.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/ArchaiusAdditionalSourcesLiveTest.java new file mode 100644 index 0000000000..f3a345d869 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/ArchaiusAdditionalSourcesLiveTest.java @@ -0,0 +1,54 @@ +package com.baeldung.spring.cloud.archaius.additionalsources; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.Map; + +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.context.ConfigurableApplicationContext; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ArchaiusAdditionalSourcesLiveTest { + + private static final String BASE_URL = "http://localhost:8082"; + + private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic"; + private static final Map EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties(); + + private static Map createExpectedArchaiusProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:other-config.properties"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "three FROM:config.properties"); + map.put("baeldung.archaius.properties.four", "four FROM:other-config.properties"); + return map; + } + + @Autowired + ConfigurableApplicationContext context; + + @Autowired + private TestRestTemplate template; + + private Map exchangeAsMap(String uri, ParameterizedTypeReference> responseType) { + return template.exchange(uri, HttpMethod.GET, null, responseType) + .getBody(); + } + + @Test + public void givenNonDefaultConfigurationFilesSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() { + Map initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES); + } +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/pom.xml b/spring-cloud/spring-cloud-archaius/basic-config/pom.xml new file mode 100644 index 0000000000..b5b091712d --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + basic-config + 1.0.0-SNAPSHOT + jar + basic-config + + + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/BasicArchaiusApplication.java b/spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/BasicArchaiusApplication.java new file mode 100644 index 0000000000..e6e578eed3 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/BasicArchaiusApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.cloud.archaius.basic; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BasicArchaiusApplication { + + public static void main(String[] args) { + SpringApplication.run(BasicArchaiusApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/controller/ConfigPropertiesController.java b/spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/controller/ConfigPropertiesController.java new file mode 100644 index 0000000000..46b8f345f6 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/controller/ConfigPropertiesController.java @@ -0,0 +1,70 @@ +package com.baeldung.spring.cloud.archaius.basic.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.netflix.config.DynamicIntProperty; +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RestController +public class ConfigPropertiesController { + + @Value("${baeldung.archaius.properties.one:not found!}") + private String propertyOneWithValue; + + @Value("${baeldung.archaius.properties.two:not found!}") + private String propertyTwoWithValue; + + @Value("${baeldung.archaius.properties.three:not found!}") + private String propertyThreeWithValue; + + @Value("${baeldung.archaius.properties.four:not found!}") + private String propertyFourWithValue; + + private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.one", "not found!"); + + private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.two", "not found!"); + + private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.three", "not found!"); + + private DynamicStringProperty propertyFourWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.four", "not found!"); + + private DynamicIntProperty intPropertyWithDynamic = DynamicPropertyFactory.getInstance() + .getIntProperty("baeldung.archaius.properties.int", 0); + + @GetMapping("/properties-from-value") + public Map getPropertiesFromValue() { + Map properties = new HashMap<>(); + properties.put("baeldung.archaius.properties.one", propertyOneWithValue); + properties.put("baeldung.archaius.properties.two", propertyTwoWithValue); + properties.put("baeldung.archaius.properties.three", propertyThreeWithValue); + properties.put("baeldung.archaius.properties.four", propertyFourWithValue); + return properties; + } + + @GetMapping("/properties-from-dynamic") + public Map getPropertiesFromDynamic() { + Map properties = new HashMap<>(); + properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get()); + properties.put(propertyTwoWithDynamic.getName(), propertyTwoWithDynamic.get()); + properties.put(propertyThreeWithDynamic.getName(), propertyThreeWithDynamic.get()); + properties.put(propertyFourWithDynamic.getName(), propertyFourWithDynamic.get()); + return properties; + } + + @GetMapping("/int-property") + public Map getIntPropertyFromDynamic() { + Map properties = new HashMap<>(); + properties.put(intPropertyWithDynamic.getName(), intPropertyWithDynamic.get()); + return properties; + } +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/application.properties b/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/application.properties new file mode 100644 index 0000000000..1a35a22197 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8080 +baeldung.archaius.properties.one=one FROM:application.properties +baeldung.archaius.properties.two=two FROM:application.properties \ No newline at end of file diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/config.properties b/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/config.properties new file mode 100644 index 0000000000..86ae575d20 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/config.properties @@ -0,0 +1,4 @@ +baeldung.archaius.properties.one=one FROM:config.properties +baeldung.archaius.properties.three=three FROM:config.properties + +baeldung.archaius.properties.int=1 diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/other.properties b/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/other.properties new file mode 100644 index 0000000000..26796b7341 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/other.properties @@ -0,0 +1,2 @@ +baeldung.archaius.properties.one=one FROM:other.properties +baeldung.archaius.properties.four=four FROM:other.properties diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationIntegrationTest.java b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationIntegrationTest.java new file mode 100644 index 0000000000..2948606c0b --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationIntegrationTest.java @@ -0,0 +1,45 @@ +package com.baeldung.spring.cloud.archaius.basic; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collections; + +import org.junit.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.util.TestPropertyValues; +import org.springframework.cloud.context.environment.EnvironmentChangeEvent; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RunWith(JUnitPlatform.class) +@ExtendWith(SpringExtension.class) +@SpringBootTest +public class ArchaiusBasicConfigurationIntegrationTest { + + @Autowired + ConfigurableApplicationContext context; + + private DynamicStringProperty testPropertyWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.test.properties.one", "not found!"); + + @Test + public void givenIntialPropertyValue_whenPropertyChanges_thenArchaiusRetrievesNewValue() { + String initialValue = testPropertyWithDynamic.get(); + + TestPropertyValues.of("baeldung.archaius.test.properties.one=new-value") + .applyTo(context); + context.publishEvent(new EnvironmentChangeEvent(Collections.singleton("baeldung.archaius.test.properties.one"))); + String finalValue = testPropertyWithDynamic.get(); + + assertThat(initialValue).isEqualTo("test-one"); + assertThat(finalValue).isEqualTo("new-value"); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationLiveTest.java b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationLiveTest.java new file mode 100644 index 0000000000..70d43df60d --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationLiveTest.java @@ -0,0 +1,74 @@ +package com.baeldung.spring.cloud.archaius.basic; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.Map; + +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.context.ConfigurableApplicationContext; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ArchaiusBasicConfigurationLiveTest { + + private static final String BASE_URL = "http://localhost:8080"; + + private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic"; + private static final Map EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties(); + + private static Map createExpectedArchaiusProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:application.properties"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "three FROM:config.properties"); + map.put("baeldung.archaius.properties.four", "not found!"); + return map; + } + + private static final String VALUE_PROPERTIES_URL = "/properties-from-value"; + private static final Map EXPECTED_VALUE_PROPERTIES = createExpectedValueProperties(); + + private static Map createExpectedValueProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:application.properties"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "not found!"); + map.put("baeldung.archaius.properties.four", "not found!"); + return map; + } + + @Autowired + ConfigurableApplicationContext context; + + @Autowired + private TestRestTemplate template; + + private Map exchangeAsMap(String uri, ParameterizedTypeReference> responseType) { + return template.exchange(uri, HttpMethod.GET, null, responseType) + .getBody(); + } + + @Test + public void givenDefaultConfigurationSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() { + Map initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES); + } + + @Test + public void givenNonDefaultConfigurationFilesSetup_whenRequestSpringVisibleProperties_thenEndpointDoesntRetrieveArchaiusProperties() { + Map initialResponse = this.exchangeAsMap(BASE_URL + VALUE_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_VALUE_PROPERTIES); + } +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/resources/config.properties b/spring-cloud/spring-cloud-archaius/basic-config/src/test/resources/config.properties new file mode 100644 index 0000000000..1ceb5d1161 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/resources/config.properties @@ -0,0 +1,3 @@ +baeldung.archaius.test.properties.one=test-one +baeldung.archaius.test.properties.two=test-two +baeldung.archaius.test.properties.int=1 diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/pom.xml b/spring-cloud/spring-cloud-archaius/extra-configs/pom.xml new file mode 100644 index 0000000000..2f3f2b084a --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + extra-configs + 1.0.0-SNAPSHOT + jar + extra-configs + + + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-netflix-archaius + + + + + + + org.springframework.cloud + spring-cloud-netflix + ${spring-cloud-dependencies.version} + pom + import + + + + + 2.0.1.RELEASE + + diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/ExtraConfigsApplication.java b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/ExtraConfigsApplication.java new file mode 100644 index 0000000000..4747d875db --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/ExtraConfigsApplication.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.archaius.extraconfigs; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ExtraConfigsApplication { + + public static void main(String[] args) { + // System properties can be set as command line arguments too + System.setProperty("archaius.configurationSource.additionalUrls", "classpath:other-config-dir/extra.properties"); + System.setProperty("archaius.configurationSource.defaultFileName", "other.properties"); + SpringApplication.run(ExtraConfigsApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/controllers/ConfigPropertiesController.java b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/controllers/ConfigPropertiesController.java new file mode 100644 index 0000000000..382c6b3a2c --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/controllers/ConfigPropertiesController.java @@ -0,0 +1,60 @@ +package com.baeldung.spring.cloud.archaius.extraconfigs.controllers; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RestController +public class ConfigPropertiesController { + + @Value("${baeldung.archaius.properties.one:not found!}") + private String propertyOneWithValue; + + @Value("${baeldung.archaius.properties.two:not found!}") + private String propertyTwoWithValue; + + @Value("${baeldung.archaius.properties.three:not found!}") + private String propertyThreeWithValue; + + @Value("${baeldung.archaius.properties.four:not found!}") + private String propertyFourWithValue; + + private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.one", "not found!"); + + private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.two", "not found!"); + + private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.three", "not found!"); + + private DynamicStringProperty propertyFourWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.four", "not found!"); + + @GetMapping("/properties-from-value") + public Map getPropertiesFromValue() { + Map properties = new HashMap<>(); + properties.put("baeldung.archaius.properties.one", propertyOneWithValue); + properties.put("baeldung.archaius.properties.two", propertyTwoWithValue); + properties.put("baeldung.archaius.properties.three", propertyThreeWithValue); + properties.put("baeldung.archaius.properties.four", propertyFourWithValue); + return properties; + } + + @GetMapping("/properties-from-dynamic") + public Map getPropertiesFromDynamic() { + Map properties = new HashMap<>(); + properties.put("baeldung.archaius.properties.one", propertyOneWithDynamic.get()); + properties.put("baeldung.archaius.properties.two", propertyTwoWithDynamic.get()); + properties.put("baeldung.archaius.properties.three", propertyThreeWithDynamic.get()); + properties.put("baeldung.archaius.properties.four", propertyFourWithDynamic.get()); + return properties; + } + +} diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/application.properties b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/application.properties new file mode 100644 index 0000000000..1e36b134d4 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8081 +baeldung.archaius.properties.one=one FROM:application.properties +baeldung.archaius.properties.two=two FROM:application.properties diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other-config-dir/extra.properties b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other-config-dir/extra.properties new file mode 100644 index 0000000000..ea99914cc1 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other-config-dir/extra.properties @@ -0,0 +1,2 @@ +baeldung.archaius.properties.one=one FROM:extra.properties +baeldung.archaius.properties.three=three FROM:extra.properties diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other.properties b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other.properties new file mode 100644 index 0000000000..26796b7341 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other.properties @@ -0,0 +1,2 @@ +baeldung.archaius.properties.one=one FROM:other.properties +baeldung.archaius.properties.four=four FROM:other.properties diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/com/baeldung/spring/cloud/archaius/extraconfigs/ArchaiusExtraConfigsLiveTest.java b/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/com/baeldung/spring/cloud/archaius/extraconfigs/ArchaiusExtraConfigsLiveTest.java new file mode 100644 index 0000000000..232ca73352 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/com/baeldung/spring/cloud/archaius/extraconfigs/ArchaiusExtraConfigsLiveTest.java @@ -0,0 +1,54 @@ +package com.baeldung.spring.cloud.archaius.extraconfigs; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.Map; + +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.context.ConfigurableApplicationContext; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ArchaiusExtraConfigsLiveTest { + + private static final String BASE_URL = "http://localhost:8081"; + + private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic"; + private static final Map EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties(); + + private static Map createExpectedArchaiusProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:application.properties"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "three FROM:extra.properties"); + map.put("baeldung.archaius.properties.four", "four FROM:other.properties"); + return map; + } + + @Autowired + ConfigurableApplicationContext context; + + @Autowired + private TestRestTemplate template; + + private Map exchangeAsMap(String uri, ParameterizedTypeReference> responseType) { + return template.exchange(uri, HttpMethod.GET, null, responseType) + .getBody(); + } + + @Test + public void givenNonDefaultConfigurationFilesSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() { + Map initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES); + } +} diff --git a/spring-cloud/spring-cloud-archaius/pom.xml b/spring-cloud/spring-cloud-archaius/pom.xml new file mode 100644 index 0000000000..cd102f86cd --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/pom.xml @@ -0,0 +1,64 @@ + + + 4.0.0 + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + spring-cloud-archaius + Spring Cloud Archaius Pom parent + pom + + + com.baeldung.spring.cloud + spring-cloud + 1.0.0-SNAPSHOT + .. + + + + basic-config + additional-sources-simple + extra-configs + + + + + org.springframework.cloud + spring-cloud-starter-netflix-archaius + + + org.springframework.boot + spring-boot-starter-test + + + org.assertj + assertj-core + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + + + + + org.springframework.cloud + spring-cloud-netflix + ${spring-cloud-dependencies.version} + pom + import + + + + + + 2.0.1.RELEASE + 1.2.0 + + diff --git a/spring-cloud/spring-cloud-aws/pom.xml b/spring-cloud/spring-cloud-aws/pom.xml index 2d2c29e53e..6933845173 100644 --- a/spring-cloud/spring-cloud-aws/pom.xml +++ b/spring-cloud/spring-cloud-aws/pom.xml @@ -1,19 +1,18 @@ + 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.cloud spring-cloud-aws - 0.0.1-SNAPSHOT jar Spring Cloud AWS Spring Cloud AWS Examples - org.springframework.boot - spring-boot-starter-parent - 1.5.8.RELEASE - + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-1 @@ -44,7 +43,6 @@ org.postgresql postgresql - @@ -59,26 +57,8 @@ - - - - maven-surefire-plugin - - - **/*IntegrationTest.java - - - - - - - com.baeldung.spring.cloud.aws.SpringCloudAwsApplication - UTF-8 - UTF-8 - 1.8 Dalston.SR4 - diff --git a/spring-cloud/spring-cloud-aws/src/main/resources/logback.xml b/spring-cloud/spring-cloud-aws/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/README.MD b/spring-cloud/spring-cloud-bootstrap/README.MD index 164219c185..5185200469 100644 --- a/spring-cloud/spring-cloud-bootstrap/README.MD +++ b/spring-cloud/spring-cloud-bootstrap/README.MD @@ -11,5 +11,5 @@ - git add . - git commit -m "First commit" - start the config server - - start the discover server + - start the discovery server - start all the other servers in any order (gateway, svc-book, svc-rating, zipkin) diff --git a/spring-cloud/spring-cloud-bootstrap/config/pom.xml b/spring-cloud/spring-cloud-bootstrap/config/pom.xml index ace46395c0..14a926fc2c 100644 --- a/spring-cloud/spring-cloud-bootstrap/config/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/config/pom.xml @@ -6,10 +6,10 @@ 1.0.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/logback.xml b/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml b/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml index 7a3ffd81cd..f94d8829f6 100644 --- a/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml @@ -7,10 +7,10 @@ 1.0.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/src/main/resources/logback.xml b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml index 5001b35fb5..fc69c16738 100644 --- a/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml @@ -6,10 +6,10 @@ 1.0.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/main/resources/logback.xml b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/pom.xml b/spring-cloud/spring-cloud-bootstrap/pom.xml index 68606d9058..74801159eb 100644 --- a/spring-cloud/spring-cloud-bootstrap/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-cloud-bootstrap 1.0.0-SNAPSHOT diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml b/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml index 2552752e29..c0d920d373 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml @@ -8,10 +8,10 @@ 1.0.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/resources/logback.xml b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml b/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml index 857ee486c0..3aa2db8f65 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml @@ -8,10 +8,10 @@ 1.0.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/resources/logback.xml b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml b/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml index 743281d346..8735e24d48 100644 --- a/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml @@ -6,10 +6,10 @@ 1.0.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/zipkin/src/main/resources/logback.xml b/spring-cloud/spring-cloud-bootstrap/zipkin/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/zipkin/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-config/pom.xml b/spring-cloud/spring-cloud-config/pom.xml index 100b421a55..b28828bf37 100644 --- a/spring-cloud/spring-cloud-config/pom.xml +++ b/spring-cloud/spring-cloud-config/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.baeldung.spring.cloud spring-cloud-config @@ -9,10 +8,10 @@ pom - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-connectors-heroku/pom.xml b/spring-cloud/spring-cloud-connectors-heroku/pom.xml index 9b5d7c91d9..f00c9eb1fc 100644 --- a/spring-cloud/spring-cloud-connectors-heroku/pom.xml +++ b/spring-cloud/spring-cloud-connectors-heroku/pom.xml @@ -1,16 +1,16 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.spring.cloud spring-cloud-connectors-heroku 1.0.0-SNAPSHOT - spring-boot-starter-parent - org.springframework.boot - 1.4.4.RELEASE - + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-1 @@ -33,8 +33,7 @@ org.postgresql postgresql - ${postgresql.version} - + com.h2database h2 @@ -54,32 +53,8 @@ - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/JdbcTest.java - **/*LiveTest.java - - true - - - - - Brixton.SR7 - 2.19.1 9.4-1201-jdbc4 - \ No newline at end of file diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/main/resources/logback.xml b/spring-cloud/spring-cloud-connectors-heroku/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-consul/pom.xml b/spring-cloud/spring-cloud-consul/pom.xml index d440da8e0c..8181832bea 100644 --- a/spring-cloud/spring-cloud-consul/pom.xml +++ b/spring-cloud/spring-cloud-consul/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 org.baeldung spring-cloud-consul @@ -18,19 +17,18 @@ org.springframework.cloud spring-cloud-starter-consul-all - 1.3.0.RELEASE + ${spring-cloud-starter-consul.version} org.springframework.cloud spring-cloud-starter-consul-config - 1.3.0.RELEASE + ${spring-cloud-starter-consul.version} - UTF-8 - 3.7.0 + 1.3.0.RELEASE diff --git a/spring-cloud/spring-cloud-consul/src/main/resources/logback.xml b/spring-cloud/spring-cloud-consul/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-consul/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-contract/pom.xml b/spring-cloud/spring-cloud-contract/pom.xml index f1d5f6f262..5dde6a7a99 100644 --- a/spring-cloud/spring-cloud-contract/pom.xml +++ b/spring-cloud/spring-cloud-contract/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 pom com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/main/resources/logback.xml b/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/main/resources/logback.xml b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-eureka/pom.xml b/spring-cloud/spring-cloud-eureka/pom.xml index 9392f17325..37571bc29a 100644 --- a/spring-cloud/spring-cloud-eureka/pom.xml +++ b/spring-cloud/spring-cloud-eureka/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.baeldung.spring.cloud spring-cloud-eureka @@ -24,8 +23,6 @@ - UTF-8 - 3.7.0 1.4.2.RELEASE diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml index 70379fbc65..c7822d51ee 100644 --- a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 spring-cloud-eureka-client @@ -43,9 +42,4 @@ - - Brixton.SR7 - 1.2.3.RELEASE - 1.4.2.RELEASE - diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/main/resources/logback.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/pom.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/pom.xml index 22b0e7b899..4552c458ec 100644 --- a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/pom.xml +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 spring-cloud-eureka-feign-client 1.0.0-SNAPSHOT @@ -20,7 +19,7 @@ com.baeldung.spring.cloud spring-cloud-eureka-client - 1.0.0-SNAPSHOT + ${spring-cloud-eureka-client.version} org.springframework.cloud @@ -52,9 +51,6 @@ - Brixton.SR7 - 1.2.3.RELEASE - 1.2.3.RELEASE - 1.4.2.RELEASE + 1.0.0-SNAPSHOT diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/resources/logback.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/pom.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/pom.xml index 4ea9748c14..8082b30c33 100644 --- a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/pom.xml +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/pom.xml @@ -1,13 +1,10 @@ - + 4.0.0 - spring-cloud-eureka-server 1.0.0-SNAPSHOT jar - Spring Cloud Eureka Server Spring Cloud Eureka Server Demo @@ -38,8 +35,4 @@ - - Brixton.SR7 - 1.2.3.RELEASE - diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/main/resources/logback.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-gateway/pom.xml b/spring-cloud/spring-cloud-gateway/pom.xml index 4cc45cc6b3..8babbff274 100644 --- a/spring-cloud/spring-cloud-gateway/pom.xml +++ b/spring-cloud/spring-cloud-gateway/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 spring-cloud-gateway jar @@ -14,64 +13,50 @@ .. + + + + org.springframework.cloud + spring-cloud-gateway + ${cloud.version} + pom + import + + + + + + org.springframework.cloud + spring-cloud-starter + org.springframework.boot - spring-boot-actuator - ${version} + spring-boot-starter-actuator org.springframework.boot spring-boot-starter-webflux - ${version} - - - org.springframework.cloud - spring-cloud-gateway-core - ${version} org.hibernate hibernate-validator-cdi - 6.0.2.Final + ${hibernate-validator.version} javax.validation validation-api - 2.0.0.Final io.projectreactor.ipc reactor-netty - 0.7.0.M1 - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - UTF-8 - 3.7.0 - 1.4.2.RELEASE - 2.0.0.M6 + 2.0.1.RELEASE + 6.0.2.Final diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/spring/cloud/GatewayApplication.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/spring/cloud/GatewayApplication.java index 4d5f61315f..ba384749df 100644 --- a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/spring/cloud/GatewayApplication.java +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/spring/cloud/GatewayApplication.java @@ -9,4 +9,5 @@ public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } + } \ No newline at end of file diff --git a/spring-cloud/spring-cloud-gateway/src/main/resources/application.yml b/spring-cloud/spring-cloud-gateway/src/main/resources/application.yml index 8b981f8071..2450638e46 100644 --- a/spring-cloud/spring-cloud-gateway/src/main/resources/application.yml +++ b/spring-cloud/spring-cloud-gateway/src/main/resources/application.yml @@ -8,6 +8,9 @@ spring: uri: http://www.baeldung.com predicates: - Path=/baeldung + management: - security: - enabled: false \ No newline at end of file + endpoints: + web: + exposure: + include: "*" diff --git a/spring-cloud/spring-cloud-gateway/src/main/resources/logback.xml b/spring-cloud/spring-cloud-gateway/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml index 700357d673..ce1e1856ed 100644 --- a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml @@ -19,7 +19,7 @@ com.baeldung.spring.cloud rest-producer - 1.0.0-SNAPSHOT + ${rest-producer.version} org.springframework.cloud @@ -66,8 +66,6 @@ - 1.2.3.RELEASE - 1.2.3.RELEASE - 1.4.2.RELEASE + 1.0.0-SNAPSHOT diff --git a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/resources/logback.xml b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-hystrix/pom.xml b/spring-cloud/spring-cloud-hystrix/pom.xml index e7b635a441..266644b4c3 100644 --- a/spring-cloud/spring-cloud-hystrix/pom.xml +++ b/spring-cloud/spring-cloud-hystrix/pom.xml @@ -22,10 +22,4 @@ feign-rest-consumer - - UTF-8 - 3.7.0 - 1.4.2.RELEASE - - diff --git a/spring-cloud/spring-cloud-hystrix/rest-consumer/pom.xml b/spring-cloud/spring-cloud-hystrix/rest-consumer/pom.xml index 81fb442ad7..651f80fc92 100644 --- a/spring-cloud/spring-cloud-hystrix/rest-consumer/pom.xml +++ b/spring-cloud/spring-cloud-hystrix/rest-consumer/pom.xml @@ -1,13 +1,11 @@ - + 4.0.0 rest-consumer 1.0.0-SNAPSHOT jar - rest-consumer @@ -57,9 +55,4 @@ - - Brixton.SR7 - 1.2.3.RELEASE - 1.4.2.RELEASE - diff --git a/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/resources/logback.xml b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-hystrix/rest-producer/pom.xml b/spring-cloud/spring-cloud-hystrix/rest-producer/pom.xml index f96d8e1768..8437ac6833 100644 --- a/spring-cloud/spring-cloud-hystrix/rest-producer/pom.xml +++ b/spring-cloud/spring-cloud-hystrix/rest-producer/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 rest-producer @@ -25,7 +24,4 @@ - - Brixton.SR7 - diff --git a/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/resources/logback.xml b/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-producer/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/demo-backend/pom.xml b/spring-cloud/spring-cloud-kubernetes/demo-backend/pom.xml index 109953ea42..308a81fd74 100644 --- a/spring-cloud/spring-cloud-kubernetes/demo-backend/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/demo-backend/pom.xml @@ -1,21 +1,14 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + demo-backend com.baeldung.spring.cloud spring-cloud-kubernetes 1.0-SNAPSHOT - demo-backend - - - - UTF-8 - UTF-8 - 1.8 - @@ -39,5 +32,4 @@ - diff --git a/spring-cloud/spring-cloud-kubernetes/demo-backend/src/main/resources/logback.xml b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationIntegrationTest.java b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationIntegrationTest.java new file mode 100644 index 0000000000..2440b97aaf --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationIntegrationTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.kubernetes.backend; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class KubernetesBackendApplicationIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationTests.java b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationTests.java deleted file mode 100644 index 5ccc49eaa7..0000000000 --- a/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.spring.cloud.kubernetes.backend; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class KubernetesBackendApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud/spring-cloud-kubernetes/demo-frontend/pom.xml b/spring-cloud/spring-cloud-kubernetes/demo-frontend/pom.xml index 32fa900f39..968529c648 100644 --- a/spring-cloud/spring-cloud-kubernetes/demo-frontend/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/demo-frontend/pom.xml @@ -1,21 +1,14 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + demo-frontend com.baeldung.spring.cloud spring-cloud-kubernetes 1.0-SNAPSHOT - demo-frontend - - - - UTF-8 - UTF-8 - 1.8 - @@ -39,5 +32,4 @@ - diff --git a/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/main/resources/logback.xml b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationIntegrationTest.java b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationIntegrationTest.java new file mode 100644 index 0000000000..19ad9676cb --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationIntegrationTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.kubernetes.frontend; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class KubernetesFrontendApplicationIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationTests.java b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationTests.java deleted file mode 100644 index 0e34eb45f8..0000000000 --- a/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.spring.cloud.kubernetes.frontend; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class KubernetesFrontendApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud/spring-cloud-kubernetes/pom.xml b/spring-cloud/spring-cloud-kubernetes/pom.xml index 96388c3672..fd9f7b5876 100644 --- a/spring-cloud/spring-cloud-kubernetes/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/pom.xml @@ -1,7 +1,7 @@ - + + 4.0.0 com.baeldung.spring.cloud spring-cloud-kubernetes @@ -14,12 +14,10 @@ - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 - 4.0.0 - \ No newline at end of file diff --git a/spring-cloud/spring-cloud-rest/pom.xml b/spring-cloud/spring-cloud-rest/pom.xml index bf0dbd7ee6..f78f58caa0 100644 --- a/spring-cloud/spring-cloud-rest/pom.xml +++ b/spring-cloud/spring-cloud-rest/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 org.baeldung spring-cloud-rest @@ -44,8 +43,6 @@ - UTF-8 - 3.7.0 1.4.2.RELEASE 1.8 1.8 diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml index 8da8ef6141..d1139b1fa4 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung spring-cloud-rest-books-api @@ -10,10 +10,10 @@ Simple books API - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/resources/logback.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/BooksApiIntegrationTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/BooksApiIntegrationTest.java index d6b0ee1694..15056e110c 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/BooksApiIntegrationTest.java +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/BooksApiIntegrationTest.java @@ -2,7 +2,14 @@ package org.baeldung; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mockito; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @@ -13,4 +20,24 @@ public class BooksApiIntegrationTest { public void contextLoads() { } + @EnableRedisHttpSession + @Configuration + static class Config { + + @Bean + @SuppressWarnings("unchecked") + public RedisSerializer defaultRedisSerializer() { + return Mockito.mock(RedisSerializer.class); + } + + @Bean + public RedisConnectionFactory connectionFactory() { + + RedisConnectionFactory factory = Mockito.mock(RedisConnectionFactory.class); + RedisConnection connection = Mockito.mock(RedisConnection.class); + Mockito.when(factory.getConnection()).thenReturn(connection); + + return factory; + } + } } diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml index e083986890..a43829666c 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml @@ -1,27 +1,21 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - org.baeldung spring-cloud-rest-config-server 0.0.1-SNAPSHOT jar - spring-cloud-rest-config-server Spring Cloud REST configuration server - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 - - Camden.SR4 - - org.springframework.cloud @@ -49,4 +43,8 @@ + + Camden.SR4 + + diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/main/resources/logback.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml index c7d647a154..5b656d4342 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung spring-cloud-rest-discovery-server @@ -10,10 +10,10 @@ Spring Cloud REST server - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 @@ -52,7 +52,7 @@ - Camden.SR4 + Edgware.SR4 diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/main/resources/logback.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/test/java/org/baeldung/SpringCloudRestServerIntegrationTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/test/java/org/baeldung/SpringCloudRestServerIntegrationTest.java index e077c42a96..14597d5c2f 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/test/java/org/baeldung/SpringCloudRestServerIntegrationTest.java +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/test/java/org/baeldung/SpringCloudRestServerIntegrationTest.java @@ -2,7 +2,14 @@ package org.baeldung; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mockito; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @@ -11,5 +18,25 @@ public class SpringCloudRestServerIntegrationTest { @Test public void contextLoads() { } + + @EnableRedisHttpSession + @Configuration + static class Config { + + @Bean + @SuppressWarnings("unchecked") + public RedisSerializer defaultRedisSerializer() { + return Mockito.mock(RedisSerializer.class); + } -} + @Bean + public RedisConnectionFactory connectionFactory() { + + RedisConnectionFactory factory = Mockito.mock(RedisConnectionFactory.class); + RedisConnection connection = Mockito.mock(RedisConnection.class); + Mockito.when(factory.getConnection()).thenReturn(connection); + + return factory; + } + } +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml index d97ab43bfe..ef969e04e5 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung spring-cloud-rest-reviews-api @@ -10,16 +10,12 @@ Simple reviews API - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 - - 3.0.1 - - org.springframework.cloud @@ -57,6 +53,11 @@ org.springframework.boot spring-boot-starter-data-redis + + com.github.kstyrc + embedded-redis + ${embedded-redis.version} + @@ -71,4 +72,9 @@ + + 3.0.1 + 0.6 + + diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/resources/logback.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/org/baeldung/BookReviewsApiIntegrationTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/org/baeldung/BookReviewsApiIntegrationTest.java index d25e0bee20..c63b4ebb08 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/org/baeldung/BookReviewsApiIntegrationTest.java +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/org/baeldung/BookReviewsApiIntegrationTest.java @@ -2,7 +2,14 @@ package org.baeldung; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mockito; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @@ -13,4 +20,24 @@ public class BookReviewsApiIntegrationTest { public void contextLoads() { } + @EnableRedisHttpSession + @Configuration + static class Config { + + @Bean + @SuppressWarnings("unchecked") + public RedisSerializer defaultRedisSerializer() { + return Mockito.mock(RedisSerializer.class); + } + + @Bean + public RedisConnectionFactory connectionFactory() { + + RedisConnectionFactory factory = Mockito.mock(RedisConnectionFactory.class); + RedisConnection connection = Mockito.mock(RedisConnection.class); + Mockito.when(factory.getConnection()).thenReturn(connection); + + return factory; + } + } } diff --git a/spring-cloud/spring-cloud-ribbon-client/pom.xml b/spring-cloud/spring-cloud-ribbon-client/pom.xml index cada10ec35..12125f4cf3 100644 --- a/spring-cloud/spring-cloud-ribbon-client/pom.xml +++ b/spring-cloud/spring-cloud-ribbon-client/pom.xml @@ -1,18 +1,18 @@ + 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-cloud-ribbon + spring-cloud-ribbon-client 0.0.1-SNAPSHOT jar spring-cloud-ribbon-client Introduction to Spring Cloud Rest Client with Netflix Ribbon - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 @@ -38,25 +38,6 @@ - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - Brixton.SR7 diff --git a/spring-cloud/spring-cloud-ribbon-client/src/main/resources/logback.xml b/spring-cloud/spring-cloud-ribbon-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-security/auth-client/pom.xml b/spring-cloud/spring-cloud-security/auth-client/pom.xml index 1f6c22e2e1..f2d6308374 100644 --- a/spring-cloud/spring-cloud-security/auth-client/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-client/pom.xml @@ -1,41 +1,21 @@ + 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 auth-client 0.0.1-SNAPSHOT jar - auth-client Demo project for Spring Boot - org.springframework.boot - spring-boot-starter-parent - 1.5.9.RELEASE - + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../../parent-boot-1 - - - - org.springframework.cloud - spring-cloud-dependencies - Dalston.SR4 - pom - import - - - - - - - UTF-8 - UTF-8 - 1.8 - - org.springframework.boot @@ -66,7 +46,6 @@ org.webjars webjars-locator - org.springframework.boot spring-boot-starter-security @@ -74,20 +53,17 @@ org.webjars js-cookie - 2.1.0 + ${js-cookie.version} - org.springframework.boot spring-boot-devtools true - org.springframework.boot spring-boot-starter-thymeleaf - @@ -98,4 +74,25 @@ + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + UTF-8 + UTF-8 + 1.8 + 2.1.0 + Dalston.SR4 + + diff --git a/spring-cloud/spring-cloud-security/auth-client/src/main/resources/logback.xml b/spring-cloud/spring-cloud-security/auth-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-security/auth-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationTests.java b/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationTests.java index 5fa51a61c3..ca89575ee0 100644 --- a/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationTests.java +++ b/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationTests.java @@ -5,8 +5,10 @@ import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.CloudSite; + @RunWith(SpringRunner.class) -@SpringBootTest +@SpringBootTest(classes = CloudSite.class) public class Springoath2ApplicationTests { @Test diff --git a/spring-cloud/spring-cloud-security/auth-resource/pom.xml b/spring-cloud/spring-cloud-security/auth-resource/pom.xml index 3813cd3a52..0115259108 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-resource/pom.xml @@ -12,19 +12,12 @@ Demo project for Spring Boot - org.springframework.boot - spring-boot-starter-parent - 1.5.9.RELEASE - + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../../parent-boot-1 - - UTF-8 - UTF-8 - 1.8 - Edgware.RELEASE - - org.springframework.security.oauth @@ -66,5 +59,11 @@ + + UTF-8 + UTF-8 + 1.8 + Edgware.RELEASE + diff --git a/spring-cloud/spring-cloud-security/auth-resource/src/main/resources/logback.xml b/spring-cloud/spring-cloud-security/auth-resource/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-security/auth-resource/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-security/auth-server/pom.xml b/spring-cloud/spring-cloud-security/auth-server/pom.xml index 82141c1015..b4367935e3 100644 --- a/spring-cloud/spring-cloud-security/auth-server/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-server/pom.xml @@ -1,20 +1,18 @@ + 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 auth-server 0.0.1-SNAPSHOT - - org.springframework.boot - spring-boot-starter-parent - 1.5.9.RELEASE + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../../parent-boot-1 - org.springframework.boot @@ -36,7 +34,12 @@ org.springframework.cloud spring-cloud-starter-oauth2 - 1.1.2.RELEASE + ${spring-cloud-starter-oauth2.version} + + + 1.1.2.RELEASE + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-security/auth-server/src/main/resources/logback.xml b/spring-cloud/spring-cloud-security/auth-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-security/auth-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-stream-starters/boot/pom.xml b/spring-cloud/spring-cloud-stream-starters/boot/pom.xml deleted file mode 100644 index 3e6bc134e3..0000000000 --- a/spring-cloud/spring-cloud-stream-starters/boot/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - 4.0.0 - com.baeldung.twitterhdfs - twitterhdfs - jar - 1.0.0 - - twitterhdfs - - - UTF-8 - UTF-8 - 1.8 - - - - org.springframework.boot - spring-boot-starter-parent - 1.5.8.RELEASE - - - - - - org.springframework.cloud.stream.app - spring-cloud-starter-stream-source-twitterstream - 1.3.1.RELEASE - - - org.springframework.cloud.stream.app - spring-cloud-starter-stream-sink-hdfs - 1.3.1.RELEASE - - - - - javax.servlet - jstl - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - twitterhdfs - - \ No newline at end of file diff --git a/spring-cloud/spring-cloud-stream-starters/twitter/twitter b/spring-cloud/spring-cloud-stream-starters/twitter/twitter new file mode 160000 index 0000000000..f9673ef0c1 --- /dev/null +++ b/spring-cloud/spring-cloud-stream-starters/twitter/twitter @@ -0,0 +1 @@ +Subproject commit f9673ef0c11c51b327555aaca61ee196935f998b diff --git a/spring-cloud/spring-cloud-stream-starters/boot/.gitignore b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/.gitignore similarity index 100% rename from spring-cloud/spring-cloud-stream-starters/boot/.gitignore rename to spring-cloud/spring-cloud-stream-starters/twitterhdfs/.gitignore diff --git a/spring-cloud/spring-cloud-stream-starters/twitterhdfs/pom.xml b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/pom.xml new file mode 100644 index 0000000000..bf725da5cf --- /dev/null +++ b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + com.baeldung.twitterhdfs + twitterhdfs + jar + 1.0.0 + twitterhdfs + + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../../parent-boot-1 + + + + + + org.springframework.cloud.stream.app + spring-cloud-starter-stream-source-twitterstream + ${spring-cloud-starter-stream.version} + + + org.springframework.cloud.stream.app + spring-cloud-starter-stream-sink-hdfs + ${spring-cloud-starter-stream.version} + + + + javax.servlet + jstl + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + twitterhdfs + + + + UTF-8 + UTF-8 + 1.8 + 1.3.1.RELEASE + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-stream-starters/boot/src/main/java/com/baeldung/twitterhdfs/aggregate/AggregateApp.java b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/java/com/baeldung/twitterhdfs/aggregate/AggregateApp.java similarity index 100% rename from spring-cloud/spring-cloud-stream-starters/boot/src/main/java/com/baeldung/twitterhdfs/aggregate/AggregateApp.java rename to spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/java/com/baeldung/twitterhdfs/aggregate/AggregateApp.java diff --git a/spring-cloud/spring-cloud-stream-starters/boot/src/main/java/com/baeldung/twitterhdfs/processor/ProcessorApp.java b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/java/com/baeldung/twitterhdfs/processor/ProcessorApp.java similarity index 100% rename from spring-cloud/spring-cloud-stream-starters/boot/src/main/java/com/baeldung/twitterhdfs/processor/ProcessorApp.java rename to spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/java/com/baeldung/twitterhdfs/processor/ProcessorApp.java diff --git a/spring-cloud/spring-cloud-stream-starters/boot/src/main/java/com/baeldung/twitterhdfs/sink/SinkApp.java b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/java/com/baeldung/twitterhdfs/sink/SinkApp.java similarity index 100% rename from spring-cloud/spring-cloud-stream-starters/boot/src/main/java/com/baeldung/twitterhdfs/sink/SinkApp.java rename to spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/java/com/baeldung/twitterhdfs/sink/SinkApp.java diff --git a/spring-cloud/spring-cloud-stream-starters/boot/src/main/java/com/baeldung/twitterhdfs/source/SourceApp.java b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/java/com/baeldung/twitterhdfs/source/SourceApp.java similarity index 100% rename from spring-cloud/spring-cloud-stream-starters/boot/src/main/java/com/baeldung/twitterhdfs/source/SourceApp.java rename to spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/java/com/baeldung/twitterhdfs/source/SourceApp.java diff --git a/spring-cloud/spring-cloud-stream-starters/boot/src/main/resources/application.properties b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/resources/application.properties similarity index 100% rename from spring-cloud/spring-cloud-stream-starters/boot/src/main/resources/application.properties rename to spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/resources/application.properties diff --git a/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/resources/logback.xml b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-stream/pom.xml b/spring-cloud/spring-cloud-stream/pom.xml index ef691fbeea..d62b959131 100644 --- a/spring-cloud/spring-cloud-stream/pom.xml +++ b/spring-cloud/spring-cloud-stream/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 org.baeldung spring-cloud-stream @@ -39,9 +38,4 @@ - - UTF-8 - 3.7.0 - - diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/resources/logback.xml b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml b/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml index 1bb3d98efb..f97d78099f 100644 --- a/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml +++ b/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml @@ -1,26 +1,18 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung.cloud - springcloudtask + springcloudtaskbatch 0.0.1-SNAPSHOT + springcloudtaskbatch - org.springframework.boot - spring-boot-starter-parent - 1.5.10.RELEASE - + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../../parent-boot-1 - - com.baeldung.TaskDemo - UTF-8 - UTF-8 - 1.8 - 1.2.2.RELEASE - - - org.springframework.boot @@ -67,7 +59,6 @@ - @@ -77,4 +68,12 @@ + + com.baeldung.TaskDemo + UTF-8 + UTF-8 + 1.8 + 1.2.2.RELEASE + + diff --git a/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/main/resources/logback.xml b/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml b/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml index 3aa038b3f3..fdcbabdd51 100644 --- a/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml +++ b/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml @@ -1,31 +1,22 @@ + 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 SpringCloudTaskSink 0.0.1-SNAPSHOT jar - SpringCloudTaskSink Demo project for Spring Boot - org.springframework.boot - spring-boot-starter-parent - 1.5.10.RELEASE - + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../../parent-boot-1 - - UTF-8 - UTF-8 - 1.8 - 1.2.2.RELEASE - Edgware.SR2 - - org.springframework.cloud @@ -54,7 +45,7 @@ org.springframework.cloud spring-cloud-deployer-local - 1.3.0.RELEASE + ${spring-cloud-deployer.version} @@ -85,4 +76,14 @@ + + + UTF-8 + UTF-8 + 1.8 + 1.2.2.RELEASE + Edgware.SR2 + 1.3.0.RELEASE + + diff --git a/spring-cloud/spring-cloud-task/springcloudtasksink/src/main/resources/logback.xml b/spring-cloud/spring-cloud-task/springcloudtasksink/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-task/springcloudtasksink/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-task/springcloudtasksink/src/main/java/com/baeldung/SpringCloudTaskFinal/TaskSinkConfiguration.java b/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/com/baeldung/SpringCloudTaskFinal/TaskSinkConfiguration.java similarity index 100% rename from spring-cloud/spring-cloud-task/springcloudtasksink/src/main/java/com/baeldung/SpringCloudTaskFinal/TaskSinkConfiguration.java rename to spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/com/baeldung/SpringCloudTaskFinal/TaskSinkConfiguration.java diff --git a/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml b/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml index e7fa972f07..9243766b77 100644 --- a/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml +++ b/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml @@ -1,7 +1,10 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + Greeting + jar + Greeting com.baeldung.spring.cloud @@ -9,24 +12,21 @@ 1.0.0-SNAPSHOT - Greeting - jar - org.springframework.boot spring-boot-starter - 1.5.2.RELEASE + ${spring-boot.version} org.springframework spring-web - 4.3.7.RELEASE + ${springframework.version} org.springframework.cloud spring-cloud-starter-zookeeper-discovery - 1.0.3.RELEASE + ${spring-cloud-starter-zookeeper-discovery.version} commons-logging @@ -37,17 +37,17 @@ org.springframework.boot spring-boot-starter-actuator - 1.5.2.RELEASE + ${spring-boot.version} org.springframework.cloud spring-cloud-starter-feign - 1.2.5.RELEASE + ${spring-cloud-starter-feign.version} org.hamcrest hamcrest-core - 1.3 + ${hamcrest.version} test @@ -57,13 +57,16 @@ org.springframework.cloud spring-cloud-dependencies - Brixton.SR7 + ${spring-cloud-dependencies.version} pom import - Greeting + + 1.2.5.RELEASE + 1.3 + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zookeeper/Greeting/src/main/resources/logback.xml b/spring-cloud/spring-cloud-zookeeper/Greeting/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-zookeeper/Greeting/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zookeeper/HelloWorld/pom.xml b/spring-cloud/spring-cloud-zookeeper/HelloWorld/pom.xml index a5b7776438..262b059544 100644 --- a/spring-cloud/spring-cloud-zookeeper/HelloWorld/pom.xml +++ b/spring-cloud/spring-cloud-zookeeper/HelloWorld/pom.xml @@ -1,29 +1,32 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + HelloWorld + jar + HelloWorld + com.baeldung.spring.cloud spring-cloud-zookeeper 1.0.0-SNAPSHOT - HelloWorld - jar + org.springframework.boot spring-boot-starter - 1.5.2.RELEASE + ${spring-boot.version} org.springframework spring-web - 4.3.7.RELEASE + ${springframework.version} org.springframework.cloud spring-cloud-starter-zookeeper-discovery - 1.0.3.RELEASE + ${spring-cloud-starter-zookeeper-discovery.version} commons-logging @@ -38,7 +41,7 @@ org.springframework.cloud spring-cloud-dependencies - Brixton.SR7 + ${spring-cloud-dependencies.version} pom import @@ -53,5 +56,5 @@ - HelloWorld + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zookeeper/HelloWorld/src/main/resources/logback.xml b/spring-cloud/spring-cloud-zookeeper/HelloWorld/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-zookeeper/HelloWorld/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zookeeper/pom.xml b/spring-cloud/spring-cloud-zookeeper/pom.xml index 091b8c4987..4535c2072d 100644 --- a/spring-cloud/spring-cloud-zookeeper/pom.xml +++ b/spring-cloud/spring-cloud-zookeeper/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-cloud-zookeeper pom @@ -16,4 +16,10 @@ HelloWorld + + 1.5.2.RELEASE + 4.3.7.RELEASE + 1.0.3.RELEASE + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-client/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-client/pom.xml index 876279262c..6a00b279c8 100644 --- a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-client/pom.xml +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-client/pom.xml @@ -1,9 +1,7 @@ - + 4.0.0 - eureka-client 1.0.0-SNAPSHOT jar @@ -42,9 +40,4 @@ - - Brixton.SR7 - 1.2.3.RELEASE - 1.4.2.RELEASE - diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-server/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-server/pom.xml index 8bf8a0da46..9db3204f64 100644 --- a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-server/pom.xml +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-server/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 eureka-server @@ -42,8 +41,5 @@ - - Brixton.SR7 - 1.2.3.RELEASE - + diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/pom.xml index b8e3c867e3..7e864499d4 100644 --- a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/pom.xml +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/pom.xml @@ -1,15 +1,12 @@ - + 4.0.0 - + com.baeldung.spring.cloud spring-cloud-zuul-eureka-integration 1.0.0-SNAPSHOT - pom - Spring Cloud Zuul and Eureka Integration Spring Cloud Zuul and Eureka Integration diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml index 3d1bd412c0..9c27affb8b 100644 --- a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 eureka-client 1.0.0-SNAPSHOT @@ -40,9 +39,4 @@ - - Brixton.SR7 - 1.2.3.RELEASE - 1.4.2.RELEASE - diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/main/resources/logback.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml index 902232c843..d694c9058b 100644 --- a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 eureka-server 1.0.0-SNAPSHOT @@ -41,8 +40,4 @@ - - Brixton.SR7 - 1.2.3.RELEASE - diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/main/resources/logback.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/pom.xml index ef16a6a885..f4166c7d34 100644 --- a/spring-cloud/spring-cloud-zuul-eureka-integration/pom.xml +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/pom.xml @@ -24,8 +24,6 @@ - UTF-8 - 3.7.0 1.4.2.RELEASE 1.10 1.2.10 diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml index 19cb2ea5b8..103b8334d3 100644 --- a/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml @@ -1,12 +1,14 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + zuul-server + com.baeldung.spring.cloud spring-cloud-zuul-eureka-integration 1.0.0-SNAPSHOT - zuul-server + org.springframework.boot @@ -35,6 +37,7 @@ spring-boot-starter-security + @@ -46,4 +49,5 @@ + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/main/resources/logback.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-core/README.md b/spring-core/README.md index 5f50b35553..c0577b4ebc 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -14,3 +14,9 @@ - [Injecting Prototype Beans into a Singleton Instance in Spring](http://www.baeldung.com/spring-inject-prototype-bean-into-singleton) - [How to Inject a Property Value Into a Class Not Managed by Spring?](http://www.baeldung.com/inject-properties-value-non-spring-class) - [@Lookup Annotation in Spring](http://www.baeldung.com/spring-lookup) +- [BeanNameAware and BeanFactoryAware Interfaces in Spring](http://www.baeldung.com/spring-bean-name-factory-aware) +- [Spring – Injecting Collections](http://www.baeldung.com/spring-injecting-collections) +- [Access a File from the Classpath in a Spring Application](http://www.baeldung.com/spring-classpath-file-access) +- [Controlling Bean Creation Order with @DependsOn Annotation](http://www.baeldung.com/spring-depends-on) +- [Spring Autowiring of Generic Types](https://www.baeldung.com/spring-autowire-generics) +- [Spring Application Context Events](https://www.baeldung.com/spring-context-events) diff --git a/spring-core/pom.xml b/spring-core/pom.xml index 93ff73bb37..60f3262f08 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -1,104 +1,90 @@ - + - 4.0.0 - com.baeldung - spring-core - 0.0.1-SNAPSHOT - war - spring-core + 4.0.0 + com.baeldung + spring-core + 0.0.1-SNAPSHOT + war + spring-core - - com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring - + + com.baeldung + parent-spring-4 + 0.0.1-SNAPSHOT + ../parent-spring-4 + - - - org.mockito - mockito-all - ${mockito.version} - - - org.springframework - spring-test - ${spring.version} - - - org.springframework - spring-beans - ${spring.version} - - - org.springframework - spring-context - ${spring.version} - - - javax.inject - javax.inject - ${javax.inject.version} - - - com.google.guava - guava - ${guava.version} - - - org.projectlombok - lombok - ${lombok.version} - - - org.springframework.boot - spring-boot-starter - 1.5.2.RELEASE - - - org.springframework.boot - spring-boot-test - ${mockito.spring.boot.version} - test - - - commons-io - commons-io - ${commons.io.version} - - + + + org.springframework + spring-test + ${spring.version} + + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-context + ${spring.version} + + + javax.inject + javax.inject + ${javax.inject.version} + + + com.google.guava + guava + ${guava.version} + + + org.projectlombok + lombok + ${lombok.version} + + + org.springframework.boot + spring-boot-starter + ${spring-boot.version} + + + org.springframework.boot + spring-boot-test + ${mockito.spring.boot.version} + test + + + commons-io + commons-io + ${commons.io.version} + + - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - false - - - - + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + - - 1.10.19 - 1.4.4.RELEASE - 4.3.4.RELEASE - 1 - 20.0 - 2.6 - 1.16.12 - 2.5 - - - - - java.net - https://maven.java.net/content/repositories/releases/ - - + + 1.4.4.RELEASE + 1 + 20.0 + 2.6 + 1.16.12 + 2.5 + 1.5.2.RELEASE + \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/collection/BaeldungBean.java b/spring-core/src/main/java/com/baeldung/collection/BaeldungBean.java new file mode 100644 index 0000000000..6d7351df02 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/collection/BaeldungBean.java @@ -0,0 +1,18 @@ +package com.baeldung.collection; + +/** + * Created by Gebruiker on 5/22/2018. + */ +public class BaeldungBean { + + private String name; + + public BaeldungBean(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } +} diff --git a/spring-core/src/main/java/com/baeldung/collection/CollectionConfig.java b/spring-core/src/main/java/com/baeldung/collection/CollectionConfig.java new file mode 100644 index 0000000000..fbae2963e5 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/collection/CollectionConfig.java @@ -0,0 +1,50 @@ +package com.baeldung.collection; + +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; + +import java.util.*; + +@Configuration +public class CollectionConfig { + + @Bean + public CollectionsBean getCollectionsBean() { + return new CollectionsBean(new HashSet<>(Arrays.asList("John", "Adam", "Harry"))); + } + + @Bean + public List nameList(){ + return Arrays.asList("John", "Adam", "Harry", null); + } + + @Bean + public Map nameMap(){ + Map nameMap = new HashMap<>(); + nameMap.put(1, "John"); + nameMap.put(2, "Adam"); + nameMap.put(3, "Harry"); + return nameMap; + } + + @Bean + @Qualifier("CollectionsBean") + @Order(2) + public BaeldungBean getElement() { + return new BaeldungBean("John"); + } + + @Bean + @Order(3) + public BaeldungBean getAnotherElement() { + return new BaeldungBean("Adam"); + } + + @Bean + @Order(1) + public BaeldungBean getOneMoreElement() { + return new BaeldungBean("Harry"); + } +} diff --git a/spring-core/src/main/java/com/baeldung/collection/CollectionInjectionDemo.java b/spring-core/src/main/java/com/baeldung/collection/CollectionInjectionDemo.java new file mode 100644 index 0000000000..2e0d9eb8d8 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/collection/CollectionInjectionDemo.java @@ -0,0 +1,20 @@ +package com.baeldung.collection; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +/** + * Created by Gebruiker on 5/18/2018. + */ +public class CollectionInjectionDemo { + + public static void main(String[] args) { + + ApplicationContext context = new AnnotationConfigApplicationContext(CollectionConfig.class); + CollectionsBean collectionsBean = context.getBean(CollectionsBean.class); + collectionsBean.printNameList(); + collectionsBean.printNameSet(); + collectionsBean.printNameMap(); + collectionsBean.printBeanList(); + } +} diff --git a/spring-core/src/main/java/com/baeldung/collection/CollectionsBean.java b/spring-core/src/main/java/com/baeldung/collection/CollectionsBean.java new file mode 100644 index 0000000000..a0e985267f --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/collection/CollectionsBean.java @@ -0,0 +1,54 @@ +package com.baeldung.collection; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Created by Gebruiker on 5/18/2018. + */ +public class CollectionsBean { + + @Autowired + private List nameList; + + private Set nameSet; + + private Map nameMap; + + @Autowired(required = false) + @Qualifier("CollectionsBean") + private List beanList = new ArrayList<>(); + + public CollectionsBean() { + } + + public CollectionsBean(Set strings) { + this.nameSet = strings; + } + + @Autowired + public void setNameMap(Map nameMap) { + this.nameMap = nameMap; + } + + public void printNameList() { + System.out.println(nameList); + } + + public void printNameSet() { + System.out.println(nameSet); + } + + public void printNameMap() { + System.out.println(nameMap); + } + + public void printBeanList() { + System.out.println(beanList); + } +} diff --git a/spring-core/src/main/java/com/baeldung/config/scope/AppConfigFunctionBean.java b/spring-core/src/main/java/com/baeldung/config/scope/AppConfigFunctionBean.java new file mode 100644 index 0000000000..a3c5445698 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/config/scope/AppConfigFunctionBean.java @@ -0,0 +1,31 @@ +package com.baeldung.config.scope; + +import java.util.function.Function; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Scope; + +import com.baeldung.scope.prototype.PrototypeBean; +import com.baeldung.scope.singletone.SingletonFunctionBean; + +@Configuration +public class AppConfigFunctionBean { + + @Bean + public Function beanFactory() { + return name -> prototypeBeanWithParam(name); + } + + @Bean + @Scope(value = "prototype") + public PrototypeBean prototypeBeanWithParam(String name) { + return new PrototypeBean(name); + } + + @Bean + public SingletonFunctionBean singletonFunctionBean() { + return new SingletonFunctionBean(); + } + +} diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/app/CustomConfiguration.java b/spring-core/src/main/java/com/baeldung/dependency/exception/app/CustomConfiguration.java new file mode 100644 index 0000000000..4366cb617a --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependency/exception/app/CustomConfiguration.java @@ -0,0 +1,13 @@ +package com.baeldung.dependency.exception.app; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackages = "com.baeldung.dependency.exception") +public class CustomConfiguration { + public static void main(String[] args) { + SpringApplication.run(CustomConfiguration.class, args); + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/app/PurchaseDeptService.java b/spring-core/src/main/java/com/baeldung/dependency/exception/app/PurchaseDeptService.java new file mode 100644 index 0000000000..e0fe01acdd --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependency/exception/app/PurchaseDeptService.java @@ -0,0 +1,14 @@ +package com.baeldung.dependency.exception.app; + +import com.baeldung.dependency.exception.repository.InventoryRepository; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +@Service +public class PurchaseDeptService { + private InventoryRepository repository; + + public PurchaseDeptService(@Qualifier("dresses") InventoryRepository repository) { + this.repository = repository; + } +} \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/repository/DressRepository.java b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/DressRepository.java new file mode 100644 index 0000000000..5a1371ce04 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/DressRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.dependency.exception.repository; + +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Repository; + +@Qualifier("dresses") +@Repository +public class DressRepository implements InventoryRepository { +} diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/repository/InventoryRepository.java b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/InventoryRepository.java new file mode 100644 index 0000000000..ccb2ad9c32 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/InventoryRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.dependency.exception.repository; + +import org.springframework.stereotype.Repository; + +@Repository +public interface InventoryRepository { +} diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/repository/ShoeRepository.java b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/ShoeRepository.java new file mode 100644 index 0000000000..227d8934b6 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/ShoeRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.dependency.exception.repository; + +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Repository; + +@Qualifier("shoes") +@Repository +public class ShoeRepository implements InventoryRepository { +} diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/annotation/CarQualifier.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/annotation/CarQualifier.java new file mode 100644 index 0000000000..cd7f81c0fb --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/annotation/CarQualifier.java @@ -0,0 +1,15 @@ +package com.baeldung.dependencyinjectiontypes.annotation; + +import org.springframework.beans.factory.annotation.Qualifier; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.FIELD, ElementType.METHOD, + ElementType.TYPE, ElementType.PARAMETER}) +@Retention(RetentionPolicy.RUNTIME) +@Qualifier +public @interface CarQualifier { +} diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/app/CustomConfiguration.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/app/CustomConfiguration.java new file mode 100644 index 0000000000..841a8d4656 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/app/CustomConfiguration.java @@ -0,0 +1,39 @@ +package com.baeldung.dependencyinjectiontypes.app; + +import com.baeldung.dependencyinjectiontypes.annotation.CarQualifier; +import com.baeldung.dependencyinjectiontypes.model.Car; +import com.baeldung.dependencyinjectiontypes.model.CarHandler; +import com.baeldung.dependencyinjectiontypes.model.Motorcycle; +import com.baeldung.dependencyinjectiontypes.model.Vehicle; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan("com.baeldung.dependencyinjectiontypes.model") +public class CustomConfiguration { + @Bean + @CarQualifier + public Car getMercedes() { + return new Car("E280", "Mercedes", "Diesel"); + } + + public static void main(String[] args) throws NoSuchFieldException { + ConfigurableApplicationContext context = SpringApplication.run(CustomConfiguration.class, args); + CarHandler carHandler = context.getBean(CarHandler.class); + carHandler.getVehicles().forEach(System.out::println); + } + + @Bean + @CarQualifier + public Car getBmw() { + return new Car("M5", "BMW", "Petrol"); + } + + @Bean + public Motorcycle getSuzuki() { + return new Motorcycle("Yamaguchi", "Suzuki", true); + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Car.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Car.java new file mode 100644 index 0000000000..a09d89248b --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Car.java @@ -0,0 +1,25 @@ +package com.baeldung.dependencyinjectiontypes.model; + +public class Car extends Vehicle { + private String engineType; + + public Car(String name, String manufacturer, String engineType) { + super(name, manufacturer); + this.engineType = engineType; + } + + public String getEngineType() { + return engineType; + } + + public void setEngineType(String engineType) { + this.engineType = engineType; + } + + @Override + public String toString() { + return "Car{" + + "engineType='" + engineType + '\'' + + '}'; + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/CarHandler.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/CarHandler.java new file mode 100644 index 0000000000..f5d581ef0a --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/CarHandler.java @@ -0,0 +1,26 @@ +package com.baeldung.dependencyinjectiontypes.model; + +import com.baeldung.dependencyinjectiontypes.annotation.CarQualifier; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ResolvableType; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +public class CarHandler { + + @Autowired + @CarQualifier + private List vehicles; + + public List getVehicles() throws NoSuchFieldException { + ResolvableType vehiclesType = ResolvableType.forField(getClass().getDeclaredField("vehicles")); + System.out.println(vehiclesType); + ResolvableType type = vehiclesType.getGeneric(); + System.out.println(type); + Class aClass = type.resolve(); + System.out.println(aClass); + return this.vehicles; + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Motorcycle.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Motorcycle.java new file mode 100644 index 0000000000..ce5e97fb6d --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Motorcycle.java @@ -0,0 +1,25 @@ +package com.baeldung.dependencyinjectiontypes.model; + +public class Motorcycle extends Vehicle { + private boolean twoWheeler; + + public Motorcycle(String name, String manufacturer, boolean twoWheeler) { + super(name, manufacturer); + this.twoWheeler = true; + } + + public boolean isTwoWheeler() { + return twoWheeler; + } + + public void setTwoWheeler(boolean twoWheeler) { + this.twoWheeler = twoWheeler; + } + + @Override + public String toString() { + return "Motorcycle{" + + "twoWheeler=" + twoWheeler + + '}'; + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Vehicle.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Vehicle.java new file mode 100644 index 0000000000..cb3dca764e --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Vehicle.java @@ -0,0 +1,28 @@ +package com.baeldung.dependencyinjectiontypes.model; + +public abstract class Vehicle { + private String name; + private String manufacturer; + + + public Vehicle(String name, String manufacturer) { + this.name = name; + this.manufacturer = manufacturer; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getManufacturer() { + return manufacturer; + } + + public void setManufacturer(String manufacturer) { + this.manufacturer = manufacturer; + } +} \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/dependson/DriverApplication.java b/spring-core/src/main/java/com/baeldung/dependson/DriverApplication.java new file mode 100644 index 0000000000..166f388aa3 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependson/DriverApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.dependson; + +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import com.baeldung.dependson.config.Config; +import com.baeldung.dependson.file.processor.FileProcessor; + +public class DriverApplication { + public static void main(String[] args) { + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class); + ctx.getBean(FileProcessor.class); + ctx.close(); + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependson/config/Config.java b/spring-core/src/main/java/com/baeldung/dependson/config/Config.java new file mode 100644 index 0000000000..8d96707ba6 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependson/config/Config.java @@ -0,0 +1,38 @@ +package com.baeldung.dependson.config; + +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.DependsOn; +import org.springframework.context.annotation.Lazy; + +import com.baeldung.dependson.file.processor.FileProcessor; +import com.baeldung.dependson.file.reader.FileReader; +import com.baeldung.dependson.file.writer.FileWriter; +import com.baeldung.dependson.shared.File; + +@Configuration +@ComponentScan("com.baeldung.dependson") +public class Config { + + @Autowired + File file; + + @Bean("fileProcessor") + @DependsOn({"fileReader","fileWriter"}) + @Lazy + public FileProcessor fileProcessor(){ + return new FileProcessor(file); + } + + @Bean("fileReader") + public FileReader fileReader(){ + return new FileReader(file); + } + + @Bean("fileWriter") + public FileWriter fileWriter(){ + return new FileWriter(file); + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependson/file/processor/FileProcessor.java b/spring-core/src/main/java/com/baeldung/dependson/file/processor/FileProcessor.java new file mode 100644 index 0000000000..f5d55dc032 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependson/file/processor/FileProcessor.java @@ -0,0 +1,19 @@ +package com.baeldung.dependson.file.processor; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.baeldung.dependson.file.reader.FileReader; +import com.baeldung.dependson.file.writer.FileWriter; +import com.baeldung.dependson.shared.File; + +public class FileProcessor { + + File file; + + public FileProcessor(File file){ + this.file = file; + if(file.getText().contains("write") && file.getText().contains("read")){ + file.setText("processed"); + } + } +} \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/dependson/file/reader/FileReader.java b/spring-core/src/main/java/com/baeldung/dependson/file/reader/FileReader.java new file mode 100644 index 0000000000..b6ff446534 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependson/file/reader/FileReader.java @@ -0,0 +1,12 @@ +package com.baeldung.dependson.file.reader; + +import com.baeldung.dependson.shared.File; + +public class FileReader { + + public FileReader(File file) { + file.setText("read"); + } + + public void readFile() {} +} diff --git a/spring-core/src/main/java/com/baeldung/dependson/file/writer/FileWriter.java b/spring-core/src/main/java/com/baeldung/dependson/file/writer/FileWriter.java new file mode 100644 index 0000000000..f251166c80 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependson/file/writer/FileWriter.java @@ -0,0 +1,13 @@ +package com.baeldung.dependson.file.writer; + +import com.baeldung.dependson.shared.File; + + +public class FileWriter { + + public FileWriter(File file){ + file.setText("write"); + } + + public void writeFile(){} +} diff --git a/spring-core/src/main/java/com/baeldung/dependson/shared/File.java b/spring-core/src/main/java/com/baeldung/dependson/shared/File.java new file mode 100644 index 0000000000..c1b1badc43 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependson/shared/File.java @@ -0,0 +1,17 @@ +package com.baeldung.dependson.shared; + +import org.springframework.stereotype.Service; + +@Service +public class File { + + private String text = ""; + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = this.text+text; + } +} diff --git a/spring-core/src/main/java/com/baeldung/event/listener/ContextEventListener.java b/spring-core/src/main/java/com/baeldung/event/listener/ContextEventListener.java new file mode 100644 index 0000000000..a2603bb95c --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/event/listener/ContextEventListener.java @@ -0,0 +1,24 @@ +package com.baeldung.event.listener; + +import org.springframework.context.event.ContextStartedEvent; +import org.springframework.context.event.ContextStoppedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +@Component +public class ContextEventListener { + + @Order(2) + @EventListener + public void handleContextRefreshEvent(ContextStartedEvent ctxStartEvt) { + System.out.println("Context Start Event received."); + } + + @Order(1) + @EventListener(classes = { ContextStartedEvent.class, ContextStoppedEvent.class }) + public void handleMultipleEvents() { + System.out.println("Multi-event listener invoked"); + } + +} diff --git a/spring-core/src/main/java/com/baeldung/event/listener/EventConfig.java b/spring-core/src/main/java/com/baeldung/event/listener/EventConfig.java new file mode 100644 index 0000000000..f2a3af7640 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/event/listener/EventConfig.java @@ -0,0 +1,10 @@ +package com.baeldung.event.listener; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages = "com.baeldung.event.listener") +public class EventConfig { + +} diff --git a/spring-core/src/main/java/com/baeldung/event/listener/SpringRunner.java b/spring-core/src/main/java/com/baeldung/event/listener/SpringRunner.java new file mode 100644 index 0000000000..bbe4693900 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/event/listener/SpringRunner.java @@ -0,0 +1,12 @@ +package com.baeldung.event.listener; + +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +public class SpringRunner { + + public static void main(String[] args) { + ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(EventConfig.class); + ctx.start(); + } +} diff --git a/spring-core/src/main/java/com/baeldung/scope/AppConfig.java b/spring-core/src/main/java/com/baeldung/scope/AppConfig.java index 5c8c539e7a..33a9c5c21e 100644 --- a/spring-core/src/main/java/com/baeldung/scope/AppConfig.java +++ b/spring-core/src/main/java/com/baeldung/scope/AppConfig.java @@ -40,4 +40,5 @@ public class AppConfig { public SingletonObjectFactoryBean singletonObjectFactoryBean() { return new SingletonObjectFactoryBean(); } + } diff --git a/spring-core/src/main/java/com/baeldung/scope/AppProxyScopeConfig.java b/spring-core/src/main/java/com/baeldung/scope/AppProxyScopeConfig.java index fc7a30471c..9f1874375e 100644 --- a/spring-core/src/main/java/com/baeldung/scope/AppProxyScopeConfig.java +++ b/spring-core/src/main/java/com/baeldung/scope/AppProxyScopeConfig.java @@ -2,6 +2,7 @@ package com.baeldung.scope; import com.baeldung.scope.prototype.PrototypeBean; import com.baeldung.scope.singletone.SingletonBean; + import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.*; @@ -19,4 +20,5 @@ public class AppProxyScopeConfig { public SingletonBean singletonBean() { return new SingletonBean(); } + } diff --git a/spring-core/src/main/java/com/baeldung/scope/prototype/PrototypeBean.java b/spring-core/src/main/java/com/baeldung/scope/prototype/PrototypeBean.java index cfccb62e45..c87c7a8d44 100644 --- a/spring-core/src/main/java/com/baeldung/scope/prototype/PrototypeBean.java +++ b/spring-core/src/main/java/com/baeldung/scope/prototype/PrototypeBean.java @@ -9,4 +9,20 @@ public class PrototypeBean { public PrototypeBean() { logger.info("Prototype instance created"); } + + private String name; + + public PrototypeBean(String name) { + this.name = name; + logger.info("Prototype instance " + name + " created"); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } diff --git a/spring-core/src/main/java/com/baeldung/scope/singletone/SingletonFunctionBean.java b/spring-core/src/main/java/com/baeldung/scope/singletone/SingletonFunctionBean.java new file mode 100644 index 0000000000..8cdc56a6fa --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/scope/singletone/SingletonFunctionBean.java @@ -0,0 +1,19 @@ +package com.baeldung.scope.singletone; + +import java.util.function.Function; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.baeldung.scope.prototype.PrototypeBean; + +public class SingletonFunctionBean { + + @Autowired + private Function beanFactory; + + public PrototypeBean getPrototypeInstance(String name) { + PrototypeBean bean = beanFactory.apply(name); + return bean; + } + +} diff --git a/spring-core/src/main/resources/logback.xml b/spring-core/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-core/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionIntegrationTest.java b/spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionIntegrationTest.java new file mode 100644 index 0000000000..faaadfcbc3 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionIntegrationTest.java @@ -0,0 +1,35 @@ +package com.baeldung.dependencyinjectiontypes; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class DependencyInjectionIntegrationTest { + + @Test + public void givenAutowiredAnnotation_WhenSetOnSetter_ThenDependencyValid() { + + ApplicationContext context = new ClassPathXmlApplicationContext("dependencyinjectiontypes-context.xml"); + ArticleWithSetterInjection article = (ArticleWithSetterInjection) context.getBean("articleWithSetterInjectionBean"); + + String originalText = "This is a text !"; + String formattedArticle = article.format(originalText); + + assertTrue(originalText.toUpperCase().equals(formattedArticle)); + } + + @Test + public void givenAutowiredAnnotation_WhenSetOnConstructor_ThenDependencyValid() { + + ApplicationContext context = new ClassPathXmlApplicationContext("dependencyinjectiontypes-context.xml"); + ArticleWithConstructorInjection article = (ArticleWithConstructorInjection) context.getBean("articleWithConstructorInjectionBean"); + + String originalText = "This is a text !"; + String formattedArticle = article.format(originalText); + + assertTrue(originalText.toUpperCase().equals(formattedArticle)); + } + +} diff --git a/spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionTest.java b/spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionTest.java deleted file mode 100644 index 57c1927e58..0000000000 --- a/spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.dependencyinjectiontypes; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class DependencyInjectionTest { - - @Test - public void givenAutowiredAnnotation_WhenSetOnSetter_ThenDependencyValid() { - - ApplicationContext context = new ClassPathXmlApplicationContext("dependencyinjectiontypes-context.xml"); - ArticleWithSetterInjection article = (ArticleWithSetterInjection) context.getBean("articleWithSetterInjectionBean"); - - String originalText = "This is a text !"; - String formattedArticle = article.format(originalText); - - assertTrue(originalText.toUpperCase().equals(formattedArticle)); - } - - @Test - public void givenAutowiredAnnotation_WhenSetOnConstructor_ThenDependencyValid() { - - ApplicationContext context = new ClassPathXmlApplicationContext("dependencyinjectiontypes-context.xml"); - ArticleWithConstructorInjection article = (ArticleWithConstructorInjection) context.getBean("articleWithConstructorInjectionBean"); - - String originalText = "This is a text !"; - String formattedArticle = article.format(originalText); - - assertTrue(originalText.toUpperCase().equals(formattedArticle)); - } - -} diff --git a/spring-core/src/test/java/com/baeldung/dependson/config/TestConfig.java b/spring-core/src/test/java/com/baeldung/dependson/config/TestConfig.java new file mode 100644 index 0000000000..f4b2e39ebc --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/dependson/config/TestConfig.java @@ -0,0 +1,59 @@ +package com.baeldung.dependson.config; + +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.DependsOn; +import org.springframework.context.annotation.Lazy; + +import com.baeldung.dependson.file.processor.FileProcessor; +import com.baeldung.dependson.file.reader.FileReader; +import com.baeldung.dependson.file.writer.FileWriter; +import com.baeldung.dependson.shared.File; + +@Configuration +@ComponentScan("com.baeldung.dependson") +public class TestConfig { + + @Autowired + File file; + + @Bean("fileProcessor") + @DependsOn({"fileReader","fileWriter"}) + @Lazy + public FileProcessor fileProcessor(){ + return new FileProcessor(file); + } + + @Bean("fileReader") + public FileReader fileReader(){ + return new FileReader(file); + } + + @Bean("fileWriter") + public FileWriter fileWriter(){ + return new FileWriter(file); + } + + @Bean("dummyFileProcessor") + @DependsOn({"dummyfileWriter"}) + @Lazy + public FileProcessor dummyFileProcessor(){ + return new FileProcessor(file); + } + + @Bean("dummyFileProcessorCircular") + @DependsOn({"dummyFileReaderCircular"}) + @Lazy + public FileProcessor dummyFileProcessorCircular(){ + return new FileProcessor(file); + } + + @Bean("dummyFileReaderCircular") + @DependsOn({"dummyFileProcessorCircular"}) + @Lazy + public FileReader dummyFileReaderCircular(){ + return new FileReader(file); + } +} diff --git a/spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorIntegrationTest.java b/spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorIntegrationTest.java new file mode 100644 index 0000000000..5de53192df --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorIntegrationTest.java @@ -0,0 +1,41 @@ +package com.baeldung.dependson.processor; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.dependson.config.TestConfig; +import com.baeldung.dependson.shared.File; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = TestConfig.class) +public class FileProcessorIntegrationTest { + + @Autowired + ApplicationContext context; + + @Autowired + File file; + + @Test + public void whenAllBeansCreated_FileTextEndsWithProcessed() { + context.getBean("fileProcessor"); + assertTrue(file.getText().endsWith("processed")); + } + + @Test(expected=BeanCreationException.class) + public void whenDependentBeanNotAvailable_ThrowsNoSuchBeanDefinitionException(){ + context.getBean("dummyFileProcessor"); + } + + @Test(expected=BeanCreationException.class) + public void whenCircularDependency_ThrowsBeanCreationException(){ + context.getBean("dummyFileReaderCircular"); + } +} diff --git a/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionIntegrationTest.java b/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionIntegrationTest.java new file mode 100644 index 0000000000..4bfb3c5de4 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionIntegrationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.di.spring; + +import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class BeanInjectionIntegrationTest { + + private ApplicationContext applicationContext; + + @Before + public void setUp() throws Exception { + applicationContext = new ClassPathXmlApplicationContext("com.baeldung.di.spring.xml"); + } + + @Test + public void singletonBean_getBean_returnsSingleInstance() { + final IndexApp indexApp1 = applicationContext.getBean("indexApp", IndexApp.class); + final IndexApp indexApp2 = applicationContext.getBean("indexApp", IndexApp.class); + assertEquals(indexApp1, indexApp2); + } + + @Test + public void getBean_returnsInstance() { + final IndexApp indexApp = applicationContext.getBean("indexApp", IndexApp.class); + assertNotNull(indexApp); + } + +} diff --git a/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java b/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java deleted file mode 100644 index 1660b99726..0000000000 --- a/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.di.spring; - -import static org.junit.Assert.*; -import org.junit.Before; -import org.junit.Test; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class BeanInjectionTest { - - private ApplicationContext applicationContext; - - @Before - public void setUp() throws Exception { - applicationContext = new ClassPathXmlApplicationContext("com.baeldung.di.spring.xml"); - } - - @Test - public void singletonBean_getBean_returnsSingleInstance() { - final IndexApp indexApp1 = applicationContext.getBean("indexApp", IndexApp.class); - final IndexApp indexApp2 = applicationContext.getBean("indexApp", IndexApp.class); - assertEquals(indexApp1, indexApp2); - } - - @Test - public void getBean_returnsInstance() { - final IndexApp indexApp = applicationContext.getBean("indexApp", IndexApp.class); - assertNotNull(indexApp); - } - -} diff --git a/spring-core/src/test/java/com/baeldung/methodinjections/StudentIntegrationTest.java b/spring-core/src/test/java/com/baeldung/methodinjections/StudentIntegrationTest.java new file mode 100644 index 0000000000..5d326a99dd --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/methodinjections/StudentIntegrationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.methodinjections; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class StudentIntegrationTest { + + @Test + public void whenLookupMethodCalled_thenNewInstanceReturned() { + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); + Student student1 = context.getBean("studentBean", Student.class); + Student student2 = context.getBean("studentBean", Student.class); + + Assert.assertEquals(student1, student2); + Assert.assertNotEquals(student1.getNotification("Alex"), student2.getNotification("Bethany")); + context.close(); + } + + @Test + public void whenAbstractGetterMethodInjects_thenNewInstanceReturned() { + ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); + StudentServices services = context.getBean("studentServices", StudentServices.class); + + Assert.assertEquals("PASS", services.appendMark("Alex", 76)); + Assert.assertEquals("FAIL", services.appendMark("Bethany", 44)); + Assert.assertEquals("PASS", services.appendMark("Claire", 96)); + context.close(); + } +} diff --git a/spring-core/src/test/java/com/baeldung/methodinjections/StudentTest.java b/spring-core/src/test/java/com/baeldung/methodinjections/StudentTest.java deleted file mode 100644 index 8c04ef472e..0000000000 --- a/spring-core/src/test/java/com/baeldung/methodinjections/StudentTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.methodinjections; - -import org.junit.Assert; -import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class StudentTest { - - @Test - public void whenLookupMethodCalled_thenNewInstanceReturned() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); - Student student1 = context.getBean("studentBean", Student.class); - Student student2 = context.getBean("studentBean", Student.class); - - Assert.assertEquals(student1, student2); - Assert.assertNotEquals(student1.getNotification("Alex"), student2.getNotification("Bethany")); - context.close(); - } - - @Test - public void whenAbstractGetterMethodInjects_thenNewInstanceReturned() { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); - StudentServices services = context.getBean("studentServices", StudentServices.class); - - Assert.assertEquals("PASS", services.appendMark("Alex", 76)); - Assert.assertEquals("FAIL", services.appendMark("Bethany", 44)); - Assert.assertEquals("PASS", services.appendMark("Claire", 96)); - context.close(); - } -} diff --git a/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java new file mode 100644 index 0000000000..38e8304f0f --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java @@ -0,0 +1,101 @@ +package com.baeldung.resource; + +import static org.junit.Assert.assertEquals; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.file.Files; +import java.util.stream.Collectors; + +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.context.ApplicationContext; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.util.ResourceUtils; + +/** + * Test class illustrating various methods of accessing a file from the classpath using Resource. + * @author tritty + * + */ + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class) +public class SpringResourceIntegrationTest { + /** + * Resource loader instance for lazily loading resources. + */ + @Autowired + private ResourceLoader resourceLoader; + + @Autowired + private ApplicationContext appContext; + + /** + * Injecting resource + */ + @Value("classpath:data/employees.dat") + private Resource resourceFile; + + /** + * Data in data/employee.dat + */ + private static final String EMPLOYEES_EXPECTED = "Joe Employee,Jan Employee,James T. Employee"; + + @Test + public void whenResourceLoader_thenReadSuccessful() throws IOException { + final Resource resource = resourceLoader.getResource("classpath:data/employees.dat"); + final String employees = new String(Files.readAllBytes(resource.getFile() + .toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); + } + + @Test + public void whenApplicationContext_thenReadSuccessful() throws IOException { + final Resource resource = appContext.getResource("classpath:data/employees.dat"); + final String employees = new String(Files.readAllBytes(resource.getFile() + .toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); + } + + @Test + public void whenAutowired_thenReadSuccessful() throws IOException { + final String employees = new String(Files.readAllBytes(resourceFile.getFile() + .toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); + } + + @Test + public void whenResourceUtils_thenReadSuccessful() throws IOException { + final File employeeFile = ResourceUtils.getFile("classpath:data/employees.dat"); + final String employees = new String(Files.readAllBytes(employeeFile.toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); + } + + @Test + public void whenResourceAsStream_thenReadSuccessful() throws IOException { + final InputStream resource = new ClassPathResource("data/employees.dat").getInputStream(); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource))) { + final String employees = reader.lines() + .collect(Collectors.joining("\n")); + assertEquals(EMPLOYEES_EXPECTED, employees); + } + } + + @Test + public void whenResourceAsFile_thenReadSuccessful() throws IOException { + final File resource = new ClassPathResource("data/employees.dat").getFile(); + final String employees = new String(Files.readAllBytes(resource.toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); + } +} diff --git a/spring-core/src/test/java/com/baeldung/scope/PrototypeBeanInjectionIntegrationTest.java b/spring-core/src/test/java/com/baeldung/scope/PrototypeBeanInjectionIntegrationTest.java new file mode 100644 index 0000000000..d0c2733765 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/scope/PrototypeBeanInjectionIntegrationTest.java @@ -0,0 +1,63 @@ +package com.baeldung.scope; + +import com.baeldung.scope.prototype.PrototypeBean; +import com.baeldung.scope.singletone.SingletonFunctionBean; +import com.baeldung.scope.singletone.SingletonLookupBean; +import com.baeldung.scope.singletone.SingletonObjectFactoryBean; +import com.baeldung.scope.singletone.SingletonProviderBean; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.support.AbstractApplicationContext; +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 = AppConfig.class) +public class PrototypeBeanInjectionIntegrationTest { + + @Test + public void givenPrototypeInjection_WhenObjectFactory_ThenNewInstanceReturn() { + + AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); + + SingletonObjectFactoryBean firstContext = context.getBean(SingletonObjectFactoryBean.class); + SingletonObjectFactoryBean secondContext = context.getBean(SingletonObjectFactoryBean.class); + + PrototypeBean firstInstance = firstContext.getPrototypeInstance(); + PrototypeBean secondInstance = secondContext.getPrototypeInstance(); + + Assert.assertTrue("New instance expected", firstInstance != secondInstance); + } + + @Test + public void givenPrototypeInjection_WhenLookup_ThenNewInstanceReturn() { + + AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); + + SingletonLookupBean firstContext = context.getBean(SingletonLookupBean.class); + SingletonLookupBean secondContext = context.getBean(SingletonLookupBean.class); + + PrototypeBean firstInstance = firstContext.getPrototypeBean(); + PrototypeBean secondInstance = secondContext.getPrototypeBean(); + + Assert.assertTrue("New instance expected", firstInstance != secondInstance); + } + + @Test + public void givenPrototypeInjection_WhenProvider_ThenNewInstanceReturn() { + + AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); + + SingletonProviderBean firstContext = context.getBean(SingletonProviderBean.class); + SingletonProviderBean secondContext = context.getBean(SingletonProviderBean.class); + + PrototypeBean firstInstance = firstContext.getPrototypeInstance(); + PrototypeBean secondInstance = secondContext.getPrototypeInstance(); + + Assert.assertTrue("New instance expected", firstInstance != secondInstance); + } + +} diff --git a/spring-core/src/test/java/com/baeldung/scope/PrototypeBeanInjectionTest.java b/spring-core/src/test/java/com/baeldung/scope/PrototypeBeanInjectionTest.java deleted file mode 100644 index 0c4c5d6069..0000000000 --- a/spring-core/src/test/java/com/baeldung/scope/PrototypeBeanInjectionTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.scope; - -import com.baeldung.scope.prototype.PrototypeBean; -import com.baeldung.scope.singletone.SingletonLookupBean; -import com.baeldung.scope.singletone.SingletonObjectFactoryBean; -import com.baeldung.scope.singletone.SingletonProviderBean; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.support.AbstractApplicationContext; -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 = AppConfig.class) -public class PrototypeBeanInjectionTest { - - @Test - public void givenPrototypeInjection_WhenObjectFactory_ThenNewInstanceReturn() { - - AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); - - SingletonObjectFactoryBean firstContext = context.getBean(SingletonObjectFactoryBean.class); - SingletonObjectFactoryBean secondContext = context.getBean(SingletonObjectFactoryBean.class); - - PrototypeBean firstInstance = firstContext.getPrototypeInstance(); - PrototypeBean secondInstance = secondContext.getPrototypeInstance(); - - Assert.assertTrue("New instance expected", firstInstance != secondInstance); - } - - @Test - public void givenPrototypeInjection_WhenLookup_ThenNewInstanceReturn() { - - AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); - - SingletonLookupBean firstContext = context.getBean(SingletonLookupBean.class); - SingletonLookupBean secondContext = context.getBean(SingletonLookupBean.class); - - PrototypeBean firstInstance = firstContext.getPrototypeBean(); - PrototypeBean secondInstance = secondContext.getPrototypeBean(); - - Assert.assertTrue("New instance expected", firstInstance != secondInstance); - } - - @Test - public void givenPrototypeInjection_WhenProvider_ThenNewInstanceReturn() { - - AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); - - SingletonProviderBean firstContext = context.getBean(SingletonProviderBean.class); - SingletonProviderBean secondContext = context.getBean(SingletonProviderBean.class); - - PrototypeBean firstInstance = firstContext.getPrototypeInstance(); - PrototypeBean secondInstance = secondContext.getPrototypeInstance(); - - Assert.assertTrue("New instance expected", firstInstance != secondInstance); - } -} diff --git a/spring-core/src/test/java/com/baeldung/scope/PrototypeFunctionBeanIntegrationTest.java b/spring-core/src/test/java/com/baeldung/scope/PrototypeFunctionBeanIntegrationTest.java new file mode 100644 index 0000000000..1e3c652599 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/scope/PrototypeFunctionBeanIntegrationTest.java @@ -0,0 +1,34 @@ +package com.baeldung.scope; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.config.scope.AppConfigFunctionBean; +import com.baeldung.scope.prototype.PrototypeBean; +import com.baeldung.scope.singletone.SingletonFunctionBean; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = AppConfigFunctionBean.class) +public class PrototypeFunctionBeanIntegrationTest { + + @Test + public void givenPrototypeInjection_WhenFunction_ThenNewInstanceReturn() { + + AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfigFunctionBean.class); + + SingletonFunctionBean firstContext = context.getBean(SingletonFunctionBean.class); + SingletonFunctionBean secondContext = context.getBean(SingletonFunctionBean.class); + + PrototypeBean firstInstance = firstContext.getPrototypeInstance("instance1"); + PrototypeBean secondInstance = secondContext.getPrototypeInstance("instance2"); + + Assert.assertTrue("New instance expected", firstInstance != secondInstance); + } + +} diff --git a/spring-core/src/test/java/com/baeldung/streamutils/CopyStreamIntegrationTest.java b/spring-core/src/test/java/com/baeldung/streamutils/CopyStreamIntegrationTest.java new file mode 100644 index 0000000000..7f4a026229 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/streamutils/CopyStreamIntegrationTest.java @@ -0,0 +1,100 @@ +package com.baeldung.streamutils; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; +import org.springframework.util.StreamUtils; + +import static com.baeldung.streamutils.CopyStream.getStringFromInputStream; + +public class CopyStreamIntegrationTest { + + @Test + public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + InputStream in = new FileInputStream(inputFileName); + OutputStream out = new FileOutputStream(outputFileName); + + StreamUtils.copy(in, out); + + assertTrue(outputFile.exists()); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + assertEquals(inputFileContent, outputFileContent); + } + + @Test + public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + InputStream in = new FileInputStream(inputFileName); + OutputStream out = new FileOutputStream(outputFileName); + + StreamUtils.copyRange(in, out, 1, 10); + + assertTrue(outputFile.exists()); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + assertEquals(inputFileContent.substring(1, 11), outputFileContent); + } + + @Test + public void whenCopyStringToOutputStream_thenCorrect() throws IOException { + String string = "Should be copied to OutputStream."; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + OutputStream out = new FileOutputStream("src/test/resources/output.txt"); + + StreamUtils.copy(string, StandardCharsets.UTF_8, out); + + assertTrue(outputFile.exists()); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + assertEquals(outputFileContent, string); + } + + @Test + public void whenCopyInputStreamToString_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + InputStream is = new FileInputStream(inputFileName); + String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8); + + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + assertEquals(inputFileContent, content); + } + + @Test + public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException { + String outputFileName = "src/test/resources/output.txt"; + String string = "Should be copied to OutputStream."; + byte[] byteArray = string.getBytes(); + OutputStream out = new FileOutputStream("src/test/resources/output.txt"); + + StreamUtils.copy(byteArray, out); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + assertEquals(outputFileContent, string); + } + + @Test + public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + InputStream in = new FileInputStream(inputFileName); + byte[] out = StreamUtils.copyToByteArray(in); + + String content = new String(out); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + assertEquals(inputFileContent, content); + } + +} diff --git a/spring-core/src/test/java/com/baeldung/streamutils/CopyStreamTest.java b/spring-core/src/test/java/com/baeldung/streamutils/CopyStreamTest.java deleted file mode 100644 index 9fe2f00a77..0000000000 --- a/spring-core/src/test/java/com/baeldung/streamutils/CopyStreamTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.baeldung.streamutils; - -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.charset.StandardCharsets; - -import static org.junit.Assert.assertEquals; -import org.junit.Test; -import org.springframework.util.StreamUtils; - -import static com.baeldung.streamutils.CopyStream.getStringFromInputStream; - -public class CopyStreamTest { - - @Test - public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException { - String inputFileName = "src/test/resources/input.txt"; - String outputFileName = "src/test/resources/output.txt"; - File outputFile = new File(outputFileName); - InputStream in = new FileInputStream(inputFileName); - OutputStream out = new FileOutputStream(outputFileName); - - StreamUtils.copy(in, out); - - assertTrue(outputFile.exists()); - String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); - String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); - assertEquals(inputFileContent, outputFileContent); - } - - @Test - public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException { - String inputFileName = "src/test/resources/input.txt"; - String outputFileName = "src/test/resources/output.txt"; - File outputFile = new File(outputFileName); - InputStream in = new FileInputStream(inputFileName); - OutputStream out = new FileOutputStream(outputFileName); - - StreamUtils.copyRange(in, out, 1, 10); - - assertTrue(outputFile.exists()); - String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); - String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); - assertEquals(inputFileContent.substring(1, 11), outputFileContent); - } - - @Test - public void whenCopyStringToOutputStream_thenCorrect() throws IOException { - String string = "Should be copied to OutputStream."; - String outputFileName = "src/test/resources/output.txt"; - File outputFile = new File(outputFileName); - OutputStream out = new FileOutputStream("src/test/resources/output.txt"); - - StreamUtils.copy(string, StandardCharsets.UTF_8, out); - - assertTrue(outputFile.exists()); - String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); - assertEquals(outputFileContent, string); - } - - @Test - public void whenCopyInputStreamToString_thenCorrect() throws IOException { - String inputFileName = "src/test/resources/input.txt"; - InputStream is = new FileInputStream(inputFileName); - String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8); - - String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); - assertEquals(inputFileContent, content); - } - - @Test - public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException { - String outputFileName = "src/test/resources/output.txt"; - String string = "Should be copied to OutputStream."; - byte[] byteArray = string.getBytes(); - OutputStream out = new FileOutputStream("src/test/resources/output.txt"); - - StreamUtils.copy(byteArray, out); - String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); - assertEquals(outputFileContent, string); - } - - @Test - public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException { - String inputFileName = "src/test/resources/input.txt"; - InputStream in = new FileInputStream(inputFileName); - byte[] out = StreamUtils.copyToByteArray(in); - - String content = new String(out); - String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); - assertEquals(inputFileContent, content); - } - -} diff --git a/spring-core/src/test/java/com/baeldung/value/ClassNotManagedBySpringIntegrationTest.java b/spring-core/src/test/java/com/baeldung/value/ClassNotManagedBySpringIntegrationTest.java new file mode 100644 index 0000000000..689801bece --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/value/ClassNotManagedBySpringIntegrationTest.java @@ -0,0 +1,40 @@ +package com.baeldung.value; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit4.SpringRunner; + +import static junit.framework.TestCase.assertEquals; +import static org.mockito.Mockito.when; + +@RunWith(SpringRunner.class) +public class ClassNotManagedBySpringIntegrationTest { + + @MockBean + private InitializerBean initializerBean; + + @Before + public void init() { + when(initializerBean.initClass()) + .thenReturn(new ClassNotManagedBySpring("This is only sample value", "Another configured value")); + } + + @Test + public void givenInitializerBean_whenInvokedInitClass_shouldInitialize() throws Exception { + + //given + ClassNotManagedBySpring classNotManagedBySpring = initializerBean.initClass(); + + //when + String initializedValue = classNotManagedBySpring.getCustomVariable(); + String anotherCustomVariable = classNotManagedBySpring.getAnotherCustomVariable(); + + //then + assertEquals("This is only sample value", initializedValue); + assertEquals("Another configured value", anotherCustomVariable); + + } + +} \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/value/ClassNotManagedBySpringTest.java b/spring-core/src/test/java/com/baeldung/value/ClassNotManagedBySpringTest.java deleted file mode 100644 index d07d490642..0000000000 --- a/spring-core/src/test/java/com/baeldung/value/ClassNotManagedBySpringTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.value; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.junit4.SpringRunner; - -import static junit.framework.TestCase.assertEquals; -import static org.mockito.Mockito.when; - -@RunWith(SpringRunner.class) -public class ClassNotManagedBySpringTest { - - @MockBean - private InitializerBean initializerBean; - - @Before - public void init() { - when(initializerBean.initClass()) - .thenReturn(new ClassNotManagedBySpring("This is only sample value", "Another configured value")); - } - - @Test - public void givenInitializerBean_whenInvokedInitClass_shouldInitialize() throws Exception { - - //given - ClassNotManagedBySpring classNotManagedBySpring = initializerBean.initClass(); - - //when - String initializedValue = classNotManagedBySpring.getCustomVariable(); - String anotherCustomVariable = classNotManagedBySpring.getAnotherCustomVariable(); - - //then - assertEquals("This is only sample value", initializedValue); - assertEquals("Another configured value", anotherCustomVariable); - - } - -} \ No newline at end of file diff --git a/spring-core/src/test/resources/data/employees.dat b/spring-core/src/test/resources/data/employees.dat new file mode 100644 index 0000000000..9c28fdf82f --- /dev/null +++ b/spring-core/src/test/resources/data/employees.dat @@ -0,0 +1 @@ +Joe Employee,Jan Employee,James T. Employee \ No newline at end of file diff --git a/spring-cucumber/pom.xml b/spring-cucumber/pom.xml index cabd1a9020..64b543bb6c 100644 --- a/spring-cucumber/pom.xml +++ b/spring-cucumber/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-cucumber @@ -10,10 +10,10 @@ Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-cucumber/src/main/resources/logback.xml b/spring-cucumber/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cucumber/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/CucumberIntegrationTest.java b/spring-cucumber/src/test/java/com/baeldung/CucumberIntegrationTest.java index 56eb810c09..f48ab410ca 100644 --- a/spring-cucumber/src/test/java/com/baeldung/CucumberIntegrationTest.java +++ b/spring-cucumber/src/test/java/com/baeldung/CucumberIntegrationTest.java @@ -1,10 +1,11 @@ package com.baeldung; +import org.junit.runner.RunWith; + import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; -import org.junit.runner.RunWith; @RunWith(Cucumber.class) @CucumberOptions(features = "src/test/resources") -public class CucumberIntegrationTest { +public class CucumberIntegrationTest extends SpringIntegrationTest{ } \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java b/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java index f4d47d7871..8655a02469 100644 --- a/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java +++ b/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java @@ -5,16 +5,17 @@ import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpResponse; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.client.ResponseErrorHandler; import org.springframework.web.client.RestTemplate; //@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = SpringDemoApplication.class) -@WebAppConfiguration +@SpringBootTest(classes = SpringDemoApplication.class, webEnvironment = WebEnvironment.DEFINED_PORT) +@ContextConfiguration public class SpringIntegrationTest { static ResponseResults latestResponse = null; diff --git a/spring-custom-aop/pom.xml b/spring-custom-aop/pom.xml index 76d8e7c344..fd5f87a476 100644 --- a/spring-custom-aop/pom.xml +++ b/spring-custom-aop/pom.xml @@ -1,5 +1,5 @@ + 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-custom-aop @@ -9,10 +9,10 @@ This is simple boot application for Spring boot actuator test - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -101,7 +101,7 @@ com.google.guava guava - 18.0 + ${guava.version} @@ -148,6 +148,7 @@ 3.3.7-1 3.1.7 8.5.11 + 18.0 diff --git a/spring-custom-aop/src/main/resources/logback.xml b/spring-custom-aop/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-custom-aop/src/main/resources/logback.xml +++ b/spring-custom-aop/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-data-5-reactive/pom.xml b/spring-data-5-reactive/pom.xml deleted file mode 100644 index 710f6f9d67..0000000000 --- a/spring-data-5-reactive/pom.xml +++ /dev/null @@ -1,138 +0,0 @@ - - - 4.0.0 - com.baeldung - spring-5-data-reactive - 0.0.1-SNAPSHOT - jar - Spring-5-data-reactive - Spring-5-data-reactive with Springboot 2.0.1 - - - org.springframework.boot - spring-boot-starter-parent - 2.0.1.RELEASE - - - - - UTF-8 - UTF-8 - 1.8 - 1.2.40 - - - - - org.springframework.boot - spring-boot-starter-data-mongodb-reactive - - - org.springframework.boot - spring-boot-starter-web - - - javax.ws.rs - javax.ws.rs-api - ${javax.ws.rs-api.version} - - - com.fasterxml.jackson.module - jackson-module-kotlin - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - - - org.jetbrains.kotlin - kotlin-reflect - - - org.projectlombok - lombok - - - io.projectreactor - reactor-test - test - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - - - org.jetbrains.kotlin - kotlin-test - ${kotlin.version} - test - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - - - - - - spring-libs-snapshot - Spring Snapshot Repository - http://repo.spring.io/libs-snapshot - - - - - src/main/kotlin - - - org.springframework.boot - spring-boot-maven-plugin - - - kotlin-maven-plugin - ${kotlin.version} - - - compile - compile - - compile - - - - test-compile - test-compile - - test-compile - - - - org.jetbrains.kotlin - - - -Xjsr305=strict - - - spring - - 1.8 - - - - org.jetbrains.kotlin - kotlin-maven-allopen - ${kotlin.version} - - - - - - diff --git a/spring-data-couchbase-2/pom.xml b/spring-data-couchbase-2/pom.xml index 10afff76e7..6c7d7a9d11 100644 --- a/spring-data-couchbase-2/pom.xml +++ b/spring-data-couchbase-2/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung spring-data-couchbase-2 @@ -61,9 +61,7 @@ - 1.8 - UTF-8 - 4.3.4.RELEASE + 4.3.4.RELEASE 2.1.5.RELEASE 5.3.3.Final 2.9.6 diff --git a/spring-data-couchbase-2/src/main/resources/logback.xml b/spring-data-couchbase-2/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-data-couchbase-2/src/main/resources/logback.xml +++ b/spring-data-couchbase-2/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegationTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegationTest.java deleted file mode 100644 index cb671dc469..0000000000 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegationTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.spring.data.couchbase2b; - -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestExecutionListeners; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { MultiBucketCouchbaseConfig.class, MultiBucketIntegrationTestConfig.class }) -@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public abstract class MultiBucketIntegationTest { - -} diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTest.java new file mode 100644 index 0000000000..05ba58d616 --- /dev/null +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTest.java @@ -0,0 +1,14 @@ +package org.baeldung.spring.data.couchbase2b; + +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MultiBucketCouchbaseConfig.class, MultiBucketIntegrationTestConfig.class }) +@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) +public abstract class MultiBucketIntegrationTest { + +} diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java index 71648cf59b..0996b252f1 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java @@ -10,7 +10,7 @@ import java.util.Set; import javax.annotation.PostConstruct; import org.baeldung.spring.data.couchbase.model.Campus; -import org.baeldung.spring.data.couchbase2b.MultiBucketIntegationTest; +import org.baeldung.spring.data.couchbase2b.MultiBucketIntegrationTest; import org.baeldung.spring.data.couchbase2b.repos.CampusRepository; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -18,7 +18,7 @@ import org.springframework.data.geo.Distance; import org.springframework.data.geo.Metrics; import org.springframework.data.geo.Point; -public class CampusServiceImplIntegrationTest extends MultiBucketIntegationTest { +public class CampusServiceImplIntegrationTest extends MultiBucketIntegrationTest { @Autowired private CampusServiceImpl campusService; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java index 819798d536..45475e50f6 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java @@ -9,7 +9,7 @@ import java.util.List; import org.baeldung.spring.data.couchbase.model.Person; import org.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig; -import org.baeldung.spring.data.couchbase2b.MultiBucketIntegationTest; +import org.baeldung.spring.data.couchbase2b.MultiBucketIntegrationTest; import org.joda.time.DateTime; import org.junit.BeforeClass; import org.junit.Test; @@ -21,7 +21,7 @@ import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; -public class PersonServiceImplIntegrationTest extends MultiBucketIntegationTest { +public class PersonServiceImplIntegrationTest extends MultiBucketIntegrationTest { static final String typeField = "_class"; static final String john = "John"; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java index f37f11744d..e7c1eab92a 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java @@ -11,7 +11,7 @@ import javax.validation.ConstraintViolationException; import org.baeldung.spring.data.couchbase.model.Student; import org.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig; -import org.baeldung.spring.data.couchbase2b.MultiBucketIntegationTest; +import org.baeldung.spring.data.couchbase2b.MultiBucketIntegrationTest; import org.joda.time.DateTime; import org.junit.BeforeClass; import org.junit.Test; @@ -23,7 +23,7 @@ import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; -public class StudentServiceImplIntegrationTest extends MultiBucketIntegationTest { +public class StudentServiceImplIntegrationTest extends MultiBucketIntegrationTest { static final String typeField = "_class"; static final String joe = "Joe"; diff --git a/spring-data-couchbase-2/src/test/resources/logback.xml b/spring-data-couchbase-2/src/test/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-data-couchbase-2/src/test/resources/logback.xml +++ b/spring-data-couchbase-2/src/test/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-data-elasticsearch/pom.xml b/spring-data-elasticsearch/pom.xml index 804cf23a69..99d8a70807 100644 --- a/spring-data-elasticsearch/pom.xml +++ b/spring-data-elasticsearch/pom.xml @@ -1,5 +1,5 @@ + 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-data-elasticsearch @@ -9,60 +9,30 @@ com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 org.springframework spring-core - ${org.springframework.version} - - - commons-logging - commons-logging - - + ${spring.version} + + + org.springframework + spring-context + ${spring.version} + + org.springframework.data spring-data-elasticsearch ${spring-data-elasticsearch.version} - - com.spatial4j - spatial4j - ${spatial4j.version} - - - - com.vividsolutions - jts - ${jts.version} - - - xerces - xercesImpl - - - - - - org.springframework - spring-test - ${org.springframework.version} - test - - - net.java.dev.jna - jna - ${jna.version} - test - - org.elasticsearch elasticsearch @@ -73,20 +43,62 @@ fastjson ${fastjson.version} + + + org.locationtech.spatial4j + spatial4j + ${spatial4j.version} + + + + com.vividsolutions + jts + ${jts.version} + + + xerces + xercesImpl + + + + + + org.apache.logging.log4j + log4j-core + ${log4j.version} + + + + org.elasticsearch.client + transport + ${elasticsearch.version} + + + + org.springframework + spring-test + ${spring.version} + test + + + + net.java.dev.jna + jna + ${jna.version} + test + - - UTF-8 1.8 1.8 - 4.3.4.RELEASE - 2.0.5.RELEASE - 4.2.2 - 2.4.2 - 1.2.21 - 0.4.1 + 3.0.8.RELEASE + 4.5.2 + 5.6.0 + 1.2.47 + 0.6 1.13 + 2.9.1 \ No newline at end of file diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java index 37e9fd46eb..e6ce795b45 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java @@ -1,15 +1,13 @@ package com.baeldung.spring.data.es.config; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; +import java.net.InetAddress; +import java.net.UnknownHostException; import org.elasticsearch.client.Client; +import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.node.NodeBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.elasticsearch.common.transport.InetSocketTransportAddress; +import org.elasticsearch.transport.client.PreBuiltTransportClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -23,35 +21,26 @@ import org.springframework.data.elasticsearch.repository.config.EnableElasticsea @ComponentScan(basePackages = { "com.baeldung.spring.data.es.service" }) public class Config { - @Value("${elasticsearch.home:/usr/local/Cellar/elasticsearch/2.3.2}") + @Value("${elasticsearch.home:/usr/local/Cellar/elasticsearch/5.6.0}") private String elasticsearchHome; - private static Logger logger = LoggerFactory.getLogger(Config.class); + @Value("${elasticsearch.cluster.name:elasticsearch}") + private String clusterName; @Bean public Client client() { + TransportClient client = null; try { - final Path tmpDir = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "elasticsearch_data"); - logger.debug(tmpDir.toAbsolutePath().toString()); - - // @formatter:off - - final Settings.Builder elasticsearchSettings = - Settings.settingsBuilder().put("http.enabled", "false") - .put("path.data", tmpDir.toAbsolutePath().toString()) - .put("path.home", elasticsearchHome); - - return new NodeBuilder() - .local(true) - .settings(elasticsearchSettings) - .node() - .client(); - - // @formatter:on - } catch (final IOException ioex) { - logger.error("Cannot create temp dir", ioex); - throw new RuntimeException(); + final Settings elasticsearchSettings = Settings.builder() + .put("client.transport.sniff", true) + .put("path.home", elasticsearchHome) + .put("cluster.name", clusterName).build(); + client = new PreBuiltTransportClient(elasticsearchSettings); + client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300)); + } catch (UnknownHostException e) { + e.printStackTrace(); } + return client; } @Bean diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java index 01330a6c9c..e901d0d0ed 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java @@ -1,8 +1,8 @@ package com.baeldung.spring.data.es.model; -import static org.springframework.data.elasticsearch.annotations.FieldIndex.not_analyzed; +import static org.springframework.data.elasticsearch.annotations.FieldType.Keyword; import static org.springframework.data.elasticsearch.annotations.FieldType.Nested; -import static org.springframework.data.elasticsearch.annotations.FieldType.String; +import static org.springframework.data.elasticsearch.annotations.FieldType.Text; import java.util.Arrays; import java.util.List; @@ -19,13 +19,13 @@ public class Article { @Id private String id; - @MultiField(mainField = @Field(type = String), otherFields = { @InnerField(index = not_analyzed, suffix = "verbatim", type = String) }) + @MultiField(mainField = @Field(type = Text, fielddata = true), otherFields = { @InnerField(suffix = "verbatim", type = Keyword) }) private String title; - @Field(type = Nested) + @Field(type = Nested, includeInParent = true) private List authors; - @Field(type = String, index = not_analyzed) + @Field(type = Keyword) private String[] tags; public Article() { diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleService.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleService.java index 63e2d91fa7..a0f72aa5f7 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleService.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleService.java @@ -1,5 +1,7 @@ package com.baeldung.spring.data.es.service; +import java.util.Optional; + import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -8,7 +10,7 @@ import com.baeldung.spring.data.es.model.Article; public interface ArticleService { Article save(Article article); - Article findOne(String id); + Optional
    findOne(String id); Iterable
    findAll(); diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java index 0908ffa70e..5064f16508 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java @@ -1,5 +1,7 @@ package com.baeldung.spring.data.es.service; +import java.util.Optional; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -24,8 +26,8 @@ public class ArticleServiceImpl implements ArticleService { } @Override - public Article findOne(String id) { - return articleRepository.findOne(id); + public Optional
    findOne(String id) { + return articleRepository.findById(id); } @Override diff --git a/spring-data-elasticsearch/src/main/resources/log4j2.properties b/spring-data-elasticsearch/src/main/resources/log4j2.properties new file mode 100644 index 0000000000..fced116e6b --- /dev/null +++ b/spring-data-elasticsearch/src/main/resources/log4j2.properties @@ -0,0 +1,6 @@ +appender.console.type = Console +appender.console.name = console +appender.console.layout.type = PatternLayout + +rootLogger.level = info +rootLogger.appenderRef.console.ref = console \ No newline at end of file diff --git a/spring-data-elasticsearch/src/main/resources/logback.xml b/spring-data-elasticsearch/src/main/resources/logback.xml deleted file mode 100644 index ec0dc2469a..0000000000 --- a/spring-data-elasticsearch/src/main/resources/logback.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - web - %date [%thread] %-5level %logger{36} - %message%n - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchManualTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchManualTest.java index 285c164869..fbf4e5ab99 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchManualTest.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchManualTest.java @@ -1,45 +1,49 @@ package com.baeldung.elasticsearch; -import com.alibaba.fastjson.JSON; -import org.elasticsearch.action.delete.DeleteResponse; -import org.elasticsearch.action.index.IndexResponse; -import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.action.search.SearchType; -import org.elasticsearch.client.Client; -import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.common.xcontent.XContentFactory; -import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.node.Node; -import org.elasticsearch.search.SearchHit; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.stream.Collectors; -import static org.elasticsearch.node.NodeBuilder.nodeBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.elasticsearch.action.DocWriteResponse.Result; +import org.elasticsearch.action.delete.DeleteResponse; +import org.elasticsearch.action.index.IndexResponse; +import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.action.search.SearchType; +import org.elasticsearch.client.Client; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.transport.InetSocketTransportAddress; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.common.xcontent.XContentFactory; +import org.elasticsearch.common.xcontent.XContentType; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.search.SearchHit; +import org.elasticsearch.transport.client.PreBuiltTransportClient; +import org.junit.Before; +import org.junit.Test; + +import com.alibaba.fastjson.JSON; public class ElasticSearchManualTest { private List listOfPersons = new ArrayList<>(); private Client client = null; @Before - public void setUp() { + public void setUp() throws UnknownHostException { Person person1 = new Person(10, "John Doe", new Date()); Person person2 = new Person(25, "Janette Doe", new Date()); listOfPersons.add(person1); listOfPersons.add(person2); - Node node = nodeBuilder() - .clusterName("elasticsearch") - .client(true) - .node(); - client = node.client(); + + client = new PreBuiltTransportClient(Settings.builder().put("client.transport.sniff", true) + .put("cluster.name","elasticsearch").build()) + .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300)); } @Test @@ -47,11 +51,12 @@ public class ElasticSearchManualTest { String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}"; IndexResponse response = client .prepareIndex("people", "Doe") - .setSource(jsonObject) + .setSource(jsonObject, XContentType.JSON) .get(); String index = response.getIndex(); String type = response.getType(); - assertTrue(response.isCreated()); + + assertEquals(Result.CREATED, response.getResult()); assertEquals(index, "people"); assertEquals(type, "Doe"); } @@ -61,13 +66,14 @@ public class ElasticSearchManualTest { String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}"; IndexResponse response = client .prepareIndex("people", "Doe") - .setSource(jsonObject) + .setSource(jsonObject, XContentType.JSON) .get(); String id = response.getId(); DeleteResponse deleteResponse = client .prepareDelete("people", "Doe", id) .get(); - assertTrue(deleteResponse.isFound()); + + assertEquals(Result.DELETED,deleteResponse.getResult()); } @Test @@ -142,6 +148,7 @@ public class ElasticSearchManualTest { .prepareIndex("people", "Doe") .setSource(builder) .get(); - assertTrue(response.isCreated()); + + assertEquals(Result.CREATED, response.getResult()); } } diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/GeoQueriesIntegrationTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/GeoQueriesIntegrationTest.java index 304cf2e62d..1f55379418 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/GeoQueriesIntegrationTest.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/GeoQueriesIntegrationTest.java @@ -1,13 +1,21 @@ package com.baeldung.elasticsearch; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; -import com.baeldung.spring.data.es.config.Config; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; +import org.elasticsearch.common.geo.GeoPoint; import org.elasticsearch.common.geo.ShapeRelation; -import org.elasticsearch.common.geo.builders.ShapeBuilder; +import org.elasticsearch.common.geo.builders.ShapeBuilders; import org.elasticsearch.common.unit.DistanceUnit; +import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; @@ -20,11 +28,8 @@ import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.junit.Assert.assertTrue; +import com.baeldung.spring.data.es.config.Config; +import com.vividsolutions.jts.geom.Coordinate; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = Config.class) @@ -43,7 +48,7 @@ public class GeoQueriesIntegrationTest { public void setUp() { String jsonObject = "{\"Wonders\":{\"properties\":{\"name\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"region\":{\"type\":\"geo_shape\",\"tree\":\"quadtree\",\"precision\":\"1m\"},\"location\":{\"type\":\"geo_point\"}}}}"; CreateIndexRequest req = new CreateIndexRequest(WONDERS_OF_WORLD); - req.mapping(WONDERS, jsonObject); + req.mapping(WONDERS, jsonObject, XContentType.JSON); client.admin() .indices() .create(req) @@ -51,31 +56,36 @@ public class GeoQueriesIntegrationTest { } @Test - public void givenGeoShapeData_whenExecutedGeoShapeQuery_thenResultNonEmpty() { - String jsonObject = "{\"name\":\"Agra\",\"region\":{\"type\":\"envelope\",\"coordinates\":[[75,25],[80.1,30.2]]}}"; + public void givenGeoShapeData_whenExecutedGeoShapeQuery_thenResultNonEmpty() throws IOException{ + String jsonObject = "{\"name\":\"Agra\",\"region\":{\"type\":\"envelope\",\"coordinates\":[[75,30.2],[80.1, 25]]}}"; IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS) - .setSource(jsonObject) + .setSource(jsonObject, XContentType.JSON) .get(); + String tajMahalId = response.getId(); client.admin() .indices() .prepareRefresh(WONDERS_OF_WORLD) .get(); - QueryBuilder qb = QueryBuilders.geoShapeQuery("region", ShapeBuilder.newEnvelope() - .topLeft(74.00, 24.0) - .bottomRight(81.1, 31.2)) - .relation(ShapeRelation.WITHIN); + Coordinate topLeft =new Coordinate(74, 31.2); + Coordinate bottomRight =new Coordinate(81.1, 24); + QueryBuilder qb = QueryBuilders + .geoShapeQuery("region", ShapeBuilders.newEnvelope(topLeft, bottomRight)) + .relation(ShapeRelation.WITHIN); + SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD) .setTypes(WONDERS) .setQuery(qb) .execute() .actionGet(); + List ids = Arrays.stream(searchResponse.getHits() .getHits()) .map(SearchHit::getId) .collect(Collectors.toList()); + assertTrue(ids.contains(tajMahalId)); } @@ -83,7 +93,7 @@ public class GeoQueriesIntegrationTest { public void givenGeoPointData_whenExecutedGeoBoundingBoxQuery_thenResultNonEmpty() { String jsonObject = "{\"name\":\"Pyramids of Giza\",\"location\":[31.131302,29.976480]}"; IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS) - .setSource(jsonObject) + .setSource(jsonObject, XContentType.JSON) .get(); String pyramidsOfGizaId = response.getId(); client.admin() @@ -92,9 +102,8 @@ public class GeoQueriesIntegrationTest { .get(); QueryBuilder qb = QueryBuilders.geoBoundingBoxQuery("location") - .bottomLeft(28, 30) - .topRight(31, 32); - + .setCorners(31,30,28,32); + SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD) .setTypes(WONDERS) .setQuery(qb) @@ -111,7 +120,7 @@ public class GeoQueriesIntegrationTest { public void givenGeoPointData_whenExecutedGeoDistanceQuery_thenResultNonEmpty() { String jsonObject = "{\"name\":\"Lighthouse of alexandria\",\"location\":[31.131302,29.976480]}"; IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS) - .setSource(jsonObject) + .setSource(jsonObject, XContentType.JSON) .get(); String lighthouseOfAlexandriaId = response.getId(); client.admin() @@ -139,7 +148,7 @@ public class GeoQueriesIntegrationTest { public void givenGeoPointData_whenExecutedGeoPolygonQuery_thenResultNonEmpty() { String jsonObject = "{\"name\":\"The Great Rann of Kutch\",\"location\":[69.859741,23.733732]}"; IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS) - .setSource(jsonObject) + .setSource(jsonObject, XContentType.JSON) .get(); String greatRannOfKutchid = response.getId(); client.admin() @@ -147,10 +156,11 @@ public class GeoQueriesIntegrationTest { .prepareRefresh(WONDERS_OF_WORLD) .get(); - QueryBuilder qb = QueryBuilders.geoPolygonQuery("location") - .addPoint(22.733, 68.859) - .addPoint(24.733, 68.859) - .addPoint(23, 70.859); + List allPoints = new ArrayList(); + allPoints.add(new GeoPoint(22.733, 68.859)); + allPoints.add(new GeoPoint(24.733, 68.859)); + allPoints.add(new GeoPoint(23, 70.859)); + QueryBuilder qb = QueryBuilders.geoPolygonQuery("location", allPoints); SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD) .setTypes(WONDERS) diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java index 60871e5eee..6ecb11cdbe 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java @@ -1,9 +1,15 @@ package com.baeldung.spring.data.es; -import com.baeldung.spring.data.es.config.Config; -import com.baeldung.spring.data.es.model.Article; -import com.baeldung.spring.data.es.model.Author; -import com.baeldung.spring.data.es.service.ArticleService; +import static java.util.Arrays.asList; +import static org.elasticsearch.index.query.Operator.AND; +import static org.elasticsearch.index.query.QueryBuilders.fuzzyQuery; +import static org.elasticsearch.index.query.QueryBuilders.matchQuery; +import static org.elasticsearch.index.query.QueryBuilders.regexpQuery; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.List; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -16,15 +22,10 @@ import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.util.List; - -import static java.util.Arrays.asList; -import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND; -import static org.elasticsearch.index.query.QueryBuilders.fuzzyQuery; -import static org.elasticsearch.index.query.QueryBuilders.matchQuery; -import static org.elasticsearch.index.query.QueryBuilders.regexpQuery; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import com.baeldung.spring.data.es.config.Config; +import com.baeldung.spring.data.es.model.Article; +import com.baeldung.spring.data.es.model.Author; +import com.baeldung.spring.data.es.service.ArticleService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = Config.class) @@ -81,25 +82,25 @@ public class ElasticSearchIntegrationTest { public void givenPersistedArticles_whenSearchByAuthorsName_thenRightFound() { final Page
    articleByAuthorName = articleService - .findByAuthorName(johnSmith.getName(), new PageRequest(0, 10)); + .findByAuthorName(johnSmith.getName(), PageRequest.of(0, 10)); assertEquals(2L, articleByAuthorName.getTotalElements()); } @Test public void givenCustomQuery_whenSearchByAuthorsName_thenArticleIsFound() { - final Page
    articleByAuthorName = articleService.findByAuthorNameUsingCustomQuery("Smith", new PageRequest(0, 10)); + final Page
    articleByAuthorName = articleService.findByAuthorNameUsingCustomQuery("Smith", PageRequest.of(0, 10)); assertEquals(2L, articleByAuthorName.getTotalElements()); } @Test public void givenTagFilterQuery_whenSearchByTag_thenArticleIsFound() { - final Page
    articleByAuthorName = articleService.findByFilteredTagQuery("elasticsearch", new PageRequest(0, 10)); + final Page
    articleByAuthorName = articleService.findByFilteredTagQuery("elasticsearch", PageRequest.of(0, 10)); assertEquals(3L, articleByAuthorName.getTotalElements()); } @Test public void givenTagFilterQuery_whenSearchByAuthorsName_thenArticleIsFound() { - final Page
    articleByAuthorName = articleService.findByAuthorsNameAndFilteredTagQuery("Doe", "elasticsearch", new PageRequest(0, 10)); + final Page
    articleByAuthorName = articleService.findByAuthorsNameAndFilteredTagQuery("Doe", "elasticsearch", PageRequest.of(0, 10)); assertEquals(2L, articleByAuthorName.getTotalElements()); } @@ -125,7 +126,7 @@ public class ElasticSearchIntegrationTest { article.setTitle(newTitle); articleService.save(article); - assertEquals(newTitle, articleService.findOne(article.getId()).getTitle()); + assertEquals(newTitle, articleService.findOne(article.getId()).get().getTitle()); } @Test diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java index c6af93bb62..2348c49830 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java @@ -1,9 +1,20 @@ package com.baeldung.spring.data.es; -import com.baeldung.spring.data.es.config.Config; -import com.baeldung.spring.data.es.model.Article; -import com.baeldung.spring.data.es.model.Author; -import com.baeldung.spring.data.es.service.ArticleService; +import static java.util.Arrays.asList; +import static java.util.stream.Collectors.toList; +import static org.elasticsearch.index.query.Operator.AND; +import static org.elasticsearch.index.query.QueryBuilders.boolQuery; +import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery; +import static org.elasticsearch.index.query.QueryBuilders.matchQuery; +import static org.elasticsearch.index.query.QueryBuilders.multiMatchQuery; +import static org.elasticsearch.index.query.QueryBuilders.nestedQuery; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; +import static org.junit.Assert.assertEquals; + +import java.util.List; +import java.util.Map; + +import org.apache.lucene.search.join.ScoreMode; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.Fuzziness; @@ -14,7 +25,7 @@ import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation; import org.elasticsearch.search.aggregations.bucket.terms.StringTerms; import org.elasticsearch.search.aggregations.bucket.terms.Terms; -import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder; +import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -25,20 +36,10 @@ import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import static java.util.Arrays.asList; -import static java.util.stream.Collectors.toList; -import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND; -import static org.elasticsearch.index.query.QueryBuilders.boolQuery; -import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery; -import static org.elasticsearch.index.query.QueryBuilders.matchQuery; -import static org.elasticsearch.index.query.QueryBuilders.multiMatchQuery; -import static org.elasticsearch.index.query.QueryBuilders.nestedQuery; -import static org.elasticsearch.index.query.QueryBuilders.termQuery; -import static org.junit.Assert.assertEquals; +import com.baeldung.spring.data.es.config.Config; +import com.baeldung.spring.data.es.model.Article; +import com.baeldung.spring.data.es.model.Author; +import com.baeldung.spring.data.es.service.ArticleService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = Config.class) @@ -124,7 +125,7 @@ public class ElasticSearchQueryIntegrationTest { @Test public void givenNestedObject_whenQueryByAuthorsName_thenFoundArticlesByThatAuthor() { - final QueryBuilder builder = nestedQuery("authors", boolQuery().must(termQuery("authors.name", "smith"))); + final QueryBuilder builder = nestedQuery("authors", boolQuery().must(termQuery("authors.name", "smith")), ScoreMode.None); final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build(); final List
    articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); @@ -134,7 +135,7 @@ public class ElasticSearchQueryIntegrationTest { @Test public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() { - final TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("title"); + final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags").field("title"); final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation) .execute().actionGet(); @@ -150,8 +151,8 @@ public class ElasticSearchQueryIntegrationTest { @Test public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() { - final TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags") - .order(Terms.Order.aggregation("_count", false)); + final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags") + .order(Terms.Order.count(false)); final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation) .execute().actionGet(); @@ -194,7 +195,7 @@ public class ElasticSearchQueryIntegrationTest { @Test public void givenBoolQuery_whenQueryByAuthorsName_thenFoundArticlesByThatAuthorAndFilteredTag() { - final QueryBuilder builder = boolQuery().must(nestedQuery("authors", boolQuery().must(termQuery("authors.name", "doe")))) + final QueryBuilder builder = boolQuery().must(nestedQuery("authors", boolQuery().must(termQuery("authors.name", "doe")), ScoreMode.None)) .filter(termQuery("tags", "elasticsearch")); final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder) diff --git a/spring-data-jpa/README.md b/spring-data-jpa/README.md new file mode 100644 index 0000000000..20e9d41839 --- /dev/null +++ b/spring-data-jpa/README.md @@ -0,0 +1,23 @@ +========= + +## Spring Data JPA Example Project + +### Relevant Articles: +- [Spring JPA – Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases) +- [Spring Data JPA – Adding a Method in All Repositories](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories) +- [Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced) +- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) +- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations) +- [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8) +- [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging) +- [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories) + +### Eclipse Config +After importing the project into Eclipse, you may see the following error: +"No persistence xml file found in project" + +This can be ignored: +- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" +Or: +- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator + diff --git a/spring-data-jpa/pom.xml b/spring-data-jpa/pom.xml new file mode 100644 index 0000000000..8691ce1f09 --- /dev/null +++ b/spring-data-jpa/pom.xml @@ -0,0 +1,66 @@ + + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + 4.0.0 + + spring-data-jpa + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.hibernate + hibernate-ehcache + + + org.hibernate + hibernate-envers + + + com.h2database + h2 + + + + org.springframework.security + spring-security-test + test + + + + com.google.guava + guava + 21.0 + + + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + org.junit.platform + junit-platform-launcher + ${junit-platform.version} + test + + + + \ No newline at end of file diff --git a/spring-data-jpa/src/main/java/com/baeldung/Application.java b/spring-data-jpa/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..72d29d9fa5 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/Application.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl; + +@SpringBootApplication +@EnableJpaRepositories(repositoryBaseClass = ExtendedRepositoryImpl.class) +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java new file mode 100644 index 0000000000..16407e510a --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java @@ -0,0 +1,102 @@ +package com.baeldung.config; + +import com.baeldung.services.IBarService; +import com.baeldung.services.impl.BarSpringDataJpaService; +import com.google.common.base.Preconditions; +import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl; +import com.baeldung.services.IFooService; +import com.baeldung.services.impl.FooService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.*; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.JpaVendorAdapter; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.sql.DataSource; +import java.util.Properties; + +@Configuration +@ComponentScan({"com.baeldung.dao", "com.baeldung.services"}) +@EnableTransactionManagement +@EnableJpaRepositories(basePackages = {"com.baeldung.dao"}, repositoryBaseClass = ExtendedRepositoryImpl.class) +@EnableJpaAuditing +@PropertySource("classpath:persistence.properties") +public class PersistenceConfiguration { + + @Autowired + private Environment env; + + public PersistenceConfiguration() { + super(); + } + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); + emf.setDataSource(dataSource()); + emf.setPackagesToScan("com.baeldung.domain"); + + final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + emf.setJpaVendorAdapter(vendorAdapter); + emf.setJpaProperties(hibernateProperties()); + + return emf; + } + + @Bean + public DataSource dataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + public PlatformTransactionManager transactionManager() { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + @Bean + public IBarService barSpringDataJpaService() { + return new BarSpringDataJpaService(); + } + + @Bean + public IFooService fooService() { + return new FooService(); + } + + private final Properties hibernateProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + + hibernateProperties.setProperty("hibernate.show_sql", "true"); + // hibernateProperties.setProperty("hibernate.format_sql", "true"); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + + // Envers properties + hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); + + return hibernateProperties; + } + +} \ No newline at end of file diff --git a/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java new file mode 100644 index 0000000000..207fba9bc5 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java @@ -0,0 +1,66 @@ +package com.baeldung.config; + +import com.google.common.base.Preconditions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; + +import javax.sql.DataSource; +import java.util.HashMap; + +@Configuration +@PropertySource({"classpath:persistence-multiple-db.properties"}) +@EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager") +public class PersistenceProductConfiguration { + @Autowired + private Environment env; + + public PersistenceProductConfiguration() { + super(); + } + + // + + @Bean + public LocalContainerEntityManagerFactoryBean productEntityManager() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(productDataSource()); + em.setPackagesToScan("com.baeldung.domain.product"); + + final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + final HashMap properties = new HashMap(); + properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); + em.setJpaPropertyMap(properties); + + return em; + } + + @Bean + public DataSource productDataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("product.jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + public PlatformTransactionManager productTransactionManager() { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(productEntityManager().getObject()); + return transactionManager; + } + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java new file mode 100644 index 0000000000..dd32477755 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java @@ -0,0 +1,70 @@ +package com.baeldung.config; + +import com.google.common.base.Preconditions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; + +import javax.sql.DataSource; +import java.util.HashMap; + +@Configuration +@PropertySource({"classpath:persistence-multiple-db.properties"}) +@EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager") +public class PersistenceUserConfiguration { + @Autowired + private Environment env; + + public PersistenceUserConfiguration() { + super(); + } + + // + + @Primary + @Bean + public LocalContainerEntityManagerFactoryBean userEntityManager() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(userDataSource()); + em.setPackagesToScan("com.baeldung.domain.user"); + + final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + final HashMap properties = new HashMap(); + properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); + em.setJpaPropertyMap(properties); + + return em; + } + + @Primary + @Bean + public DataSource userDataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("user.jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Primary + @Bean + public PlatformTransactionManager userTransactionManager() { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(userEntityManager().getObject()); + return transactionManager; + } + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/IFooDao.java b/spring-data-jpa/src/main/java/com/baeldung/dao/IFooDao.java new file mode 100644 index 0000000000..bb3c229945 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/IFooDao.java @@ -0,0 +1,12 @@ +package com.baeldung.dao; + +import com.baeldung.domain.Foo; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface IFooDao extends JpaRepository { + + @Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)") + Foo retrieveByName(@Param("name") String name); +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ArticleRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ArticleRepository.java new file mode 100644 index 0000000000..8402c099d9 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ArticleRepository.java @@ -0,0 +1,22 @@ +package com.baeldung.dao.repositories; + +import com.baeldung.domain.Article; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.Date; +import java.util.List; + +public interface ArticleRepository extends JpaRepository { + + List
    findAllByPublicationDate(Date publicationDate); + + List
    findAllByPublicationTimeBetween(Date publicationTimeStart, + Date publicationTimeEnd); + + @Query("select a from Article a where a.creationDateTime <= :creationDateTime") + List
    findAllWithCreationDateTimeBefore( + @Param("creationDateTime") Date creationDateTime); + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java new file mode 100644 index 0000000000..ba077ccf1f --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java @@ -0,0 +1,15 @@ +package com.baeldung.dao.repositories; + +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.Item; + +@Repository +public interface CustomItemRepository { + + void deleteCustom(Item entity); + + Item findItemById(Long id); + + void findThenDelete(Long id); +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemTypeRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemTypeRepository.java new file mode 100644 index 0000000000..81ebdf3fda --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemTypeRepository.java @@ -0,0 +1,13 @@ +package com.baeldung.dao.repositories; + +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.ItemType; + +@Repository +public interface CustomItemTypeRepository { + + void deleteCustom(ItemType entity); + + void findThenDelete(Long id); +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedRepository.java new file mode 100644 index 0000000000..9e82f02fa6 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedRepository.java @@ -0,0 +1,14 @@ +package com.baeldung.dao.repositories; + +import java.io.Serializable; +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.repository.NoRepositoryBean; + +@NoRepositoryBean +public interface ExtendedRepository extends JpaRepository { + + List findByAttributeContainsText(String attributeName, String text); + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedStudentRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedStudentRepository.java new file mode 100644 index 0000000000..199e4e5ff6 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedStudentRepository.java @@ -0,0 +1,6 @@ +package com.baeldung.dao.repositories; + +import com.baeldung.domain.Student; + +public interface ExtendedStudentRepository extends ExtendedRepository { +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/IBarCrudRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/IBarCrudRepository.java new file mode 100644 index 0000000000..54a7d77691 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/IBarCrudRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.dao.repositories; + +import com.baeldung.domain.Bar; +import org.springframework.data.repository.CrudRepository; + +import java.io.Serializable; + +public interface IBarCrudRepository extends CrudRepository { + // +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ItemTypeRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ItemTypeRepository.java new file mode 100644 index 0000000000..2af83bc322 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ItemTypeRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.dao.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.ItemType; + +@Repository +public interface ItemTypeRepository extends JpaRepository, CustomItemTypeRepository, CustomItemRepository { +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/LocationRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/LocationRepository.java new file mode 100644 index 0000000000..27bbe27af0 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/LocationRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.dao.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.Location; + +@Repository +public interface LocationRepository extends JpaRepository { +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ReadOnlyLocationRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ReadOnlyLocationRepository.java new file mode 100644 index 0000000000..8f68cdbbe5 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ReadOnlyLocationRepository.java @@ -0,0 +1,15 @@ +package com.baeldung.dao.repositories; + +import java.util.Optional; + +import org.springframework.data.repository.Repository; + +import com.baeldung.domain.Location; + +@org.springframework.stereotype.Repository +public interface ReadOnlyLocationRepository extends Repository { + + Optional findById(Long id); + + Location save(Location location); +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/StoreRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/StoreRepository.java new file mode 100644 index 0000000000..9318c32ee9 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/StoreRepository.java @@ -0,0 +1,13 @@ +package com.baeldung.dao.repositories; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.Store; + +@Repository +public interface StoreRepository extends JpaRepository { + List findStoreByLocationId(Long locationId); +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java new file mode 100644 index 0000000000..53def88af0 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java @@ -0,0 +1,32 @@ +package com.baeldung.dao.repositories.impl; + +import javax.persistence.EntityManager; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.Item; +import com.baeldung.dao.repositories.CustomItemRepository; + +@Repository +public class CustomItemRepositoryImpl implements CustomItemRepository { + + @Autowired + private EntityManager entityManager; + + @Override + public void deleteCustom(Item item) { + entityManager.remove(item); + } + + @Override + public Item findItemById(Long id) { + return entityManager.find(Item.class, id); + } + + @Override + public void findThenDelete(Long id) { + final Item item = entityManager.find(Item.class, id); + entityManager.remove(item); + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemTypeRepositoryImpl.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemTypeRepositoryImpl.java new file mode 100644 index 0000000000..2b49f2380c --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemTypeRepositoryImpl.java @@ -0,0 +1,31 @@ +package com.baeldung.dao.repositories.impl; + +import javax.persistence.EntityManager; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.ItemType; +import com.baeldung.dao.repositories.CustomItemTypeRepository; + +@Repository +public class CustomItemTypeRepositoryImpl implements CustomItemTypeRepository { + + private static final Logger LOGGER = LoggerFactory.getLogger(CustomItemTypeRepositoryImpl.class); + + @Autowired + private EntityManager entityManager; + + @Override + public void deleteCustom(ItemType itemType) { + entityManager.remove(itemType); + } + + @Override + public void findThenDelete(Long id) { + ItemType itemTypeToDelete = entityManager.find(ItemType.class, id); + entityManager.remove(itemTypeToDelete); + } +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/ExtendedRepositoryImpl.java similarity index 93% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/ExtendedRepositoryImpl.java index 7ed652dc4d..f6f06efb51 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/ExtendedRepositoryImpl.java @@ -1,4 +1,4 @@ -package org.baeldung.extended.persistence.dao; +package com.baeldung.dao.repositories.impl; import java.io.Serializable; import java.util.List; @@ -10,6 +10,7 @@ import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import javax.transaction.Transactional; +import com.baeldung.dao.repositories.ExtendedRepository; import org.springframework.data.jpa.repository.support.JpaEntityInformation; import org.springframework.data.jpa.repository.support.SimpleJpaRepository; diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java new file mode 100644 index 0000000000..7044d57e53 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.dao.repositories.product; + +import com.baeldung.domain.product.Product; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ProductRepository extends JpaRepository { + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/PossessionRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/PossessionRepository.java new file mode 100644 index 0000000000..f0eeb475c1 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/PossessionRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.dao.repositories.user; + +import com.baeldung.domain.user.Possession; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PossessionRepository extends JpaRepository { + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java new file mode 100644 index 0000000000..5bb0232e4a --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java @@ -0,0 +1,69 @@ +package com.baeldung.dao.repositories.user; + +import com.baeldung.domain.user.User; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.Collection; +import java.util.List; +import java.util.stream.Stream; + +public interface UserRepository extends JpaRepository { + + Stream findAllByName(String name); + + @Query("SELECT u FROM User u WHERE u.status = 1") + Collection findAllActiveUsers(); + + @Query(value = "SELECT * FROM USERS.USERS u WHERE u.status = 1", nativeQuery = true) + Collection findAllActiveUsersNative(); + + @Query("SELECT u FROM User u WHERE u.status = ?1") + User findUserByStatus(Integer status); + + @Query(value = "SELECT * FROM USERS.Users u WHERE u.status = ?1", nativeQuery = true) + User findUserByStatusNative(Integer status); + + @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") + User findUserByStatusAndName(Integer status, String name); + + @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") + User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name); + + @Query(value = "SELECT * FROM USERS.Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) + User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name); + + @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") + User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName); + + @Query("SELECT u FROM User u WHERE u.name like ?1%") + User findUserByNameLike(String name); + + @Query("SELECT u FROM User u WHERE u.name like :name%") + User findUserByNameLikeNamedParam(@Param("name") String name); + + @Query(value = "SELECT * FROM USERS.users u WHERE u.name LIKE ?1%", nativeQuery = true) + User findUserByNameLikeNative(String name); + + @Query(value = "SELECT u FROM User u") + List findAllUsers(Sort sort); + + @Query(value = "SELECT u FROM User u ORDER BY id") + Page findAllUsersWithPagination(Pageable pageable); + + @Query(value = "SELECT * FROM USERS.Users ORDER BY id", countQuery = "SELECT count(*) FROM USERS.Users", nativeQuery = true) + Page findAllUsersWithPaginationNative(Pageable pageable); + + @Modifying + @Query("update User u set u.status = :status where u.name = :name") + int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); + + @Modifying + @Query(value = "UPDATE USERS.Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) + int updateUserSetStatusForNameNative(Integer status, String name); +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate.java b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate.java new file mode 100644 index 0000000000..bf6ff0a0b9 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate.java @@ -0,0 +1,46 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Transient; + +import org.springframework.context.ApplicationEventPublisher; + +@Entity +class Aggregate { + @Transient + private ApplicationEventPublisher eventPublisher; + @Id + private long id; + + private Aggregate() { + } + + Aggregate(long id, ApplicationEventPublisher eventPublisher) { + this.id = id; + this.eventPublisher = eventPublisher; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "DomainEntity [id=" + id + "]"; + } + + void domainOperation() { + // some business logic + if (eventPublisher != null) { + eventPublisher.publishEvent(new DomainEvent()); + } + } + + long getId() { + return id; + } + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate2.java b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate2.java new file mode 100644 index 0000000000..3d2816299a --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate2.java @@ -0,0 +1,44 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Transient; + +import org.springframework.data.domain.AfterDomainEventPublication; +import org.springframework.data.domain.DomainEvents; + +@Entity +public class Aggregate2 { + @Transient + private final Collection domainEvents; + @Id + @GeneratedValue + private long id; + + public Aggregate2() { + domainEvents = new ArrayList<>(); + } + + @AfterDomainEventPublication + public void clearEvents() { + domainEvents.clear(); + } + + public void domainOperation() { + // some domain operation + domainEvents.add(new DomainEvent()); + } + + @DomainEvents + public Collection events() { + return domainEvents; + } + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate2Repository.java b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate2Repository.java new file mode 100644 index 0000000000..2a95abe347 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate2Repository.java @@ -0,0 +1,10 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import org.springframework.data.repository.CrudRepository; + +public interface Aggregate2Repository extends CrudRepository { + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate3.java b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate3.java new file mode 100644 index 0000000000..e0c3131b06 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate3.java @@ -0,0 +1,23 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +import org.springframework.data.domain.AbstractAggregateRoot; + +@Entity +public class Aggregate3 extends AbstractAggregateRoot { + @Id + @GeneratedValue + private long id; + + public void domainOperation() { + // some domain operation + registerEvent(new DomainEvent()); + } + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate3Repository.java b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate3Repository.java new file mode 100644 index 0000000000..e442bdb210 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate3Repository.java @@ -0,0 +1,14 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import org.springframework.data.repository.CrudRepository; + +/** + * @author goobar + * + */ +public interface Aggregate3Repository extends CrudRepository { + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/ddd/event/AggregateRepository.java b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/AggregateRepository.java new file mode 100644 index 0000000000..5a15156d03 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/AggregateRepository.java @@ -0,0 +1,10 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import org.springframework.data.repository.CrudRepository; + +public interface AggregateRepository extends CrudRepository { + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/ddd/event/DddConfig.java b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/DddConfig.java new file mode 100644 index 0000000000..1315b11875 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/DddConfig.java @@ -0,0 +1,15 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.PropertySource; + +@SpringBootConfiguration +@EnableAutoConfiguration +@PropertySource("classpath:/ddd.properties") +public class DddConfig { + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/ddd/event/DomainEvent.java b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/DomainEvent.java new file mode 100644 index 0000000000..1e6479d4fc --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/DomainEvent.java @@ -0,0 +1,8 @@ +/** + * + */ +package com.baeldung.ddd.event; + +class DomainEvent { + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/ddd/event/DomainService.java b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/DomainService.java new file mode 100644 index 0000000000..082c9bd88e --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/DomainService.java @@ -0,0 +1,31 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import javax.transaction.Transactional; + +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Service; + +@Service +public class DomainService { + private final ApplicationEventPublisher eventPublisher; + private final AggregateRepository repository; + + public DomainService(AggregateRepository repository, ApplicationEventPublisher eventPublisher) { + this.repository = repository; + this.eventPublisher = eventPublisher; + } + + @Transactional + public void serviceDomainOperation(long entityId) { + repository.findById(entityId) + .ifPresent(entity -> { + entity.domainOperation(); + repository.save(entity); + eventPublisher.publishEvent(new DomainEvent()); + }); + } + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Article.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Article.java new file mode 100644 index 0000000000..3b5a8be088 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Article.java @@ -0,0 +1,23 @@ +package com.baeldung.domain; + +import javax.persistence.*; +import java.util.Date; + +@Entity +public class Article { + + @Id + @GeneratedValue + private Integer id; + @Temporal(TemporalType.DATE) + private Date publicationDate; + @Temporal(TemporalType.TIME) + private Date publicationTime; + @Temporal(TemporalType.TIMESTAMP) + private Date creationDateTime; + + public Integer getId() { + return id; + } + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Bar.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Bar.java new file mode 100644 index 0000000000..efd297bafc --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Bar.java @@ -0,0 +1,220 @@ +package com.baeldung.domain; + +import com.google.common.collect.Sets; +import org.hibernate.annotations.OrderBy; +import org.hibernate.envers.Audited; +import org.jboss.logging.Logger; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Date; +import java.util.Set; + +@Entity +@NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b") +@Audited +@EntityListeners(AuditingEntityListener.class) +public class Bar implements Serializable { + + private static Logger logger = Logger.getLogger(Bar.class); + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private int id; + + @Column(name = "name") + private String name; + @OneToMany(mappedBy = "bar", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @OrderBy(clause = "NAME DESC") + // @NotAudited + private Set fooSet = Sets.newHashSet(); + @Column(name = "operation") + private String operation; + @Column(name = "timestamp") + private long timestamp; + @Column(name = "created_date", updatable = false, nullable = false) + @CreatedDate + private long createdDate; + @Column(name = "modified_date") + @LastModifiedDate + private long modifiedDate; + @Column(name = "created_by") + @CreatedBy + private String createdBy; + @Column(name = "modified_by") + @LastModifiedBy + private String modifiedBy; + + public Bar() { + super(); + } + + public Bar(final String name) { + super(); + + this.name = name; + } + + public Set getFooSet() { + return fooSet; + } + + // API + + public void setFooSet(final Set fooSet) { + this.fooSet = fooSet; + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public OPERATION getOperation() { + return OPERATION.parse(operation); + } + + public void setOperation(final String operation) { + this.operation = operation; + } + + public void setOperation(final OPERATION operation) { + this.operation = operation.getValue(); + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(final long timestamp) { + this.timestamp = timestamp; + } + + public long getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(final long createdDate) { + this.createdDate = createdDate; + } + + public long getModifiedDate() { + return modifiedDate; + } + + public void setModifiedDate(final long modifiedDate) { + this.modifiedDate = modifiedDate; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(final String createdBy) { + this.createdBy = createdBy; + } + + public String getModifiedBy() { + return modifiedBy; + } + + public void setModifiedBy(final String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Bar other = (Bar) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Bar [name=").append(name).append("]"); + return builder.toString(); + } + + @PrePersist + public void onPrePersist() { + logger.info("@PrePersist"); + audit(OPERATION.INSERT); + } + + @PreUpdate + public void onPreUpdate() { + logger.info("@PreUpdate"); + audit(OPERATION.UPDATE); + } + + @PreRemove + public void onPreRemove() { + logger.info("@PreRemove"); + audit(OPERATION.DELETE); + } + + private void audit(final OPERATION operation) { + setOperation(operation); + setTimestamp((new Date()).getTime()); + } + + public enum OPERATION { + INSERT, UPDATE, DELETE; + private String value; + + OPERATION() { + value = toString(); + } + + public static OPERATION parse(final String value) { + OPERATION operation = null; + for (final OPERATION op : OPERATION.values()) { + if (op.getValue().equals(value)) { + operation = op; + break; + } + } + return operation; + } + + public String getValue() { + return value; + } + } + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Foo.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Foo.java new file mode 100644 index 0000000000..ef88840746 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Foo.java @@ -0,0 +1,94 @@ +package com.baeldung.domain; + +import org.hibernate.envers.Audited; + +import javax.persistence.*; +import java.io.Serializable; + +@NamedNativeQueries({@NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class)}) +@Entity +@Audited +// @Proxy(lazy = false) +public class Foo implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private long id; + + @Column(name = "name", nullable = false) + private String name; + + @ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "BAR_ID") + private Bar bar = new Bar(); + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + this.name = name; + } + + // + + public Bar getBar() { + return bar; + } + + public void setBar(final Bar bar) { + this.bar = bar; + } + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + // + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Foo other = (Foo) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Foo [name=").append(name).append("]"); + return builder.toString(); + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Item.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Item.java new file mode 100644 index 0000000000..97ce14d92d --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Item.java @@ -0,0 +1,81 @@ +package com.baeldung.domain; + +import java.math.BigDecimal; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Item { + + private String color; + private String grade; + + @Id + private Long id; + + @ManyToOne + private ItemType itemType; + + private String name; + private BigDecimal price; + @ManyToOne + private Store store; + + public String getColor() { + return color; + } + + public String getGrade() { + return grade; + } + + public Long getId() { + return id; + } + + public ItemType getItemType() { + return itemType; + } + + public String getName() { + return name; + } + + public BigDecimal getPrice() { + return price; + } + + public Store getStore() { + return store; + } + + public void setColor(String color) { + this.color = color; + } + + public void setGrade(String grade) { + this.grade = grade; + } + + public void setId(Long id) { + this.id = id; + } + + public void setItemType(ItemType itemType) { + this.itemType = itemType; + } + + public void setName(String name) { + this.name = name; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public void setStore(Store store) { + this.store = store; + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/ItemType.java b/spring-data-jpa/src/main/java/com/baeldung/domain/ItemType.java new file mode 100644 index 0000000000..412079c2ae --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/ItemType.java @@ -0,0 +1,46 @@ +package com.baeldung.domain; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToMany; + +@Entity +public class ItemType { + + @Id + private Long id; + @OneToMany(cascade = CascadeType.ALL) + @JoinColumn(name = "ITEM_TYPE_ID") + private List items = new ArrayList<>(); + + private String name; + + public Long getId() { + return id; + } + + public List getItems() { + return items; + } + + public String getName() { + return name; + } + + public void setId(Long id) { + this.id = id; + } + + public void setItems(List items) { + this.items = items; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/KVTag.java b/spring-data-jpa/src/main/java/com/baeldung/domain/KVTag.java new file mode 100644 index 0000000000..b3e7d78b30 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/KVTag.java @@ -0,0 +1,34 @@ +package com.baeldung.domain; + +import javax.persistence.Embeddable; + +@Embeddable +public class KVTag { + private String key; + private String value; + + public KVTag() { + } + + public KVTag(String key, String value) { + super(); + this.key = key; + this.value = value; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Location.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Location.java new file mode 100644 index 0000000000..2178d378eb --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Location.java @@ -0,0 +1,55 @@ +package com.baeldung.domain; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToMany; + +@Entity +public class Location { + + private String city; + private String country; + @Id + private Long id; + + @OneToMany(cascade = CascadeType.ALL) + @JoinColumn(name = "LOCATION_ID") + private List stores = new ArrayList<>(); + + public String getCity() { + return city; + } + + public String getCountry() { + return country; + } + + public Long getId() { + return id; + } + + public List getStores() { + return stores; + } + + public void setCity(String city) { + this.city = city; + } + + public void setCountry(String country) { + this.country = country; + } + + public void setId(Long id) { + this.id = id; + } + + public void setStores(List stores) { + this.stores = stores; + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/SkillTag.java b/spring-data-jpa/src/main/java/com/baeldung/domain/SkillTag.java new file mode 100644 index 0000000000..1f2778c589 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/SkillTag.java @@ -0,0 +1,30 @@ +package com.baeldung.domain; + +import javax.persistence.Embeddable; + +@Embeddable +public class SkillTag { + private String name; + private int value; + + public SkillTag() { + } + + public SkillTag(String name, int value) { + super(); + this.name = name; + this.value = value; + } + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + public String getName() { + return name; + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Store.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Store.java new file mode 100644 index 0000000000..e04684c479 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Store.java @@ -0,0 +1,76 @@ +package com.baeldung.domain; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; + +@Entity +public class Store { + + private Boolean active; + @Id + private Long id; + @OneToMany(cascade = CascadeType.ALL) + @JoinColumn(name = "STORE_ID") + private List items = new ArrayList<>(); + private Long itemsSold; + + @ManyToOne + private Location location; + + private String name; + + public Boolean getActive() { + return active; + } + + public Long getId() { + return id; + } + + public List getItems() { + return items; + } + + public Long getItemsSold() { + return itemsSold; + } + + public Location getLocation() { + return location; + } + + public String getName() { + return name; + } + + public void setActive(Boolean active) { + this.active = active; + } + + public void setId(Long id) { + this.id = id; + } + + public void setItems(List items) { + this.items = items; + } + + public void setItemsSold(Long itemsSold) { + this.itemsSold = itemsSold; + } + + public void setLocation(Location location) { + this.location = location; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Student.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Student.java new file mode 100644 index 0000000000..bd7eaeb24b --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Student.java @@ -0,0 +1,74 @@ +package com.baeldung.domain; + +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.Id; +import java.util.ArrayList; +import java.util.List; + +@Entity +public class Student { + + @Id + private long id; + private String name; + + @ElementCollection + private List tags = new ArrayList<>(); + + @ElementCollection + private List skillTags = new ArrayList<>(); + + @ElementCollection + private List kvTags = new ArrayList<>(); + + public Student() { + } + + public Student(long id, String name) { + super(); + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags.addAll(tags); + } + + public List getSkillTags() { + return skillTags; + } + + public void setSkillTags(List skillTags) { + this.skillTags.addAll(skillTags); + } + + public List getKVTags() { + return this.kvTags; + } + + public void setKVTags(List kvTags) { + this.kvTags.addAll(kvTags); + } + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java b/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java new file mode 100644 index 0000000000..42e6dd8f45 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java @@ -0,0 +1,52 @@ +package com.baeldung.domain.product; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(schema = "products") +public class Product { + + @Id + private int id; + + private String name; + + private double price; + + public Product() { + super(); + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public double getPrice() { + return price; + } + + public void setPrice(final double price) { + this.price = price; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Product [name=").append(name).append(", id=").append(id).append("]"); + return builder.toString(); + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java b/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java new file mode 100644 index 0000000000..614e13df36 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java @@ -0,0 +1,86 @@ +package com.baeldung.domain.user; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(schema = "users") +public class Possession { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String name; + + public Possession() { + super(); + } + + public Possession(final String name) { + super(); + + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + (int) (id ^ (id >>> 32)); + result = (prime * result) + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Possession other = (Possession) obj; + if (id != other.id) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]"); + return builder.toString(); + } + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java b/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java new file mode 100644 index 0000000000..3a8b617d9a --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java @@ -0,0 +1,86 @@ +package com.baeldung.domain.user; + +import javax.persistence.*; +import java.util.List; + +@Entity +@Table(name = "users", schema = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int id; + private String name; + private int age; + @Column(unique = true, nullable = false) + private String email; + private Integer status; + @OneToMany + List possessionList; + + public User() { + super(); + } + + public User(String name, String email, Integer status) { + this.name = name; + this.email = email; + this.status = status; + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(final String email) { + this.email = email; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public int getAge() { + return age; + } + + public void setAge(final int age) { + this.age = age; + } + + public List getPossessionList() { + return possessionList; + } + + public void setPossessionList(List possessionList) { + this.possessionList = possessionList; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("User [name=").append(name).append(", id=").append(id).append("]"); + return builder.toString(); + } + +} \ No newline at end of file diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/IBarService.java b/spring-data-jpa/src/main/java/com/baeldung/services/IBarService.java new file mode 100644 index 0000000000..7e127488db --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/IBarService.java @@ -0,0 +1,7 @@ +package com.baeldung.services; + +import com.baeldung.domain.Bar; + +public interface IBarService extends IOperations { + // +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/IFooService.java b/spring-data-jpa/src/main/java/com/baeldung/services/IFooService.java new file mode 100644 index 0000000000..7e16ace5b6 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/IFooService.java @@ -0,0 +1,13 @@ +package com.baeldung.services; + +import com.baeldung.domain.Foo; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +public interface IFooService extends IOperations { + + Foo retrieveByName(String name); + + Page findPaginated(Pageable pageable); + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/IOperations.java b/spring-data-jpa/src/main/java/com/baeldung/services/IOperations.java new file mode 100644 index 0000000000..d50d465639 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/IOperations.java @@ -0,0 +1,26 @@ +package com.baeldung.services; + +import org.springframework.data.domain.Page; + +import java.io.Serializable; +import java.util.List; + +public interface IOperations { + + T findOne(final long id); + + List findAll(); + + Page findPaginated(int page, int size); + + // write + + T create(final T entity); + + T update(final T entity); + + void delete(final T entity); + + void deleteById(final long entityId); + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractService.java b/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractService.java new file mode 100644 index 0000000000..708524225b --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractService.java @@ -0,0 +1,61 @@ +package com.baeldung.services.impl; + +import com.baeldung.services.IOperations; +import com.google.common.collect.Lists; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.transaction.annotation.Transactional; + +import java.io.Serializable; +import java.util.List; + +@Transactional +public abstract class AbstractService implements IOperations { + + // read - one + + @Override + @Transactional(readOnly = true) + public T findOne(final long id) { + return getDao().findById(id).orElse(null); + } + + // read - all + + @Override + @Transactional(readOnly = true) + public List findAll() { + return Lists.newArrayList(getDao().findAll()); + } + + @Override + public Page findPaginated(final int page, final int size) { + return getDao().findAll(new PageRequest(page, size)); + } + + // write + + @Override + public T create(final T entity) { + return getDao().save(entity); + } + + @Override + public T update(final T entity) { + return getDao().save(entity); + } + + @Override + public void delete(final T entity) { + getDao().delete(entity); + } + + @Override + public void deleteById(final long entityId) { + getDao().deleteById(entityId); + } + + protected abstract PagingAndSortingRepository getDao(); + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractSpringDataJpaService.java b/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractSpringDataJpaService.java new file mode 100644 index 0000000000..28c86bee28 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractSpringDataJpaService.java @@ -0,0 +1,45 @@ +package com.baeldung.services.impl; + +import com.baeldung.services.IOperations; +import com.google.common.collect.Lists; +import org.springframework.data.repository.CrudRepository; +import org.springframework.transaction.annotation.Transactional; + +import java.io.Serializable; +import java.util.List; + +@Transactional(value = "transactionManager") +public abstract class AbstractSpringDataJpaService implements IOperations { + + @Override + public T findOne(final long id) { + return getDao().findById(id).orElse(null); + } + + @Override + public List findAll() { + return Lists.newArrayList(getDao().findAll()); + } + + @Override + public T create(final T entity) { + return getDao().save(entity); + } + + @Override + public T update(final T entity) { + return getDao().save(entity); + } + + @Override + public void delete(final T entity) { + getDao().delete(entity); + } + + @Override + public void deleteById(final long entityId) { + getDao().deleteById(entityId); + } + + protected abstract CrudRepository getDao(); +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/impl/BarSpringDataJpaService.java b/spring-data-jpa/src/main/java/com/baeldung/services/impl/BarSpringDataJpaService.java new file mode 100644 index 0000000000..ca3e5f868d --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/impl/BarSpringDataJpaService.java @@ -0,0 +1,30 @@ +package com.baeldung.services.impl; + +import com.baeldung.domain.Bar; +import com.baeldung.dao.repositories.IBarCrudRepository; +import com.baeldung.services.IBarService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.repository.CrudRepository; + +import java.io.Serializable; + +public class BarSpringDataJpaService extends AbstractSpringDataJpaService implements IBarService { + + @Autowired + private IBarCrudRepository dao; + + public BarSpringDataJpaService() { + super(); + } + + @Override + protected CrudRepository getDao() { + return dao; + } + + @Override + public Page findPaginated(int page, int size) { + throw new UnsupportedOperationException("Not implemented yet"); + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/impl/FooService.java b/spring-data-jpa/src/main/java/com/baeldung/services/impl/FooService.java new file mode 100644 index 0000000000..319ab3a825 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/impl/FooService.java @@ -0,0 +1,54 @@ +package com.baeldung.services.impl; + +import com.google.common.collect.Lists; +import com.baeldung.dao.IFooDao; +import com.baeldung.domain.Foo; +import com.baeldung.services.IFooService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class FooService extends AbstractService implements IFooService { + + @Autowired + private IFooDao dao; + + public FooService() { + super(); + } + + // API + + @Override + protected PagingAndSortingRepository getDao() { + return dao; + } + + // custom methods + + @Override + public Foo retrieveByName(final String name) { + return dao.retrieveByName(name); + } + + // overridden to be secured + + @Override + @Transactional(readOnly = true) + public List findAll() { + return Lists.newArrayList(getDao().findAll()); + } + + @Override + public Page findPaginated(Pageable pageable) { + return dao.findAll(pageable); + } + +} diff --git a/spring-data-jpa/src/main/resources/application.properties b/spring-data-jpa/src/main/resources/application.properties new file mode 100644 index 0000000000..73d72bc7d6 --- /dev/null +++ b/spring-data-jpa/src/main/resources/application.properties @@ -0,0 +1,15 @@ +# spring.datasource.x +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +spring.datasource.username=sa +spring.datasource.password=sa + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop +hibernate.cache.use_second_level_cache=true +hibernate.cache.use_query_cache=true +hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory + +spring.datasource.data=import_entities.sql \ No newline at end of file diff --git a/spring-data-jpa/src/main/resources/ddd.properties b/spring-data-jpa/src/main/resources/ddd.properties new file mode 100644 index 0000000000..e5126b694b --- /dev/null +++ b/spring-data-jpa/src/main/resources/ddd.properties @@ -0,0 +1 @@ +spring.datasource.initialization-mode=never \ No newline at end of file diff --git a/spring-data-jpa/src/main/resources/logback.xml b/spring-data-jpa/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-data-jpa/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-data-jpa/src/main/resources/persistence-multiple-db.properties b/spring-data-jpa/src/main/resources/persistence-multiple-db.properties new file mode 100644 index 0000000000..75534e8a54 --- /dev/null +++ b/spring-data-jpa/src/main/resources/persistence-multiple-db.properties @@ -0,0 +1,13 @@ +# jdbc.X +jdbc.driverClassName=org.h2.Driver +user.jdbc.url=jdbc:h2:mem:spring_jpa_user;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS +product.jdbc.url=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS PRODUCTS +jdbc.user=sa +jdbc.pass=sa + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create-drop +hibernate.cache.use_second_level_cache=false +hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/spring-data-jpa/src/main/resources/persistence.properties b/spring-data-jpa/src/main/resources/persistence.properties new file mode 100644 index 0000000000..3543e1b52b --- /dev/null +++ b/spring-data-jpa/src/main/resources/persistence.properties @@ -0,0 +1,16 @@ +# jdbc.X +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS +jdbc.user=sa +jdbc.pass=sa + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop +hibernate.cache.use_second_level_cache=true +hibernate.cache.use_query_cache=true +hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory + +# envers.X +envers.audit_table_suffix=_audit_log \ No newline at end of file diff --git a/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/ArticleRepositoryIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/ArticleRepositoryIntegrationTest.java new file mode 100644 index 0000000000..093e744003 --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/ArticleRepositoryIntegrationTest.java @@ -0,0 +1,69 @@ +package com.baeldung.dao.repositories; + +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.config.PersistenceProductConfiguration; +import com.baeldung.config.PersistenceUserConfiguration; +import com.baeldung.domain.Article; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringRunner.class) +@DataJpaTest(excludeAutoConfiguration = {PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class}) +public class ArticleRepositoryIntegrationTest { + + @Autowired + private ArticleRepository repository; + + @Test + public void givenImportedArticlesWhenFindAllByPublicationDateThenArticles1And2Returned() + throws Exception { + List
    result = repository.findAllByPublicationDate( + new SimpleDateFormat("yyyy-MM-dd").parse("2018-01-01") + ); + + assertEquals(2, result.size()); + assertTrue(result.stream() + .map(Article::getId) + .allMatch(id -> Arrays.asList(1, 2).contains(id)) + ); + } + + @Test + public void givenImportedArticlesWhenFindAllByPublicationTimeBetweenThenArticles2And3Returned() + throws Exception { + List
    result = repository.findAllByPublicationTimeBetween( + new SimpleDateFormat("HH:mm").parse("15:15"), + new SimpleDateFormat("HH:mm").parse("16:30") + ); + + assertEquals(2, result.size()); + assertTrue(result.stream() + .map(Article::getId) + .allMatch(id -> Arrays.asList(2, 3).contains(id)) + ); + } + + @Test + public void givenImportedArticlesWhenFindAllWithCreationDateTimeBeforeThenArticles2And3Returned() throws Exception { + List
    result = repository.findAllWithCreationDateTimeBefore( + new SimpleDateFormat("yyyy-MM-dd HH:mm").parse("2017-12-15 10:00") + ); + + assertEquals(2, result.size()); + assertTrue(result.stream() + .map(Article::getId) + .allMatch(id -> Arrays.asList(2, 3).contains(id)) + ); + } + +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/ExtendedStudentRepositoryIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/ExtendedStudentRepositoryIntegrationTest.java new file mode 100644 index 0000000000..b19a34df82 --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/ExtendedStudentRepositoryIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.dao.repositories; + +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.domain.Student; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.annotation.Resource; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = {PersistenceConfiguration.class}) +@DirtiesContext +public class ExtendedStudentRepositoryIntegrationTest { + @Resource + private ExtendedStudentRepository extendedStudentRepository; + + @Before + public void setup() { + Student student = new Student(1, "john"); + extendedStudentRepository.save(student); + Student student2 = new Student(2, "johnson"); + extendedStudentRepository.save(student2); + Student student3 = new Student(3, "tom"); + extendedStudentRepository.save(student3); + } + + @Test + public void givenStudents_whenFindByName_thenGetOk() { + List students = extendedStudentRepository.findByAttributeContainsText("name", "john"); + assertThat(students.size()).isEqualTo(2); + } +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/JpaRepositoriesIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/JpaRepositoriesIntegrationTest.java new file mode 100644 index 0000000000..01405c0b8a --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/JpaRepositoriesIntegrationTest.java @@ -0,0 +1,96 @@ +package com.baeldung.dao.repositories; + +import static junit.framework.TestCase.assertEquals; +import static junit.framework.TestCase.assertFalse; +import static junit.framework.TestCase.assertNotNull; +import static junit.framework.TestCase.assertNull; +import static junit.framework.TestCase.assertTrue; + +import java.util.List; +import java.util.Optional; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.config.PersistenceProductConfiguration; +import com.baeldung.config.PersistenceUserConfiguration; +import com.baeldung.domain.Item; +import com.baeldung.domain.ItemType; +import com.baeldung.domain.Location; +import com.baeldung.domain.Store; + +@RunWith(SpringRunner.class) +@DataJpaTest(excludeAutoConfiguration = { PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class }) +public class JpaRepositoriesIntegrationTest { + @Autowired + private LocationRepository locationRepository; + @Autowired + private StoreRepository storeRepository; + @Autowired + private ItemTypeRepository compositeRepository; + @Autowired + private ReadOnlyLocationRepository readOnlyRepository; + + @Test + public void whenSaveLocation_ThenGetSameLocation() { + Location location = new Location(); + location.setId(100L); + location.setCountry("Country H"); + location.setCity("City Hundred"); + location = locationRepository.saveAndFlush(location); + + Location otherLocation = locationRepository.getOne(location.getId()); + assertEquals("Country H", otherLocation.getCountry()); + assertEquals("City Hundred", otherLocation.getCity()); + + locationRepository.delete(otherLocation); + } + + @Test + public void givenLocationId_whenFindStores_thenGetStores() { + List stores = storeRepository.findStoreByLocationId(1L); + assertEquals(1, stores.size()); + } + + @Test + public void givenItemTypeId_whenDeleted_ThenItemTypeDeleted() { + Optional itemType = compositeRepository.findById(1L); + assertTrue(itemType.isPresent()); + compositeRepository.deleteCustom(itemType.get()); + itemType = compositeRepository.findById(1L); + assertFalse(itemType.isPresent()); + } + + @Test + public void givenItemId_whenUsingCustomRepo_ThenDeleteAppropriateEntity() { + Item item = compositeRepository.findItemById(1L); + assertNotNull(item); + compositeRepository.deleteCustom(item); + item = compositeRepository.findItemById(1L); + assertNull(item); + } + + @Test + public void givenItemAndItemType_WhenAmbiguousDeleteCalled_ThenItemTypeDeletedAndNotItem() { + Optional itemType = compositeRepository.findById(1L); + assertTrue(itemType.isPresent()); + Item item = compositeRepository.findItemById(2L); + assertNotNull(item); + + compositeRepository.findThenDelete(1L); + Optional sameItemType = compositeRepository.findById(1L); + assertFalse(sameItemType.isPresent()); + Item sameItem = compositeRepository.findItemById(2L); + assertNotNull(sameItem); + } + + @Test + public void whenCreatingReadOnlyRepo_thenHaveOnlyReadOnlyOperationsAvailable() { + Optional location = readOnlyRepository.findById(1L); + assertNotNull(location); + } +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java new file mode 100644 index 0000000000..e29161394b --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java @@ -0,0 +1,378 @@ +package com.baeldung.dao.repositories; + +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.dao.repositories.user.UserRepository; +import com.baeldung.domain.user.User; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.domain.JpaSort; +import org.springframework.data.mapping.PropertyReferenceException; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Collection; +import java.util.List; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Created by adam. + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PersistenceConfiguration.class) +@DirtiesContext +public class UserRepositoryIntegrationTest { + + private final String USER_NAME_ADAM = "Adam"; + private final String USER_NAME_PETER = "Peter"; + + private final String USER_EMAIL = "email@example.com"; + private final String USER_EMAIL2 = "email2@example.com"; + private final String USER_EMAIL3 = "email3@example.com"; + private final String USER_EMAIL4 = "email4@example.com"; + private final String USER_EMAIL5 = "email5@example.com"; + private final String USER_EMAIL6 = "email6@example.com"; + + private final Integer INACTIVE_STATUS = 0; + private final Integer ACTIVE_STATUS = 1; + + @Autowired + private UserRepository userRepository; + + @Test + @Transactional + public void givenUsersWithSameNameInDBWhenFindAllByNameThenReturnStreamOfUsers() { + User user1 = new User(); + user1.setName(USER_NAME_ADAM); + user1.setEmail(USER_EMAIL); + userRepository.save(user1); + + User user2 = new User(); + user2.setName(USER_NAME_ADAM); + user2.setEmail(USER_EMAIL2); + userRepository.save(user2); + + User user3 = new User(); + user3.setName(USER_NAME_ADAM); + user3.setEmail(USER_EMAIL3); + userRepository.save(user3); + + User user4 = new User(); + user4.setName("SAMPLE"); + user4.setEmail(USER_EMAIL4); + userRepository.save(user4); + + try (Stream foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) { + assertThat(foundUsersStream.count()).isEqualTo(3l); + } + } + + @Test + public void givenUsersInDBWhenFindAllWithQueryAnnotationThenReturnCollectionWithActiveUsers() { + User user1 = new User(); + user1.setName(USER_NAME_ADAM); + user1.setEmail(USER_EMAIL); + user1.setStatus(ACTIVE_STATUS); + userRepository.save(user1); + + User user2 = new User(); + user2.setName(USER_NAME_ADAM); + user2.setEmail(USER_EMAIL2); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User user3 = new User(); + user3.setName(USER_NAME_ADAM); + user3.setEmail(USER_EMAIL3); + user3.setStatus(INACTIVE_STATUS); + userRepository.save(user3); + + Collection allActiveUsers = userRepository.findAllActiveUsers(); + + assertThat(allActiveUsers.size()).isEqualTo(2); + } + + @Test + public void givenUsersInDBWhenFindAllWithQueryAnnotationNativeThenReturnCollectionWithActiveUsers() { + User user1 = new User(); + user1.setName(USER_NAME_ADAM); + user1.setEmail(USER_EMAIL); + user1.setStatus(ACTIVE_STATUS); + userRepository.save(user1); + + User user2 = new User(); + user2.setName(USER_NAME_ADAM); + user2.setEmail(USER_EMAIL2); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User user3 = new User(); + user3.setName(USER_NAME_ADAM); + user3.setEmail(USER_EMAIL3); + user3.setStatus(INACTIVE_STATUS); + userRepository.save(user3); + + Collection allActiveUsers = userRepository.findAllActiveUsersNative(); + + assertThat(allActiveUsers.size()).isEqualTo(2); + } + + @Test + public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationThenReturnActiveUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationNativeThenReturnActiveUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationIndexedParamsThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParamsThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNamesThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationIndexedParamsThenReturnUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByNameLike("Ad"); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNamedParamsThenReturnUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad"); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNativeThenReturnUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByNameLikeNative("Ad"); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindAllWithSortByNameThenReturnUsersSorted() { + userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS)); + + List usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + + assertThat(usersSortByName + .get(0) + .getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test(expected = PropertyReferenceException.class) + public void givenUsersInDBWhenFindAllSortWithFunctionThenThrowException() { + userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS)); + + userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + + List usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)")); + + assertThat(usersSortByNameLength + .get(0) + .getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindAllSortWithFunctionQueryAnnotationJPQLThenReturnUsersSorted() { + userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS)); + + userRepository.findAllUsers(new Sort("name")); + + List usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)")); + + assertThat(usersSortByNameLength + .get(0) + .getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationJPQLThenReturnPageOfUsers() { + userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", USER_EMAIL6, INACTIVE_STATUS)); + + Page usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3)); + + assertThat(usersPage + .getContent() + .get(0) + .getName()).isEqualTo("SAMPLE1"); + } + + @Test + public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationNativeThenReturnPageOfUsers() { + userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", USER_EMAIL6, INACTIVE_STATUS)); + + Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3)); + + assertThat(usersSortByNameLength + .getContent() + .get(0) + .getName()).isEqualTo("SAMPLE1"); + } + + @Test + @Transactional + public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationJPQLThenModifyMatchingUsers() { + userRepository.save(new User("SAMPLE", USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", USER_EMAIL4, ACTIVE_STATUS)); + + int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE"); + + assertThat(updatedUsersSize).isEqualTo(2); + } + + @Test + @Transactional + public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() { + userRepository.save(new User("SAMPLE", USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", USER_EMAIL4, ACTIVE_STATUS)); + userRepository.flush(); + + int updatedUsersSize = userRepository.updateUserSetStatusForNameNative(INACTIVE_STATUS, "SAMPLE"); + + assertThat(updatedUsersSize).isEqualTo(2); + } + + @After + public void cleanUp() { + userRepository.deleteAll(); + } + +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/ddd/event/Aggregate2EventsIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/ddd/event/Aggregate2EventsIntegrationTest.java new file mode 100644 index 0000000000..3f650d4d63 --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/ddd/event/Aggregate2EventsIntegrationTest.java @@ -0,0 +1,68 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +@SpringJUnitConfig +@SpringBootTest +class Aggregate2EventsIntegrationTest { + @MockBean + private TestEventHandler eventHandler; + @Autowired + private Aggregate2Repository repository; + + // @formatter:off + @DisplayName("given aggregate with @AfterDomainEventPublication," + + " when do domain operation and save twice," + + " then an event is published only for the first time") + // @formatter:on + @Test + void afterDomainEvents() { + // given + Aggregate2 aggregate = new Aggregate2(); + + // when + aggregate.domainOperation(); + repository.save(aggregate); + repository.save(aggregate); + + // then + verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); + } + + @BeforeEach + void beforeEach() { + repository.deleteAll(); + } + + // @formatter:off + @DisplayName("given aggregate with @DomainEvents," + + " when do domain operation and save," + + " then an event is published") + // @formatter:on + @Test + void domainEvents() { + // given + Aggregate2 aggregate = new Aggregate2(); + + // when + aggregate.domainOperation(); + repository.save(aggregate); + + // then + verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); + } + +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/ddd/event/Aggregate3EventsIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/ddd/event/Aggregate3EventsIntegrationTest.java new file mode 100644 index 0000000000..893dcac3f8 --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/ddd/event/Aggregate3EventsIntegrationTest.java @@ -0,0 +1,63 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +@SpringJUnitConfig +@SpringBootTest +class Aggregate3EventsIntegrationTest { + + @MockBean + private TestEventHandler eventHandler; + @Autowired + private Aggregate3Repository repository; + + // @formatter:off + @DisplayName("given aggregate extending AbstractAggregateRoot," + + " when do domain operation and save twice," + + " then an event is published only for the first time") + // @formatter:on + @Test + void afterDomainEvents() { + // given + Aggregate3 aggregate = new Aggregate3(); + + // when + aggregate.domainOperation(); + repository.save(aggregate); + repository.save(aggregate); + + // then + verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); + } + + // @formatter:off + @DisplayName("given aggregate extending AbstractAggregateRoot," + + " when do domain operation and save," + + " then an event is published") + // @formatter:on + @Test + void domainEvents() { + // given + Aggregate3 aggregate = new Aggregate3(); + + // when + aggregate.domainOperation(); + repository.save(aggregate); + + // then + verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); + } + +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/ddd/event/AggregateEventsIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/ddd/event/AggregateEventsIntegrationTest.java new file mode 100644 index 0000000000..f0e1147245 --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/ddd/event/AggregateEventsIntegrationTest.java @@ -0,0 +1,82 @@ +package com.baeldung.ddd.event; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.annotation.Bean; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +@SpringJUnitConfig +@SpringBootTest +class AggregateEventsIntegrationTest { + + @Autowired + private DomainService domainService; + + @MockBean + private TestEventHandler eventHandler; + @Autowired + private ApplicationEventPublisher eventPublisher; + @Autowired + private AggregateRepository repository; + + // @formatter:off + @DisplayName("given existing aggregate," + + " when do domain operation directly on aggregate," + + " then domain event is NOT published") + // @formatter:on + @Test + void aggregateEventsTest() { + Aggregate existingDomainEntity = new Aggregate(0, eventPublisher); + repository.save(existingDomainEntity); + + // when + repository.findById(existingDomainEntity.getId()) + .get() + .domainOperation(); + + // then + verifyZeroInteractions(eventHandler); + } + + @BeforeEach + void beforeEach() { + repository.deleteAll(); + } + + // @formatter:off + @DisplayName("given existing aggregate," + + " when do domain operation on service," + + " then domain event is published") + // @formatter:on + @Test + void serviceEventsTest() { + Aggregate existingDomainEntity = new Aggregate(1, eventPublisher); + repository.save(existingDomainEntity); + + // when + domainService.serviceDomainOperation(existingDomainEntity.getId()); + + // then + verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); + } + + @TestConfiguration + public static class TestConfig { + @Bean + public DomainService domainService(AggregateRepository repository, ApplicationEventPublisher eventPublisher) { + return new DomainService(repository, eventPublisher); + } + } + +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/ddd/event/TestEventHandler.java b/spring-data-jpa/src/test/java/com/baeldung/ddd/event/TestEventHandler.java new file mode 100644 index 0000000000..721402c17a --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/ddd/event/TestEventHandler.java @@ -0,0 +1,12 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import org.springframework.transaction.event.TransactionalEventListener; + +interface TestEventHandler { + @TransactionalEventListener + void handleEvent(DomainEvent event); + +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/services/AbstractServicePersistenceIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/services/AbstractServicePersistenceIntegrationTest.java new file mode 100644 index 0000000000..acac66f2f7 --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/services/AbstractServicePersistenceIntegrationTest.java @@ -0,0 +1,251 @@ +package com.baeldung.services; + +import com.baeldung.domain.Foo; +import com.baeldung.util.IDUtil; +import org.hamcrest.Matchers; +import org.junit.Ignore; +import org.junit.Test; +import org.springframework.dao.DataAccessException; + +import java.io.Serializable; +import java.util.List; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.*; + +public abstract class AbstractServicePersistenceIntegrationTest { + + // tests + + // find - one + + @Test + /**/public final void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoResourceIsReceived() { + // When + final Foo createdResource = getApi().findOne(IDUtil.randomPositiveLong()); + + // Then + assertNull(createdResource); + } + + @Test + public void givenResourceExists_whenResourceIsRetrieved_thenNoExceptions() { + final Foo existingResource = persistNewEntity(); + getApi().findOne(existingResource.getId()); + } + + @Test + public void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoExceptions() { + getApi().findOne(IDUtil.randomPositiveLong()); + } + + @Test + public void givenResourceExists_whenResourceIsRetrieved_thenTheResultIsNotNull() { + final Foo existingResource = persistNewEntity(); + final Foo retrievedResource = getApi().findOne(existingResource.getId()); + assertNotNull(retrievedResource); + } + + @Test + public void givenResourceExists_whenResourceIsRetrieved_thenResourceIsRetrievedCorrectly() { + final Foo existingResource = persistNewEntity(); + final Foo retrievedResource = getApi().findOne(existingResource.getId()); + assertEquals(existingResource, retrievedResource); + } + + // find - one - by name + + // find - all + + @Test + /**/public void whenAllResourcesAreRetrieved_thenNoExceptions() { + getApi().findAll(); + } + + @Test + /**/public void whenAllResourcesAreRetrieved_thenTheResultIsNotNull() { + final List resources = getApi().findAll(); + + assertNotNull(resources); + } + + @Test + /**/public void givenAtLeastOneResourceExists_whenAllResourcesAreRetrieved_thenRetrievedResourcesAreNotEmpty() { + persistNewEntity(); + + // When + final List allResources = getApi().findAll(); + + // Then + assertThat(allResources, not(Matchers. empty())); + } + + @Test + /**/public void givenAnResourceExists_whenAllResourcesAreRetrieved_thenTheExistingResourceIsIndeedAmongThem() { + final Foo existingResource = persistNewEntity(); + + final List resources = getApi().findAll(); + + assertThat(resources, hasItem(existingResource)); + } + + @Test + /**/public void whenAllResourcesAreRetrieved_thenResourcesHaveIds() { + persistNewEntity(); + + // When + final List allResources = getApi().findAll(); + + // Then + for (final Foo resource : allResources) { + assertNotNull(resource.getId()); + } + } + + // create + + @Test(expected = RuntimeException.class) + /**/public void whenNullResourceIsCreated_thenException() { + getApi().create(null); + } + + @Test + /**/public void whenResourceIsCreated_thenNoExceptions() { + persistNewEntity(); + } + + @Test + /**/public void whenResourceIsCreated_thenResourceIsRetrievable() { + final Foo existingResource = persistNewEntity(); + + assertNotNull(getApi().findOne(existingResource.getId())); + } + + @Test + /**/public void whenResourceIsCreated_thenSavedResourceIsEqualToOriginalResource() { + final Foo originalResource = createNewEntity(); + final Foo savedResource = getApi().create(originalResource); + + assertEquals(originalResource, savedResource); + } + + @Test(expected = RuntimeException.class) + public void whenResourceWithFailedConstraintsIsCreated_thenException() { + final Foo invalidResource = createNewEntity(); + invalidate(invalidResource); + + getApi().create(invalidResource); + } + + /** + * -- specific to the persistence engine + */ + @Test(expected = DataAccessException.class) + @Ignore("Hibernate simply ignores the id silently and still saved (tracking this)") + public void whenResourceWithIdIsCreated_thenDataAccessException() { + final Foo resourceWithId = createNewEntity(); + resourceWithId.setId(IDUtil.randomPositiveLong()); + + getApi().create(resourceWithId); + } + + // update + + @Test(expected = RuntimeException.class) + /**/public void whenNullResourceIsUpdated_thenException() { + getApi().update(null); + } + + @Test + /**/public void givenResourceExists_whenResourceIsUpdated_thenNoExceptions() { + // Given + final Foo existingResource = persistNewEntity(); + + // When + getApi().update(existingResource); + } + + /** + * - can also be the ConstraintViolationException which now occurs on the update operation will not be translated; as a consequence, it will be a TransactionSystemException + */ + @Test(expected = RuntimeException.class) + public void whenResourceIsUpdatedWithFailedConstraints_thenException() { + final Foo existingResource = persistNewEntity(); + invalidate(existingResource); + + getApi().update(existingResource); + } + + @Test + /**/public void givenResourceExists_whenResourceIsUpdated_thenUpdatesArePersisted() { + // Given + final Foo existingResource = persistNewEntity(); + + // When + change(existingResource); + getApi().update(existingResource); + + final Foo updatedResource = getApi().findOne(existingResource.getId()); + + // Then + assertEquals(existingResource, updatedResource); + } + + // delete + + // @Test(expected = RuntimeException.class) + // public void givenResourceDoesNotExists_whenResourceIsDeleted_thenException() { + // // When + // getApi().delete(IDUtil.randomPositiveLong()); + // } + // + // @Test(expected = RuntimeException.class) + // public void whenResourceIsDeletedByNegativeId_thenException() { + // // When + // getApi().delete(IDUtil.randomNegativeLong()); + // } + // + // @Test + // public void givenResourceExists_whenResourceIsDeleted_thenNoExceptions() { + // // Given + // final Foo existingResource = persistNewEntity(); + // + // // When + // getApi().delete(existingResource.getId()); + // } + // + // @Test + // /**/public final void givenResourceExists_whenResourceIsDeleted_thenResourceNoLongerExists() { + // // Given + // final Foo existingResource = persistNewEntity(); + // + // // When + // getApi().delete(existingResource.getId()); + // + // // Then + // assertNull(getApi().findOne(existingResource.getId())); + // } + + // template method + + protected Foo createNewEntity() { + return new Foo(randomAlphabetic(6)); + } + + protected abstract IOperations getApi(); + + private final void invalidate(final Foo entity) { + entity.setName(null); + } + + private final void change(final Foo entity) { + entity.setName(randomAlphabetic(6)); + } + + protected Foo persistNewEntity() { + return getApi().create(createNewEntity()); + } + +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/services/FooServicePersistenceIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/services/FooServicePersistenceIntegrationTest.java new file mode 100644 index 0000000000..fd17d033e1 --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/services/FooServicePersistenceIntegrationTest.java @@ -0,0 +1,75 @@ +package com.baeldung.services; + +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.domain.Foo; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.dao.InvalidDataAccessApiUsageException; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = {PersistenceConfiguration.class}, loader = AnnotationConfigContextLoader.class) +public class FooServicePersistenceIntegrationTest extends AbstractServicePersistenceIntegrationTest { + + @Autowired + private IFooService service; + + // tests + + @Test + public final void whenContextIsBootstrapped_thenNoExceptions() { + // + } + + @Test + public final void whenEntityIsCreated_thenNoExceptions() { + service.create(new Foo(randomAlphabetic(6))); + } + + @Test(expected = DataIntegrityViolationException.class) + public final void whenInvalidEntityIsCreated_thenDataException() { + service.create(new Foo()); + } + + @Test(expected = DataIntegrityViolationException.class) + public final void whenEntityWithLongNameIsCreated_thenDataException() { + service.create(new Foo(randomAlphabetic(2048))); + } + + // custom Query method + + @Test + public final void givenUsingCustomQuery_whenRetrievingEntity_thenFound() { + final String name = randomAlphabetic(6); + service.create(new Foo(name)); + + final Foo retrievedByName = service.retrieveByName(name); + assertNotNull(retrievedByName); + } + + // work in progress + + @Test(expected = InvalidDataAccessApiUsageException.class) + @Ignore("Right now, persist has saveOrUpdate semantics, so this will no longer fail") + public final void whenSameEntityIsCreatedTwice_thenDataException() { + final Foo entity = new Foo(randomAlphabetic(8)); + service.create(entity); + service.create(entity); + } + + // API + + @Override + protected final IOperations getApi() { + return service; + } + +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/services/JpaMultipleDBIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/services/JpaMultipleDBIntegrationTest.java new file mode 100644 index 0000000000..71a3fb0b44 --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/services/JpaMultipleDBIntegrationTest.java @@ -0,0 +1,100 @@ +package com.baeldung.services; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.Collections; +import java.util.Optional; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.config.PersistenceProductConfiguration; +import com.baeldung.config.PersistenceUserConfiguration; +import com.baeldung.dao.repositories.product.ProductRepository; +import com.baeldung.dao.repositories.user.PossessionRepository; +import com.baeldung.dao.repositories.user.UserRepository; +import com.baeldung.domain.product.Product; +import com.baeldung.domain.user.Possession; +import com.baeldung.domain.user.User; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = { PersistenceUserConfiguration.class, PersistenceProductConfiguration.class }) +@EnableTransactionManagement +@DirtiesContext +public class JpaMultipleDBIntegrationTest { + + @Autowired + private UserRepository userRepository; + + @Autowired + private PossessionRepository possessionRepository; + + @Autowired + private ProductRepository productRepository; + + // tests + + @Test + @Transactional("userTransactionManager") + public void whenCreatingUser_thenCreated() { + User user = new User(); + user.setName("John"); + user.setEmail("john@test.com"); + user.setAge(20); + Possession p = new Possession("sample"); + p = possessionRepository.save(p); + user.setPossessionList(Collections.singletonList(p)); + user = userRepository.save(user); + final Optional result = userRepository.findById(user.getId()); + assertTrue(result.isPresent()); + System.out.println(result.get().getPossessionList()); + assertEquals(1, result.get().getPossessionList().size()); + } + + @Test + @Transactional("userTransactionManager") + public void whenCreatingUsersWithSameEmail_thenRollback() { + User user1 = new User(); + user1.setName("John"); + user1.setEmail("john@test.com"); + user1.setAge(20); + user1 = userRepository.save(user1); + assertTrue(userRepository.findById(user1.getId()).isPresent()); + + User user2 = new User(); + user2.setName("Tom"); + user2.setEmail("john@test.com"); + user2.setAge(10); + try { + user2 = userRepository.save(user2); + userRepository.flush(); + fail("DataIntegrityViolationException should be thrown!"); + } catch (final DataIntegrityViolationException e) { + // Expected + } catch (final Exception e) { + fail("DataIntegrityViolationException should be thrown, instead got: " + e); + } + } + + @Test + @Transactional("productTransactionManager") + public void whenCreatingProduct_thenCreated() { + Product product = new Product(); + product.setName("Book"); + product.setId(2); + product.setPrice(20); + product = productRepository.save(product); + + assertTrue(productRepository.findById(product.getId()).isPresent()); + } + +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/services/SpringDataJPABarAuditIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/services/SpringDataJPABarAuditIntegrationTest.java new file mode 100644 index 0000000000..f3b857c73d --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/services/SpringDataJPABarAuditIntegrationTest.java @@ -0,0 +1,76 @@ +package com.baeldung.services; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.domain.Bar; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = { PersistenceConfiguration.class }, loader = AnnotationConfigContextLoader.class) +public class SpringDataJPABarAuditIntegrationTest { + + private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + logger.info("setUpBeforeClass()"); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + logger.info("tearDownAfterClass()"); + } + + @Autowired + @Qualifier("barSpringDataJpaService") + private IBarService barService; + + @Autowired + private EntityManagerFactory entityManagerFactory; + + private EntityManager em; + + @Before + public void setUp() throws Exception { + logger.info("setUp()"); + em = entityManagerFactory.createEntityManager(); + } + + @After + public void tearDown() throws Exception { + logger.info("tearDown()"); + em.close(); + } + + @Test + @WithMockUser(username = "tutorialuser") + public final void whenBarsModified_thenBarsAudited() { + Bar bar = new Bar("BAR1"); + barService.create(bar); + assertEquals(bar.getCreatedDate(), bar.getModifiedDate()); + assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); + bar.setName("BAR2"); + bar = barService.update(bar); + assertTrue(bar.getCreatedDate() < bar.getModifiedDate()); + assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); + } +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/util/IDUtil.java b/spring-data-jpa/src/test/java/com/baeldung/util/IDUtil.java new file mode 100644 index 0000000000..45e72e046d --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/util/IDUtil.java @@ -0,0 +1,33 @@ +package com.baeldung.util; + +import java.util.Random; + +public final class IDUtil { + + private IDUtil() { + throw new AssertionError(); + } + + // API + + public static String randomPositiveLongAsString() { + return Long.toString(randomPositiveLong()); + } + + public static String randomNegativeLongAsString() { + return Long.toString(randomNegativeLong()); + } + + public static long randomPositiveLong() { + long id = new Random().nextLong() * 10000; + id = (id < 0) ? (-1 * id) : id; + return id; + } + + private static long randomNegativeLong() { + long id = new Random().nextLong() * 10000; + id = (id > 0) ? (-1 * id) : id; + return id; + } + +} diff --git a/spring-data-jpa/src/test/resources/import_entities.sql b/spring-data-jpa/src/test/resources/import_entities.sql new file mode 100644 index 0000000000..deb9d07f05 --- /dev/null +++ b/spring-data-jpa/src/test/resources/import_entities.sql @@ -0,0 +1,21 @@ +insert into Article(id, publication_date, publication_time, creation_date_time) values(1, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:00', 'HH24:MI'), TO_DATE('31/12/2017 07:30', 'DD/MM/YYYY HH24:MI')); +insert into Article(id, publication_date, publication_time, creation_date_time) values(2, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:30', 'HH24:MI'), TO_DATE('15/12/2017 08:00', 'DD/MM/YYYY HH24:MI')); +insert into Article(id, publication_date, publication_time, creation_date_time) values(3, TO_DATE('15/12/2017', 'DD/MM/YYYY'), TO_DATE('16:00', 'HH24:MI'), TO_DATE('01/12/2017 13:45', 'DD/MM/YYYY HH24:MI')); + +insert into location (id, country, city) values (1, 'Country X', 'City One'); +insert into location (id, country, city) values (2, 'Country X', 'City Two'); +insert into location (id, country, city) values (3, 'Country X', 'City Three'); + +insert into store (id, name, location_id, items_sold, active) values (1, 'Store One', 3, 130000, true); +insert into store (id, name, location_id, items_sold, active) values (2, 'Store Two', 1, 170000, false); + +insert into item_type (id, name) values (1, 'Food'); +insert into item_type (id, name) values (2, 'Furniture'); +insert into item_type (id, name) values (3, 'Electronics'); + +insert into item (id, name, store_id, item_type_id, price, grade, color) values (1, 'Food Item One', 1, 1, 100, 'A', 'Color x'); +insert into item (id, name, store_id, item_type_id, price, grade, color) values (2, 'Furniture Item One', 1, 2, 2500, 'B', 'Color y'); +insert into item (id, name, store_id, item_type_id, price, grade, color) values (3, 'Food Item Two', 1, 1, 35, 'A', 'Color z'); +insert into item (id, name, store_id, item_type_id, price, grade, color) values (5, 'Furniture Item Two', 2, 2, 1600, 'A', 'Color w'); +insert into item (id, name, store_id, item_type_id, price, grade, color) values (6, 'Food Item Three', 2, 1, 5, 'B', 'Color a'); +insert into item (id, name, store_id, item_type_id, price, grade, color) values (7, 'Electronics Item One', 2, 3, 999, 'B', 'Color b'); diff --git a/spring-data-keyvalue/README.md b/spring-data-keyvalue/README.md new file mode 100644 index 0000000000..f76cf4d5ac --- /dev/null +++ b/spring-data-keyvalue/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [A Guide to Spring Data Key Value](http://www.baeldung.com/spring-data-key-value) diff --git a/spring-data-keyvalue/pom.xml b/spring-data-keyvalue/pom.xml index e90f18948f..6ab928303d 100644 --- a/spring-data-keyvalue/pom.xml +++ b/spring-data-keyvalue/pom.xml @@ -1,37 +1,37 @@ - 4.0.0 - com.baeldung - spring-data-keyvalue - 1.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-data-keyvalue + 1.0 - - org.springframework.boot - spring-boot-starter-parent - 2.0.1.RELEASE - - + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + - - 2.0.3.RELEASE - + - + + org.springframework.boot + spring-boot-starter + - - org.springframework.boot - spring-boot-starter - + + org.springframework.data + spring-data-keyvalue + - - org.springframework.data - spring-data-keyvalue - + + org.springframework.boot + spring-boot-starter-test + + - - org.springframework.boot - spring-boot-starter-test - - + + 2.0.3.RELEASE + \ No newline at end of file diff --git a/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/EmployeeService.java b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/EmployeeService.java index dd89609be7..83117b3baa 100644 --- a/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/EmployeeService.java +++ b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/EmployeeService.java @@ -1,12 +1,14 @@ package com.baeldung.spring.data.keyvalue.services; +import java.util.Optional; + import com.baeldung.spring.data.keyvalue.vo.Employee; public interface EmployeeService { void save(Employee employee); - Employee get(Integer id); + Optional get(Integer id); Iterable fetchAll(); diff --git a/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithKeyValueTemplate.java b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithKeyValueTemplate.java index 26f1756add..3eb1d0f66a 100644 --- a/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithKeyValueTemplate.java +++ b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithKeyValueTemplate.java @@ -27,9 +27,8 @@ public class EmployeeServicesWithKeyValueTemplate implements EmployeeService { } @Override - public Employee get(Integer id) { - Optional employee = keyValueTemplate.findById(id, Employee.class); - return employee.isPresent() ? employee.get() : null; + public Optional get(Integer id) { + return keyValueTemplate.findById(id, Employee.class); } @Override diff --git a/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithRepository.java b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithRepository.java index 73f3493a6b..70e00dadc0 100644 --- a/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithRepository.java +++ b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithRepository.java @@ -1,5 +1,7 @@ package com.baeldung.spring.data.keyvalue.services.impl; +import java.util.Optional; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -26,8 +28,8 @@ public class EmployeeServicesWithRepository implements EmployeeService { } @Override - public Employee get(Integer id) { - return employeeRepository.findById(id).get(); + public Optional get(Integer id) { + return employeeRepository.findById(id); } @Override diff --git a/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/vo/Employee.java b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/vo/Employee.java index 208e6e1735..1063c578f3 100644 --- a/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/vo/Employee.java +++ b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/vo/Employee.java @@ -6,7 +6,7 @@ import org.springframework.data.annotation.Id; import org.springframework.data.keyvalue.annotation.KeySpace; @KeySpace("employees") -public class Employee implements Serializable { +public class Employee { @Id private Integer id; diff --git a/spring-data-keyvalue/src/main/resources/logback.xml b/spring-data-keyvalue/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-data-keyvalue/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-data-keyvalue/src/test/java/com/baeldung/spring/data/keyvalue/services/test/EmployeeServicesWithKeyValueRepositoryIntegrationTest.java b/spring-data-keyvalue/src/test/java/com/baeldung/spring/data/keyvalue/services/test/EmployeeServicesWithKeyValueRepositoryIntegrationTest.java index e376f1b804..37b0a69a2d 100644 --- a/spring-data-keyvalue/src/test/java/com/baeldung/spring/data/keyvalue/services/test/EmployeeServicesWithKeyValueRepositoryIntegrationTest.java +++ b/spring-data-keyvalue/src/test/java/com/baeldung/spring/data/keyvalue/services/test/EmployeeServicesWithKeyValueRepositoryIntegrationTest.java @@ -50,7 +50,7 @@ public class EmployeeServicesWithKeyValueRepositoryIntegrationTest { @Test public void test2_whenEmployeeGet_thenEmployeeIsReturnedFromMap() { - Employee employeeFetched = employeeService.get(1); + Employee employeeFetched = employeeService.get(1).get(); assertEquals(employeeFetched, employee1); } diff --git a/spring-data-keyvalue/src/test/java/com/baeldung/spring/data/keyvalue/services/test/EmployeeServicesWithRepositoryIntegrationTest.java b/spring-data-keyvalue/src/test/java/com/baeldung/spring/data/keyvalue/services/test/EmployeeServicesWithRepositoryIntegrationTest.java index bb034d6aee..d0ed1506f8 100644 --- a/spring-data-keyvalue/src/test/java/com/baeldung/spring/data/keyvalue/services/test/EmployeeServicesWithRepositoryIntegrationTest.java +++ b/spring-data-keyvalue/src/test/java/com/baeldung/spring/data/keyvalue/services/test/EmployeeServicesWithRepositoryIntegrationTest.java @@ -46,7 +46,7 @@ public class EmployeeServicesWithRepositoryIntegrationTest { @Test public void test2_whenEmployeeGet_thenEmployeeIsReturnedFromMap() { - Employee employeeFetched = employeeService.get(1); + Employee employeeFetched = employeeService.get(1).get(); assertEquals(employeeFetched, employee1); } diff --git a/spring-data-mongodb/README.md b/spring-data-mongodb/README.md index c2a1f703b5..4e12a2218a 100644 --- a/spring-data-mongodb/README.md +++ b/spring-data-mongodb/README.md @@ -10,3 +10,4 @@ - [GridFS in Spring Data MongoDB](http://www.baeldung.com/spring-data-mongodb-gridfs) - [Introduction to Spring Data MongoDB](http://www.baeldung.com/spring-data-mongodb-tutorial) - [Spring Data MongoDB: Projections and Aggregations](http://www.baeldung.com/spring-data-mongodb-projections-aggregations) +- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations) diff --git a/spring-data-mongodb/pom.xml b/spring-data-mongodb/pom.xml index 24847aaec6..332245adc8 100644 --- a/spring-data-mongodb/pom.xml +++ b/spring-data-mongodb/pom.xml @@ -1,5 +1,5 @@ + 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-data-mongodb @@ -8,9 +8,9 @@ com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring + parent-spring-4 + 0.0.1-SNAPSHOT + ../parent-spring-4 @@ -22,7 +22,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -33,7 +33,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -70,8 +70,6 @@ - UTF-8 - 4.3.4.RELEASE 1.10.4.RELEASE 2.9.0 4.1.4 diff --git a/spring-data-mongodb/src/main/java/org/baeldung/annotation/CascadeSave.java b/spring-data-mongodb/src/main/java/com/baeldung/annotation/CascadeSave.java similarity index 88% rename from spring-data-mongodb/src/main/java/org/baeldung/annotation/CascadeSave.java rename to spring-data-mongodb/src/main/java/com/baeldung/annotation/CascadeSave.java index aae0214d09..3e43221aff 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/annotation/CascadeSave.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/annotation/CascadeSave.java @@ -1,4 +1,4 @@ -package org.baeldung.annotation; +package com.baeldung.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/config/MongoConfig.java b/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java similarity index 84% rename from spring-data-mongodb/src/main/java/org/baeldung/config/MongoConfig.java rename to spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java index 80b177f4c9..551a9142a6 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/config/MongoConfig.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java @@ -1,10 +1,10 @@ -package org.baeldung.config; +package com.baeldung.config; import com.mongodb.Mongo; import com.mongodb.MongoClient; -import org.baeldung.converter.UserWriterConverter; -import org.baeldung.event.CascadeSaveMongoEventListener; -import org.baeldung.event.UserCascadeSaveMongoEventListener; +import com.baeldung.converter.UserWriterConverter; +import com.baeldung.event.CascadeSaveMongoEventListener; +import com.baeldung.event.UserCascadeSaveMongoEventListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.converter.Converter; @@ -17,7 +17,7 @@ import java.util.ArrayList; import java.util.List; @Configuration -@EnableMongoRepositories(basePackages = "org.baeldung.repository") +@EnableMongoRepositories(basePackages = "com.baeldung.repository") public class MongoConfig extends AbstractMongoConfiguration { private final List> converters = new ArrayList>(); @@ -34,7 +34,7 @@ public class MongoConfig extends AbstractMongoConfiguration { @Override public String getMappingBasePackage() { - return "org.baeldung"; + return "com.baeldung"; } @Bean diff --git a/spring-data-mongodb/src/main/java/org/baeldung/config/SimpleMongoConfig.java b/spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java similarity index 86% rename from spring-data-mongodb/src/main/java/org/baeldung/config/SimpleMongoConfig.java rename to spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java index 9653796d8d..95f192811f 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/config/SimpleMongoConfig.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import com.mongodb.Mongo; import com.mongodb.MongoClient; @@ -8,7 +8,7 @@ import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; @Configuration -@EnableMongoRepositories(basePackages = "org.baeldung.repository") +@EnableMongoRepositories(basePackages = "com.baeldung.repository") public class SimpleMongoConfig { @Bean diff --git a/spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java b/spring-data-mongodb/src/main/java/com/baeldung/converter/UserWriterConverter.java similarity index 92% rename from spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java rename to spring-data-mongodb/src/main/java/com/baeldung/converter/UserWriterConverter.java index 4a6970489e..542ebb2c85 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/converter/UserWriterConverter.java @@ -1,8 +1,8 @@ -package org.baeldung.converter; +package com.baeldung.converter; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; -import org.baeldung.model.User; +import com.baeldung.model.User; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java b/spring-data-mongodb/src/main/java/com/baeldung/event/CascadeCallback.java similarity index 95% rename from spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java rename to spring-data-mongodb/src/main/java/com/baeldung/event/CascadeCallback.java index 94cad4566a..6ce5747793 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/event/CascadeCallback.java @@ -1,8 +1,8 @@ -package org.baeldung.event; +package com.baeldung.event; import java.lang.reflect.Field; -import org.baeldung.annotation.CascadeSave; +import com.baeldung.annotation.CascadeSave; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.util.ReflectionUtils; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java b/spring-data-mongodb/src/main/java/com/baeldung/event/CascadeSaveMongoEventListener.java similarity index 96% rename from spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java rename to spring-data-mongodb/src/main/java/com/baeldung/event/CascadeSaveMongoEventListener.java index acc377011d..499e727a90 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/event/CascadeSaveMongoEventListener.java @@ -1,4 +1,4 @@ -package org.baeldung.event; +package com.baeldung.event; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/FieldCallback.java b/spring-data-mongodb/src/main/java/com/baeldung/event/FieldCallback.java similarity index 95% rename from spring-data-mongodb/src/main/java/org/baeldung/event/FieldCallback.java rename to spring-data-mongodb/src/main/java/com/baeldung/event/FieldCallback.java index c6bd90d4f3..5e478270c1 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/FieldCallback.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/event/FieldCallback.java @@ -1,4 +1,4 @@ -package org.baeldung.event; +package com.baeldung.event; import java.lang.reflect.Field; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java b/spring-data-mongodb/src/main/java/com/baeldung/event/UserCascadeSaveMongoEventListener.java similarity index 92% rename from spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java rename to spring-data-mongodb/src/main/java/com/baeldung/event/UserCascadeSaveMongoEventListener.java index ade20bcc1d..832e3563f9 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/event/UserCascadeSaveMongoEventListener.java @@ -1,6 +1,6 @@ -package org.baeldung.event; +package com.baeldung.event; -import org.baeldung.model.User; +import com.baeldung.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/model/EmailAddress.java b/spring-data-mongodb/src/main/java/com/baeldung/model/EmailAddress.java similarity index 94% rename from spring-data-mongodb/src/main/java/org/baeldung/model/EmailAddress.java rename to spring-data-mongodb/src/main/java/com/baeldung/model/EmailAddress.java index 6db7d160d7..13fe340f69 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/model/EmailAddress.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/model/EmailAddress.java @@ -1,4 +1,4 @@ -package org.baeldung.model; +package com.baeldung.model; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; diff --git a/spring-data-mongodb/src/main/java/com/baeldung/model/User.java b/spring-data-mongodb/src/main/java/com/baeldung/model/User.java new file mode 100644 index 0000000000..1bbe49ee1d --- /dev/null +++ b/spring-data-mongodb/src/main/java/com/baeldung/model/User.java @@ -0,0 +1,93 @@ +package com.baeldung.model; + +import com.baeldung.annotation.CascadeSave; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.PersistenceConstructor; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.index.CompoundIndex; +import org.springframework.data.mongodb.core.index.CompoundIndexes; +import org.springframework.data.mongodb.core.index.IndexDirection; +import org.springframework.data.mongodb.core.index.Indexed; +import org.springframework.data.mongodb.core.mapping.DBRef; +import org.springframework.data.mongodb.core.mapping.Document; +import org.springframework.data.mongodb.core.mapping.Field; + +import com.querydsl.core.annotations.QueryEntity; + +@QueryEntity +@Document +@CompoundIndexes({ @CompoundIndex(name = "email_age", def = "{'email.id' : 1, 'age': 1}") }) +public class User { + + @Id + private String id; + @Indexed(direction = IndexDirection.ASCENDING) + private String name; + @Indexed(direction = IndexDirection.ASCENDING) + private Integer age; + + @DBRef + @Field("email") + @CascadeSave + private EmailAddress emailAddress; + + @Transient + private Integer yearOfBirth; + + public User() { + } + + public User(String name, Integer age) { + this.name = name; + this.age = age; + } + + @PersistenceConstructor + public User(final String name, @Value("#root.age ?: 0") final Integer age, final EmailAddress emailAddress) { + this.name = name; + this.age = age; + this.emailAddress = emailAddress; + } + + public String getId() { + return id; + } + + public void setId(final String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(final Integer age) { + this.age = age; + } + + public EmailAddress getEmailAddress() { + return emailAddress; + } + + public void setEmailAddress(final EmailAddress emailAddress) { + this.emailAddress = emailAddress; + } + + public Integer getYearOfBirth() { + return yearOfBirth; + } + + public void setYearOfBirth(final Integer yearOfBirth) { + this.yearOfBirth = yearOfBirth; + } + +} diff --git a/spring-data-mongodb/src/main/java/com/baeldung/repository/UserRepository.java b/spring-data-mongodb/src/main/java/com/baeldung/repository/UserRepository.java new file mode 100644 index 0000000000..e9dc0f5c95 --- /dev/null +++ b/spring-data-mongodb/src/main/java/com/baeldung/repository/UserRepository.java @@ -0,0 +1,35 @@ +package com.baeldung.repository; + +import com.baeldung.model.User; +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.data.mongodb.repository.Query; +import org.springframework.data.querydsl.QueryDslPredicateExecutor; + +import java.util.List; + +public interface UserRepository extends MongoRepository, QueryDslPredicateExecutor { + @Query("{ 'name' : ?0 }") + List findUsersByName(String name); + + @Query("{ 'age' : { $gt: ?0, $lt: ?1 } }") + List findUsersByAgeBetween(int ageGT, int ageLT); + + @Query("{ 'name' : { $regex: ?0 } }") + List findUsersByRegexpName(String regexp); + + List findByName(String name); + + List findByNameLikeOrderByAgeAsc(String name); + + List findByAgeBetween(int ageGT, int ageLT); + + List findByNameStartingWith(String regexp); + + List findByNameEndingWith(String regexp); + + @Query(value = "{}", fields = "{name : 1}") + List findNameAndId(); + + @Query(value = "{}", fields = "{_id : 0}") + List findNameAndAgeExcludeId(); +} diff --git a/spring-data-mongodb/src/main/java/org/baeldung/model/User.java b/spring-data-mongodb/src/main/java/org/baeldung/model/User.java deleted file mode 100644 index 9b8c47a58f..0000000000 --- a/spring-data-mongodb/src/main/java/org/baeldung/model/User.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.baeldung.model; - -import org.baeldung.annotation.CascadeSave; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.data.annotation.Id; -import org.springframework.data.annotation.PersistenceConstructor; -import org.springframework.data.annotation.Transient; -import org.springframework.data.mongodb.core.index.CompoundIndex; -import org.springframework.data.mongodb.core.index.CompoundIndexes; -import org.springframework.data.mongodb.core.index.IndexDirection; -import org.springframework.data.mongodb.core.index.Indexed; -import org.springframework.data.mongodb.core.mapping.DBRef; -import org.springframework.data.mongodb.core.mapping.Document; -import org.springframework.data.mongodb.core.mapping.Field; - -import com.querydsl.core.annotations.QueryEntity; - -@QueryEntity -@Document -@CompoundIndexes({ @CompoundIndex(name = "email_age", def = "{'email.id' : 1, 'age': 1}") }) -public class User { - - @Id - private String id; - @Indexed(direction = IndexDirection.ASCENDING) - private String name; - @Indexed(direction = IndexDirection.ASCENDING) - private Integer age; - - @DBRef - @Field("email") - @CascadeSave - private EmailAddress emailAddress; - - @Transient - private Integer yearOfBirth; - - public User() { - } - - public User(String name, Integer age) { - this.name = name; - this.age = age; - } - - @PersistenceConstructor - public User(final String name, @Value("#root.age ?: 0") final Integer age, final EmailAddress emailAddress) { - this.name = name; - this.age = age; - this.emailAddress = emailAddress; - } - - public String getId() { - return id; - } - - public void setId(final String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public Integer getAge() { - return age; - } - - public void setAge(final Integer age) { - this.age = age; - } - - public EmailAddress getEmailAddress() { - return emailAddress; - } - - public void setEmailAddress(final EmailAddress emailAddress) { - this.emailAddress = emailAddress; - } - - public Integer getYearOfBirth() { - return yearOfBirth; - } - - public void setYearOfBirth(final Integer yearOfBirth) { - this.yearOfBirth = yearOfBirth; - } - -} diff --git a/spring-data-mongodb/src/main/java/org/baeldung/repository/UserRepository.java b/spring-data-mongodb/src/main/java/org/baeldung/repository/UserRepository.java deleted file mode 100644 index 8e442e8b7f..0000000000 --- a/spring-data-mongodb/src/main/java/org/baeldung/repository/UserRepository.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.repository; - -import org.baeldung.model.User; -import org.springframework.data.mongodb.repository.MongoRepository; -import org.springframework.data.mongodb.repository.Query; -import org.springframework.data.querydsl.QueryDslPredicateExecutor; - -import java.util.List; - -public interface UserRepository extends MongoRepository, QueryDslPredicateExecutor { - @Query("{ 'name' : ?0 }") - List findUsersByName(String name); - - @Query("{ 'age' : { $gt: ?0, $lt: ?1 } }") - List findUsersByAgeBetween(int ageGT, int ageLT); - - @Query("{ 'name' : { $regex: ?0 } }") - List findUsersByRegexpName(String regexp); - - List findByName(String name); - - List findByNameLikeOrderByAgeAsc(String name); - - List findByAgeBetween(int ageGT, int ageLT); - - List findByNameStartingWith(String regexp); - - List findByNameEndingWith(String regexp); - - @Query(value = "{}", fields = "{name : 1}") - List findNameAndId(); - - @Query(value = "{}", fields = "{_id : 0}") - List findNameAndAgeExcludeId(); -} diff --git a/spring-data-mongodb/src/main/resources/logback.xml b/spring-data-mongodb/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-data-mongodb/src/main/resources/logback.xml +++ b/spring-data-mongodb/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-data-mongodb/src/test/java/org/baeldung/aggregation/ZipsAggregationLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java similarity index 97% rename from spring-data-mongodb/src/test/java/org/baeldung/aggregation/ZipsAggregationLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java index 5686465c19..a4bea45fcf 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/aggregation/ZipsAggregationLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java @@ -1,12 +1,12 @@ -package org.baeldung.aggregation; +package com.baeldung.aggregation; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.util.JSON; -import org.baeldung.aggregation.model.StatePopulation; -import org.baeldung.config.MongoConfig; +import com.baeldung.aggregation.model.StatePopulation; +import com.baeldung.config.MongoConfig; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/aggregation/model/StatePopulation.java b/spring-data-mongodb/src/test/java/com/baeldung/aggregation/model/StatePopulation.java similarity index 95% rename from spring-data-mongodb/src/test/java/org/baeldung/aggregation/model/StatePopulation.java rename to spring-data-mongodb/src/test/java/com/baeldung/aggregation/model/StatePopulation.java index 6a3cd0d426..be77783439 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/aggregation/model/StatePopulation.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/aggregation/model/StatePopulation.java @@ -1,4 +1,4 @@ -package org.baeldung.aggregation.model; +package com.baeldung.aggregation.model; import org.springframework.data.annotation.Id; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java similarity index 99% rename from spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java index 88205ba7fd..02485e8517 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.gridfs; +package com.baeldung.gridfs; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java similarity index 97% rename from spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java index 729b0f6dfa..7a61f9f98a 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java @@ -1,8 +1,8 @@ -package org.baeldung.mongotemplate; +package com.baeldung.mongotemplate; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.EmailAddress; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.EmailAddress; +import com.baeldung.model.User; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java similarity index 94% rename from spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java index 2d2117afbb..309f14e995 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java @@ -1,7 +1,7 @@ -package org.baeldung.mongotemplate; +package com.baeldung.mongotemplate; -import org.baeldung.config.SimpleMongoConfig; -import org.baeldung.model.User; +import com.baeldung.config.SimpleMongoConfig; +import com.baeldung.model.User; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java similarity index 97% rename from spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java index b7ce0cafae..ee1d4f4760 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java @@ -1,8 +1,8 @@ -package org.baeldung.mongotemplate; +package com.baeldung.mongotemplate; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.EmailAddress; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.EmailAddress; +import com.baeldung.model.User; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/BaseQueryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/repository/BaseQueryLiveTest.java similarity index 83% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/BaseQueryLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/repository/BaseQueryLiveTest.java index afd7259c6c..e4849181e5 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/BaseQueryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/repository/BaseQueryLiveTest.java @@ -1,7 +1,7 @@ -package org.baeldung.repository; +package com.baeldung.repository; -import org.baeldung.model.User; -import org.baeldung.repository.UserRepository; +import com.baeldung.model.User; +import com.baeldung.repository.UserRepository; import org.junit.After; import org.junit.Before; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/DSLQueryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/repository/DSLQueryLiveTest.java similarity index 95% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/DSLQueryLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/repository/DSLQueryLiveTest.java index 5924dea9fe..f87ca5cbb5 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/DSLQueryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/repository/DSLQueryLiveTest.java @@ -1,13 +1,13 @@ -package org.baeldung.repository; +package com.baeldung.repository; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.List; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.QUser; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.QUser; +import com.baeldung.model.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/JSONQueryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/repository/JSONQueryLiveTest.java similarity index 96% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/JSONQueryLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/repository/JSONQueryLiveTest.java index 9464a4eb52..4e99c0b140 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/JSONQueryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/repository/JSONQueryLiveTest.java @@ -1,12 +1,12 @@ -package org.baeldung.repository; +package com.baeldung.repository; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.List; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/QueryMethodsLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/repository/QueryMethodsLiveTest.java similarity index 96% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/QueryMethodsLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/repository/QueryMethodsLiveTest.java index 5705c119b8..47e67a6b4c 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/QueryMethodsLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/repository/QueryMethodsLiveTest.java @@ -1,12 +1,12 @@ -package org.baeldung.repository; +package com.baeldung.repository; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.List; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java similarity index 97% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java index 1543b847ba..da4e91baec 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java @@ -1,12 +1,12 @@ -package org.baeldung.repository; +package com.baeldung.repository; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.List; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.User; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryProjectionLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryProjectionLiveTest.java similarity index 93% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryProjectionLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryProjectionLiveTest.java index 5436896f08..80f4275794 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryProjectionLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryProjectionLiveTest.java @@ -1,9 +1,9 @@ -package org.baeldung.repository; +package com.baeldung.repository; import static org.junit.Assert.*; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.User; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/spring-data-rest-querydsl/README.md b/spring-data-rest-querydsl/README.md new file mode 100644 index 0000000000..03b5fee06a --- /dev/null +++ b/spring-data-rest-querydsl/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [REST Query Language Over Multiple Tables with Querydsl Web Support](http://www.baeldung.com/rest-querydsl-multiple-tables) diff --git a/spring-data-rest-querydsl/pom.xml b/spring-data-rest-querydsl/pom.xml new file mode 100644 index 0000000000..55ff78f0cb --- /dev/null +++ b/spring-data-rest-querydsl/pom.xml @@ -0,0 +1,98 @@ + + + 4.0.0 + com.baeldung + spring-data-rest-querydsl + 1.0 + spring-data-rest-querydsl + + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-1 + + + + + org.springframework.boot + spring-boot-starter-data-rest + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + + + com.querydsl + querydsl-apt + + + com.querydsl + querydsl-jpa + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + ${start-class} + ZIP + + + + + repackage + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + -verbose + -parameters + + + + + com.mysema.maven + apt-maven-plugin + 1.1.3 + + + generate-sources + + process + + + ${project.build.directory}/generated-sources + com.querydsl.apt.jpa.JPAAnnotationProcessor + + + + + + + + diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/Application.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..28d084a4dc --- /dev/null +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/Application.java @@ -0,0 +1,44 @@ +package com.baeldung; + +import com.baeldung.controller.repository.AddressRepository; +import com.baeldung.controller.repository.UserRepository; +import com.baeldung.entity.Address; +import com.baeldung.entity.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +import javax.annotation.PostConstruct; + +@SpringBootApplication +@EntityScan("com.baeldung.entity") +@EnableJpaRepositories("com.baeldung.controller.repository") +@EnableAutoConfiguration +public class Application { + + @Autowired + private UserRepository personRepository; + @Autowired + private AddressRepository addressRepository; + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @PostConstruct + private void initializeData() { + // Create John + final User john = new User("John"); + personRepository.save(john); + final Address addressOne = new Address("Fake Street 1", "Spain", john); + addressRepository.save(addressOne); + // Create Lisa + final User lisa = new User("Lisa"); + personRepository.save(lisa); + final Address addressTwo = new Address("Real Street 1", "Germany", lisa); + addressRepository.save(addressTwo); + } +} diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/QueryController.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/QueryController.java new file mode 100644 index 0000000000..e29932657f --- /dev/null +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/QueryController.java @@ -0,0 +1,34 @@ +package com.baeldung.controller; + +import com.baeldung.controller.repository.AddressRepository; +import com.baeldung.controller.repository.UserRepository; +import com.baeldung.entity.Address; +import com.baeldung.entity.User; +import com.querydsl.core.BooleanBuilder; +import com.querydsl.core.types.Predicate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.querydsl.binding.QuerydslPredicate; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class QueryController { + + @Autowired + private UserRepository personRepository; + @Autowired + private AddressRepository addressRepository; + + @GetMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE) + public Iterable queryOverUser(@QuerydslPredicate(root = User.class) Predicate predicate) { + final BooleanBuilder builder = new BooleanBuilder(); + return personRepository.findAll(builder.and(predicate)); + } + + @GetMapping(value = "/addresses", produces = MediaType.APPLICATION_JSON_VALUE) + public Iterable
    queryOverAddress(@QuerydslPredicate(root = Address.class) Predicate predicate) { + final BooleanBuilder builder = new BooleanBuilder(); + return addressRepository.findAll(builder.and(predicate)); + } +} diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/AddressRepository.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/AddressRepository.java new file mode 100644 index 0000000000..2e88820c98 --- /dev/null +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/AddressRepository.java @@ -0,0 +1,19 @@ +package com.baeldung.controller.repository; + +import com.baeldung.entity.Address; +import com.baeldung.entity.QAddress; +import com.querydsl.core.types.dsl.StringExpression; +import com.querydsl.core.types.dsl.StringPath; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer; +import org.springframework.data.querydsl.binding.QuerydslBindings; +import org.springframework.data.querydsl.binding.SingleValueBinding; + +public interface AddressRepository + extends JpaRepository, QueryDslPredicateExecutor
    , QuerydslBinderCustomizer { + @Override + default void customize(final QuerydslBindings bindings, final QAddress root) { + bindings.bind(String.class).first((SingleValueBinding) StringExpression::eq); + } +} diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/UserRepository.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/UserRepository.java new file mode 100644 index 0000000000..98ff2ac5e3 --- /dev/null +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/UserRepository.java @@ -0,0 +1,19 @@ +package com.baeldung.controller.repository; + +import com.baeldung.entity.QUser; +import com.baeldung.entity.User; +import com.querydsl.core.types.dsl.StringExpression; +import com.querydsl.core.types.dsl.StringPath; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer; +import org.springframework.data.querydsl.binding.QuerydslBindings; +import org.springframework.data.querydsl.binding.SingleValueBinding; + +public interface UserRepository + extends JpaRepository, QueryDslPredicateExecutor, QuerydslBinderCustomizer { + @Override + default void customize(final QuerydslBindings bindings, final QUser root) { + bindings.bind(String.class).first((SingleValueBinding) StringExpression::eq); + } +} diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/Address.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/Address.java new file mode 100644 index 0000000000..b01194adb7 --- /dev/null +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/Address.java @@ -0,0 +1,57 @@ +package com.baeldung.entity; + + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import javax.persistence.*; + +@Entity +@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) +public class Address { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", unique = true, nullable = false) + private Long id; + @Column + private String address; + @Column + private String country; + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User user; + + public Address() { + } + + public Address(String address, String country, User user) { + this.id = id; + this.address = address; + this.country = country; + this.user = user; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } +} diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/User.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/User.java new file mode 100644 index 0000000000..cfd484bb7a --- /dev/null +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/User.java @@ -0,0 +1,51 @@ +package com.baeldung.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import javax.persistence.*; + + +@Entity +@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", unique = true, nullable = false) + private Long id; + @Column + private String name; + @OneToOne(fetch = FetchType.LAZY, mappedBy = "user") + private Address address; + + public User() { + } + + public User(String name) { + 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 Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } +} diff --git a/spring-data-rest-querydsl/src/main/resources/application.yml b/spring-data-rest-querydsl/src/main/resources/application.yml new file mode 100644 index 0000000000..f25c6ea0e3 --- /dev/null +++ b/spring-data-rest-querydsl/src/main/resources/application.yml @@ -0,0 +1,11 @@ +spring: + datasource: + driver-class-name: com.mysql.jdbc.Driver + hikari: + pool-name: hikari-pool + url: jdbc:mysql://localhost:3306/baeldung?verifyServerCertificate=false&useSSL=false&requireSSL=false + username: root + + jpa: + hibernate: + ddl-auto: create diff --git a/spring-data-rest-querydsl/src/main/resources/logback.xml b/spring-data-rest-querydsl/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-data-rest-querydsl/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java new file mode 100644 index 0000000000..ef86c2f36d --- /dev/null +++ b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.springdatarestquerydsl; + +import com.baeldung.Application; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +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.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import java.nio.charset.Charset; + +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class) @WebAppConfiguration +public class IntegrationTest { + + final MediaType contentType = + new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); + + @Autowired private WebApplicationContext webApplicationContext; + + private MockMvc mockMvc; + + @Before public void setupMockMvc() { + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); + } + + @Test public void givenRequestHasBeenMade_whenQueryOverNameAttribute_thenGetJohn() throws Exception { + // Get John + mockMvc.perform(get("/personQuery?name=John")).andExpect(status().isOk()).andExpect(content().contentType(contentType)) + .andExpect(jsonPath("$", hasSize(1))).andExpect(jsonPath("$[0].name", is("John"))) + .andExpect(jsonPath("$[0].address.address", is("Fake Street 1"))) + .andExpect(jsonPath("$[0].address.country", is("Fake Country"))); + } + + @Test public void givenRequestHasBeenMade_whenQueryOverNameAttribute_thenGetLisa() throws Exception { + // Get Lisa + mockMvc.perform(get("/personQuery?name=Lisa")).andExpect(status().isOk()).andExpect(content().contentType(contentType)) + .andExpect(jsonPath("$", hasSize(1))).andExpect(jsonPath("$[0].name", is("Lisa"))) + .andExpect(jsonPath("$[0].address.address", is("Real Street 1"))) + .andExpect(jsonPath("$[0].address.country", is("Real Country"))); + } +} diff --git a/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/QuerydslIntegrationTest.java b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/QuerydslIntegrationTest.java new file mode 100644 index 0000000000..11e5ffca05 --- /dev/null +++ b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/QuerydslIntegrationTest.java @@ -0,0 +1,65 @@ +package com.baeldung.springdatarestquerydsl; + +import com.baeldung.Application; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +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.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import java.nio.charset.Charset; + +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = Application.class) +@WebAppConfiguration +public class QuerydslIntegrationTest { + + final MediaType contentType = + new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); + + @Autowired + private WebApplicationContext webApplicationContext; + + private MockMvc mockMvc; + + @Before + public void setupMockMvc() { + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); + } + + @Test + public void givenRequest_whenQueryUserFilteringByCountrySpain_thenGetJohn() throws Exception { + mockMvc.perform(get("/users?address.country=Spain")).andExpect(status().isOk()).andExpect(content() + .contentType + (contentType)) + .andExpect(jsonPath("$", hasSize(1))) + .andExpect(jsonPath("$[0].name", is("John"))) + .andExpect(jsonPath("$[0].address.address", is("Fake Street 1"))) + .andExpect(jsonPath("$[0].address.country", is("Spain"))); + } + + @Test + public void givenRequest_whenQueryUserWithoutFilter_thenGetJohnAndLisa() throws Exception { + mockMvc.perform(get("/users")).andExpect(status().isOk()).andExpect(content() + .contentType + (contentType)) + .andExpect(jsonPath("$", hasSize(2))) + .andExpect(jsonPath("$[0].name", is("John"))) + .andExpect(jsonPath("$[0].address.address", is("Fake Street 1"))) + .andExpect(jsonPath("$[0].address.country", is("Spain"))) + .andExpect(jsonPath("$[1].name", is("Lisa"))) + .andExpect(jsonPath("$[1].address.address", is("Real Street 1"))) + .andExpect(jsonPath("$[1].address.country", is("Germany"))); + } +} diff --git a/spring-data-rest/README.md b/spring-data-rest/README.md index fa4a264abb..09f8391406 100644 --- a/spring-data-rest/README.md +++ b/spring-data-rest/README.md @@ -1,4 +1,4 @@ -###The Course +### The Course The "REST With Spring" Classes: http://bit.ly/restwithspring # About this project @@ -13,8 +13,10 @@ The application uses [Spring Boot](http://projects.spring.io/spring-boot/), so i # Viewing the running application To view the running application, visit [http://localhost:8080](http://localhost:8080) in your browser -###Relevant Articles: +### Relevant Articles: - [Guide to Spring Data REST Validators](http://www.baeldung.com/spring-data-rest-validators) - [Working with Relationships in Spring Data REST](http://www.baeldung.com/spring-data-rest-relationships) - [AngularJS CRUD Application with Spring Data REST](http://www.baeldung.com/angularjs-crud-with-spring-data-rest) - [List of In-Memory Databases](http://www.baeldung.com/java-in-memory-databases) +- [Projections and Excerpts in Spring Data REST](http://www.baeldung.com/spring-data-rest-projections-excerpts) +- [Spring Data REST Events with @RepositoryEventHandler](http://www.baeldung.com/spring-data-rest-events) diff --git a/spring-data-rest/pom.xml b/spring-data-rest/pom.xml index bad7a38281..a756ef0497 100644 --- a/spring-data-rest/pom.xml +++ b/spring-data-rest/pom.xml @@ -1,19 +1,19 @@ + 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-data-rest 1.0 jar - intro-spring-data-rest + spring-data-rest Intro to Spring Data REST - parent-boot-5 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-2 @@ -33,11 +33,9 @@ com.h2database h2 - + diff --git a/spring-data-rest/src/main/java/com/baeldung/config/MvcConfig.java b/spring-data-rest/src/main/java/com/baeldung/config/MvcConfig.java index bed1a6f846..e5748f2f55 100644 --- a/spring-data-rest/src/main/java/com/baeldung/config/MvcConfig.java +++ b/spring-data-rest/src/main/java/com/baeldung/config/MvcConfig.java @@ -1,17 +1,16 @@ package com.baeldung.config; +import com.baeldung.events.AuthorEventHandler; +import com.baeldung.events.BookEventHandler; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc -public class MvcConfig extends WebMvcConfigurerAdapter{ +public class MvcConfig implements WebMvcConfigurer { public MvcConfig(){ super(); @@ -22,4 +21,14 @@ public class MvcConfig extends WebMvcConfigurerAdapter{ configurer.enable(); } + @Bean + AuthorEventHandler authorEventHandler() { + return new AuthorEventHandler(); + } + + @Bean + BookEventHandler bookEventHandler(){ + return new BookEventHandler(); + } + } diff --git a/spring-data-rest/src/main/java/com/baeldung/events/AuthorEventHandler.java b/spring-data-rest/src/main/java/com/baeldung/events/AuthorEventHandler.java new file mode 100644 index 0000000000..5a8ae05c08 --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/events/AuthorEventHandler.java @@ -0,0 +1,40 @@ +package com.baeldung.events; + +import com.baeldung.models.Author; +import com.baeldung.models.Book; +import org.springframework.data.rest.core.annotation.*; + +import java.util.logging.Logger; + +@RepositoryEventHandler +public class AuthorEventHandler { + Logger logger = Logger.getLogger("Class AuthorEventHandler"); + public AuthorEventHandler(){ + super(); + } + + @HandleBeforeCreate + public void handleAuthorBeforeCreate(Author author){ + logger.info("Inside Author Before Create...."); + String name = author.getName(); + } + + @HandleAfterCreate + public void handleAuthorAfterCreate(Author author){ + logger.info("Inside Author After Create ...."); + String name = author.getName(); + } + + @HandleBeforeDelete + public void handleAuthorBeforeDelete(Author author){ + logger.info("Inside Author Before Delete ...."); + String name = author.getName(); + } + + @HandleAfterDelete + public void handleAuthorAfterDelete(Author author){ + logger.info("Inside Author After Delete ...."); + String name = author.getName(); + } + +} diff --git a/spring-data-rest/src/main/java/com/baeldung/events/BookEventHandler.java b/spring-data-rest/src/main/java/com/baeldung/events/BookEventHandler.java new file mode 100644 index 0000000000..3953e6ce0d --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/events/BookEventHandler.java @@ -0,0 +1,26 @@ +package com.baeldung.events; + +import java.util.logging.Logger; +import com.baeldung.models.Author; +import com.baeldung.models.Book; +import org.apache.commons.logging.Log; +import org.springframework.data.rest.core.annotation.HandleAfterDelete; +import org.springframework.data.rest.core.annotation.HandleBeforeCreate; +import org.springframework.data.rest.core.annotation.RepositoryEventHandler; + +@RepositoryEventHandler +public class BookEventHandler { + Logger logger = Logger.getLogger("Class BookEventHandler"); + @HandleBeforeCreate + public void handleBookBeforeCreate(Book book){ + + logger.info("Inside Book Before Create ...."); + book.getAuthors(); + } + + @HandleBeforeCreate + public void handleAuthorBeforeCreate(Author author){ + logger.info("Inside Author Before Create ...."); + author.getBooks(); + } +} diff --git a/spring-data-rest/src/main/resources/logback.xml b/spring-data-rest/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-data-rest/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerUnitTest.java b/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerUnitTest.java new file mode 100644 index 0000000000..6db536c40c --- /dev/null +++ b/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.events; + +import com.baeldung.models.Author; +import org.junit.Test; +import org.mockito.Mockito; +import org.springframework.data.rest.core.annotation.RepositoryEventHandler; + +import static org.mockito.Mockito.mock; + +public class AuthorEventHandlerUnitTest { + + @Test + public void whenCreateAuthorThenSuccess() { + Author author = mock(Author.class); + AuthorEventHandler authorEventHandler = new AuthorEventHandler(); + authorEventHandler.handleAuthorBeforeCreate(author); + Mockito.verify(author,Mockito.times(1)).getName(); + + } + + @Test + public void whenDeleteAuthorThenSuccess() { + Author author = mock(Author.class); + AuthorEventHandler authorEventHandler = new AuthorEventHandler(); + authorEventHandler.handleAuthorAfterDelete(author); + Mockito.verify(author,Mockito.times(1)).getName(); + + } +} diff --git a/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerUnitTest.java b/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerUnitTest.java new file mode 100644 index 0000000000..28f0b91e1c --- /dev/null +++ b/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.events; + +import com.baeldung.models.Author; +import com.baeldung.models.Book; +import org.junit.Test; +import org.mockito.Mockito; + +import static org.mockito.Mockito.mock; + +public class BookEventHandlerUnitTest { + @Test + public void whenCreateBookThenSuccess() { + Book book = mock(Book.class); + BookEventHandler bookEventHandler = new BookEventHandler(); + bookEventHandler.handleBookBeforeCreate(book); + Mockito.verify(book,Mockito.times(1)).getAuthors(); + + } + + @Test + public void whenCreateAuthorThenSuccess() { + Author author = mock(Author.class); + BookEventHandler bookEventHandler = new BookEventHandler(); + bookEventHandler.handleAuthorBeforeCreate(author); + Mockito.verify(author,Mockito.times(1)).getBooks(); + + } +} diff --git a/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionIntegrationTest.java b/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionIntegrationTest.java deleted file mode 100644 index 4091fdf154..0000000000 --- a/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionIntegrationTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.baeldung.projection; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import io.restassured.RestAssured; -import io.restassured.response.Response; - -import java.util.Arrays; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.SpringDataRestApplication; -import com.baeldung.models.Author; -import com.baeldung.models.Book; -import com.baeldung.repositories.AuthorRepository; -import com.baeldung.repositories.BookRepository; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringDataRestApplication.class, webEnvironment = WebEnvironment.DEFINED_PORT) - -public class SpringDataProjectionIntegrationTest { - private static final String BOOK_ENDPOINT = "http://localhost:8080/books"; - private static final String AUTHOR_ENDPOINT = "http://localhost:8080/authors"; - - - @Autowired - private BookRepository bookRepo; - - @Autowired - private AuthorRepository authorRepo; - - @Before - public void setup(){ - if(bookRepo.findOne(1L) == null){ - Book book = new Book("Animal Farm"); - book.setIsbn("978-1943138425"); - book = bookRepo.save(book); - Author author = new Author("George Orwell"); - author = authorRepo.save(author); - author.setBooks(Arrays.asList(book)); - author = authorRepo.save(author); - } - } - - @Test - public void whenGetBook_thenOK(){ - final Response response = RestAssured.get(BOOK_ENDPOINT+"/1"); - - assertEquals(200, response.getStatusCode()); - assertTrue(response.asString().contains("isbn")); - assertFalse(response.asString().contains("authorCount")); -// System.out.println(response.asString()); - } - - - @Test - public void whenGetBookProjection_thenOK(){ - final Response response = RestAssured.get(BOOK_ENDPOINT+"/1?projection=customBook"); - - assertEquals(200, response.getStatusCode()); - assertFalse(response.asString().contains("isbn")); - assertTrue(response.asString().contains("authorCount")); -// System.out.println(response.asString()); - } - - @Test - public void whenGetAllBooks_thenOK(){ - final Response response = RestAssured.get(BOOK_ENDPOINT); - - assertEquals(200, response.getStatusCode()); - assertFalse(response.asString().contains("isbn")); - assertTrue(response.asString().contains("authorCount")); - // System.out.println(response.asString()); - } - - @Test - public void whenGetAuthorBooks_thenOK(){ - final Response response = RestAssured.get(AUTHOR_ENDPOINT+"/1/books"); - - assertEquals(200, response.getStatusCode()); - assertFalse(response.asString().contains("isbn")); - assertTrue(response.asString().contains("authorCount")); - System.out.println(response.asString()); - } -} diff --git a/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java b/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java new file mode 100644 index 0000000000..702c1521da --- /dev/null +++ b/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java @@ -0,0 +1,92 @@ +package com.baeldung.projection; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import io.restassured.RestAssured; +import io.restassured.response.Response; + +import java.util.Arrays; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.SpringDataRestApplication; +import com.baeldung.models.Author; +import com.baeldung.models.Book; +import com.baeldung.repositories.AuthorRepository; +import com.baeldung.repositories.BookRepository; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataRestApplication.class, webEnvironment = WebEnvironment.DEFINED_PORT) + +public class SpringDataProjectionLiveTest { + private static final String BOOK_ENDPOINT = "http://localhost:8080/books"; + private static final String AUTHOR_ENDPOINT = "http://localhost:8080/authors"; + + + @Autowired + private BookRepository bookRepo; + + @Autowired + private AuthorRepository authorRepo; + + @Before + public void setup(){ + if(bookRepo.findById(1L) == null){ + Book book = new Book("Animal Farm"); + book.setIsbn("978-1943138425"); + book = bookRepo.save(book); + Author author = new Author("George Orwell"); + author = authorRepo.save(author); + author.setBooks(Arrays.asList(book)); + author = authorRepo.save(author); + } + } + + @Test + public void whenGetBook_thenOK(){ + final Response response = RestAssured.get(BOOK_ENDPOINT+"/1"); + + assertEquals(200, response.getStatusCode()); + assertTrue(response.asString().contains("isbn")); + assertFalse(response.asString().contains("authorCount")); +// System.out.println(response.asString()); + } + + + @Test + public void whenGetBookProjection_thenOK(){ + final Response response = RestAssured.get(BOOK_ENDPOINT+"/1?projection=customBook"); + + assertEquals(200, response.getStatusCode()); + assertFalse(response.asString().contains("isbn")); + assertTrue(response.asString().contains("authorCount")); +// System.out.println(response.asString()); + } + + @Test + public void whenGetAllBooks_thenOK(){ + final Response response = RestAssured.get(BOOK_ENDPOINT); + + assertEquals(200, response.getStatusCode()); + assertFalse(response.asString().contains("isbn")); + assertTrue(response.asString().contains("authorCount")); + // System.out.println(response.asString()); + } + + @Test + public void whenGetAuthorBooks_thenOK(){ + final Response response = RestAssured.get(AUTHOR_ENDPOINT+"/1/books"); + + assertEquals(200, response.getStatusCode()); + assertFalse(response.asString().contains("isbn")); + assertTrue(response.asString().contains("authorCount")); + System.out.println(response.asString()); + } +} diff --git a/spring-data-rest/src/test/java/com/baeldung/relationships/SpringDataRelationshipsIntegrationTest.java b/spring-data-rest/src/test/java/com/baeldung/relationships/SpringDataRelationshipsIntegrationTest.java deleted file mode 100644 index e3fe60d487..0000000000 --- a/spring-data-rest/src/test/java/com/baeldung/relationships/SpringDataRelationshipsIntegrationTest.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.baeldung.relationships; - -import com.baeldung.SpringDataRestApplication; -import com.baeldung.models.Address; -import com.baeldung.models.Author; -import com.baeldung.models.Book; -import com.baeldung.models.Library; -import org.json.JSONArray; -import org.json.JSONObject; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; -import org.json.JSONException; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringDataRestApplication.class, webEnvironment = WebEnvironment.DEFINED_PORT) -public class SpringDataRelationshipsIntegrationTest { - - @Autowired - private TestRestTemplate template; - - private static final String BOOK_ENDPOINT = "http://localhost:8080/books/"; - private static final String AUTHOR_ENDPOINT = "http://localhost:8080/authors/"; - private static final String ADDRESS_ENDPOINT = "http://localhost:8080/addresses/"; - private static final String LIBRARY_ENDPOINT = "http://localhost:8080/libraries/"; - - private static final String LIBRARY_NAME = "My Library"; - private static final String AUTHOR_NAME = "George Orwell"; - - @Test - public void whenSaveOneToOneRelationship_thenCorrect() throws JSONException { - Library library = new Library(LIBRARY_NAME); - template.postForEntity(LIBRARY_ENDPOINT, library, Library.class); - - Address address = new Address("Main street, nr 1"); - template.postForEntity(ADDRESS_ENDPOINT, address, Address.class); - - HttpHeaders requestHeaders = new HttpHeaders(); - requestHeaders.add("Content-type", "text/uri-list"); - HttpEntity httpEntity = new HttpEntity<>(ADDRESS_ENDPOINT + "/1", requestHeaders); - template.exchange(LIBRARY_ENDPOINT + "/1/libraryAddress", HttpMethod.PUT, httpEntity, String.class); - - ResponseEntity libraryGetResponse = template.getForEntity(ADDRESS_ENDPOINT + "/1/library", Library.class); - assertEquals("library is incorrect", libraryGetResponse.getBody() - .getName(), LIBRARY_NAME); - } - - @Test - public void whenSaveOneToManyRelationship_thenCorrect() throws JSONException{ - Library library = new Library(LIBRARY_NAME); - template.postForEntity(LIBRARY_ENDPOINT, library, Library.class); - - Book book1 = new Book("Dune"); - template.postForEntity(BOOK_ENDPOINT, book1, Book.class); - - Book book2 = new Book("1984"); - template.postForEntity(BOOK_ENDPOINT, book2, Book.class); - - HttpHeaders requestHeaders = new HttpHeaders(); - requestHeaders.add("Content-type", "text/uri-list"); - HttpEntity bookHttpEntity = new HttpEntity<>(LIBRARY_ENDPOINT + "/1", requestHeaders); - template.exchange(BOOK_ENDPOINT + "/1/library", HttpMethod.PUT, bookHttpEntity, String.class); - template.exchange(BOOK_ENDPOINT + "/2/library", HttpMethod.PUT, bookHttpEntity, String.class); - - ResponseEntity libraryGetResponse = template.getForEntity(BOOK_ENDPOINT + "/1/library", Library.class); - assertEquals("library is incorrect", libraryGetResponse.getBody() - .getName(), LIBRARY_NAME); - } - - @Test - public void whenSaveManyToManyRelationship_thenCorrect() throws JSONException{ - Author author1 = new Author(AUTHOR_NAME); - template.postForEntity(AUTHOR_ENDPOINT, author1, Author.class); - - Book book1 = new Book("Animal Farm"); - template.postForEntity(BOOK_ENDPOINT, book1, Book.class); - - Book book2 = new Book("1984"); - template.postForEntity(BOOK_ENDPOINT, book2, Book.class); - - HttpHeaders requestHeaders = new HttpHeaders(); - requestHeaders.add("Content-type", "text/uri-list"); - HttpEntity httpEntity = new HttpEntity<>(BOOK_ENDPOINT + "/1\n" + BOOK_ENDPOINT + "/2", requestHeaders); - template.exchange(AUTHOR_ENDPOINT + "/1/books", HttpMethod.PUT, httpEntity, String.class); - - String jsonResponse = template.getForObject(BOOK_ENDPOINT + "/1/authors", String.class); - JSONObject jsonObj = new JSONObject(jsonResponse).getJSONObject("_embedded"); - JSONArray jsonArray = jsonObj.getJSONArray("authors"); - assertEquals("author is incorrect", jsonArray.getJSONObject(0) - .getString("name"), AUTHOR_NAME); - } -} diff --git a/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorIntegrationTest.java b/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorIntegrationTest.java index bc321bc686..4c936ffc1c 100644 --- a/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorIntegrationTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorIntegrationTest.java @@ -1,31 +1,33 @@ package com.baeldung.validator; -import com.baeldung.SpringDataRestApplication; -import com.baeldung.models.WebsiteUser; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.web.context.WebApplicationContext; - import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.SpringDataRestApplication; +import com.baeldung.models.WebsiteUser; +import com.fasterxml.jackson.databind.ObjectMapper; + @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = SpringDataRestApplication.class) -@WebAppConfiguration +@SpringBootTest(classes = SpringDataRestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK) +@AutoConfigureMockMvc public class SpringDataRestValidatorIntegrationTest { public static final String URL = "http://localhost"; + @Autowired private MockMvc mockMvc; @Autowired diff --git a/spring-data-spring-security/README.md b/spring-data-spring-security/README.md deleted file mode 100644 index da65527a8a..0000000000 --- a/spring-data-spring-security/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# About this project -This project contains examples from the [Spring Data with Spring Security](http://www.baeldung.com/spring-data-with-spring-security) article from Baeldung. - -# Running the project -The application uses [Spring Boot](http://projects.spring.io/spring-boot/), so it is easy to run. You can start it any of a few ways: -* Run the `main` method from `SpringDataRestApplication` -* Use the Maven Spring Boot plugin: `mvn spring-boot:run` -* Package the application as a JAR and run it using `java -jar spring-data-spring-security.jar` - -# Viewing the running application -To view the running application, visit [http://localhost:8080](http://localhost:8080) in your browser - -###Relevant Articles: -- [Spring Data with Spring Security](http://www.baeldung.com/spring-data-security) diff --git a/spring-data-spring-security/pom.xml b/spring-data-spring-security/pom.xml deleted file mode 100644 index afdf3c332c..0000000000 --- a/spring-data-spring-security/pom.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - 4.0.0 - - com.baeldung - spring-data-spring-security - 1.0 - jar - intro-spring-data-spring-security - Spring Data with Spring Security - - - parent-boot-5 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-5 - - - - - org.springframework.boot - spring-boot-starter - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.security - spring-security-data - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.security - spring-security-test - test - - - org.apache.tomcat.embed - tomcat-embed-jasper - - - - com.h2database - h2 - - - javax.servlet - jstl - - - - - ${project.artifactId} - - - diff --git a/spring-data-spring-security/src/test/java/com/baeldung/relationships/SpringDataWithSecurityTest.java b/spring-data-spring-security/src/test/java/com/baeldung/relationships/SpringDataWithSecurityTest.java deleted file mode 100644 index dbbfe7e85e..0000000000 --- a/spring-data-spring-security/src/test/java/com/baeldung/relationships/SpringDataWithSecurityTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.baeldung.relationships; - -import static org.springframework.util.Assert.isTrue; - -import java.util.Date; -import java.util.List; - -import javax.servlet.ServletContext; - -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.InvalidDataAccessApiUsageException; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; - -import com.baeldung.AppConfig; -import com.baeldung.data.repositories.TweetRepository; -import com.baeldung.data.repositories.UserRepository; -import com.baeldung.models.AppUser; -import com.baeldung.models.Tweet; -import com.baeldung.security.AppUserPrincipal; -import com.baeldung.util.DummyContentUtil; - -@RunWith(SpringRunner.class) -@WebAppConfiguration -@ContextConfiguration -@DirtiesContext -public class SpringDataWithSecurityTest { - AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); - @Autowired - private ServletContext servletContext; - private static UserRepository userRepository; - private static TweetRepository tweetRepository; - - @Before - public void testInit() { - ctx.register(AppConfig.class); - ctx.setServletContext(servletContext); - ctx.refresh(); - userRepository = ctx.getBean(UserRepository.class); - tweetRepository = ctx.getBean(TweetRepository.class); - List appUsers = (List) userRepository.save(DummyContentUtil.generateDummyUsers()); - tweetRepository.save(DummyContentUtil.generateDummyTweets(appUsers)); - } - - @AfterClass - public static void tearDown() { - tweetRepository.deleteAll(); - userRepository.deleteAll(); - } - - @Test - public void givenAppUser_whenLoginSuccessful_shouldUpdateLastLogin() { - AppUser appUser = userRepository.findByUsername("lionel@messi.com"); - Authentication auth = new UsernamePasswordAuthenticationToken(new AppUserPrincipal(appUser), null, DummyContentUtil.getAuthorities()); - SecurityContextHolder.getContext() - .setAuthentication(auth); - userRepository.updateLastLogin(new Date()); - } - - @Test(expected = InvalidDataAccessApiUsageException.class) - public void givenNoAppUserInSecurityContext_whenUpdateLastLoginAttempted_shouldFail() { - userRepository.updateLastLogin(new Date()); - } - - @Test - public void givenAppUser_whenLoginSuccessful_shouldReadMyPagedTweets() { - AppUser appUser = userRepository.findByUsername("lionel@messi.com"); - Authentication auth = new UsernamePasswordAuthenticationToken(new AppUserPrincipal(appUser), null, DummyContentUtil.getAuthorities()); - SecurityContextHolder.getContext() - .setAuthentication(auth); - Page page = null; - do { - page = tweetRepository.getMyTweetsAndTheOnesILiked(new PageRequest(page != null ? page.getNumber() + 1 : 0, 5)); - for (Tweet twt : page.getContent()) { - isTrue((twt.getOwner() == appUser.getUsername()) || (twt.getLikes() - .contains(appUser.getUsername())), "I do not have any Tweets"); - } - } while (page.hasNext()); - } - - @Test(expected = InvalidDataAccessApiUsageException.class) - public void givenNoAppUser_whenPaginatedResultsRetrievalAttempted_shouldFail() { - Page page = null; - do { - page = tweetRepository.getMyTweetsAndTheOnesILiked(new PageRequest(page != null ? page.getNumber() + 1 : 0, 5)); - } while (page != null && page.hasNext()); - } -} diff --git a/spring-dispatcher-servlet/pom.xml b/spring-dispatcher-servlet/pom.xml index 9fa02f157d..4e4346e43b 100644 --- a/spring-dispatcher-servlet/pom.xml +++ b/spring-dispatcher-servlet/pom.xml @@ -1,98 +1,96 @@ - - 4.0.0 - com.baeldung - spring-dispatcher-servlet - war - 1.0.0 - spring-dispatcher-servlet + + 4.0.0 + com.baeldung + spring-dispatcher-servlet + war + 1.0.0 + spring-dispatcher-servlet - - com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring - + + com.baeldung + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 + - - - org.springframework - spring-web - ${spring.version} - - - org.springframework - spring-webmvc - ${spring.version} - - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - - - javax.servlet.jsp.jstl - jstl-api - ${jstl-api.version} - - - javax.servlet.jsp - javax.servlet.jsp-api - ${javax.servlet.jsp-api.version} - - - org.codehaus.jackson - jackson-mapper-asl - ${jackson-mapper-asl.version} - - - javax.servlet - jstl - ${jstl.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind.version} - - - commons-fileupload - commons-fileupload - ${commons-fileupload.version} - - + + + org.springframework + spring-web + ${spring.version} + + + org.springframework + spring-webmvc + ${spring.version} + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + + + javax.servlet.jsp.jstl + jstl-api + ${jstl-api.version} + + + javax.servlet.jsp + javax.servlet.jsp-api + ${javax.servlet.jsp-api.version} + + + org.codehaus.jackson + jackson-mapper-asl + ${jackson-mapper-asl.version} + + + javax.servlet + jstl + ${jstl.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-databind.version} + + + commons-fileupload + commons-fileupload + ${commons-fileupload.version} + + - - spring-dispatcher-servlet - - - - org.apache.tomcat.maven - tomcat8-maven-plugin - ${tomcat8-maven-plugin.version} - - /springdispatcherservlet - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - src/main/webapp - false - - - - - + + spring-dispatcher-servlet + + + + org.apache.tomcat.maven + tomcat8-maven-plugin + ${tomcat8-maven-plugin.version} + + /springdispatcherservlet + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + src/main/webapp + false + + + + + - - 4.3.7.RELEASE - 3.0-r1655215 - 3.0.0 - + + 3.0-r1655215 + 3.0.0 + \ No newline at end of file diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/springdispatcherservlet/configuration/AppConfig.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/springdispatcherservlet/configuration/AppConfig.java index f5ad032e84..c8a6cf06a6 100644 --- a/spring-dispatcher-servlet/src/main/java/com/baeldung/springdispatcherservlet/configuration/AppConfig.java +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/springdispatcherservlet/configuration/AppConfig.java @@ -17,7 +17,7 @@ import java.io.IOException; @Configuration @EnableWebMvc @ComponentScan("com.baeldung.springdispatcherservlet") -public class AppConfig extends WebMvcConfigurerAdapter { +public class AppConfig implements WebMvcConfigurer { public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("index"); diff --git a/spring-dispatcher-servlet/src/main/resources/logback.xml b/spring-dispatcher-servlet/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-drools/pom.xml b/spring-drools/pom.xml index 9df43a89ad..8c65d5e34e 100644 --- a/spring-drools/pom.xml +++ b/spring-drools/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-drools @@ -34,7 +34,7 @@ drools-compiler ${drools-version} - + org.kie kie-spring diff --git a/spring-drools/src/main/resources/logback.xml b/spring-drools/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-drools/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-ejb/README.md b/spring-ejb/README.md index 8fa8833f3a..d09b27db27 100644 --- a/spring-ejb/README.md +++ b/spring-ejb/README.md @@ -1,3 +1,4 @@ ### Relevant Articles - [Integration Guide for Spring and EJB](http://www.baeldung.com/spring-ejb) +- [Singleton Session Bean in Java EE](http://www.baeldung.com/java-ee-singleton-session-bean) diff --git a/spring-ejb/ejb-beans/pom.xml b/spring-ejb/ejb-beans/pom.xml index 0ce390b6ac..76c0afadee 100644 --- a/spring-ejb/ejb-beans/pom.xml +++ b/spring-ejb/ejb-beans/pom.xml @@ -1,44 +1,35 @@ + 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.singletonsession - singleton-ejb-bean + ejb-beans 1.0.0-SNAPSHOT - EJB Singleton Session Bean + EJB Beans + com.baeldung.spring.ejb - ejb-for-spring + spring-ejb 1.0.1 - - UTF-8 - - javax javaee-api - 8.0 + ${javaee.version} provided - org.apache.openejb tomee-embedded - 1.7.5 + ${tomee-embedded.version} - - - - junit - junit - 4.12 - test - - + + 1.7.5 + + diff --git a/spring-ejb/ejb-beans/src/main/resources/logback.xml b/spring-ejb/ejb-beans/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-ejb/ejb-beans/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-ejb/ejb-beans/src/test/java/com/baeldung/singletonbean/CountryStateCacheBeanTest.java b/spring-ejb/ejb-beans/src/test/java/com/baeldung/singletonbean/CountryStateCacheBeanTest.java deleted file mode 100644 index 2207431702..0000000000 --- a/spring-ejb/ejb-beans/src/test/java/com/baeldung/singletonbean/CountryStateCacheBeanTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.baeldung.singletonbean; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertNotNull; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import javax.ejb.embeddable.EJBContainer; -import javax.naming.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class CountryStateCacheBeanTest { - - private EJBContainer ejbContainer = null; - - private Context context = null; - - @Before - public void init() { - - ejbContainer = EJBContainer.createEJBContainer(); - context = ejbContainer.getContext(); - } - - @Test - public void whenCallGetStatesFromContainerManagedBean_ReturnsStatesForCountry() throws Exception { - - String[] expectedStates = { "Texas", "Alabama", "Alaska", "Arizona", "Arkansas" }; - - CountryState countryStateBean = (CountryState) context.lookup("java:global/ejb-beans/CountryStateContainerManagedBean"); - List actualStates = countryStateBean.getStates("UnitedStates"); - assertNotNull(actualStates); - assertArrayEquals(expectedStates, actualStates.toArray()); - } - - @Test - public void whenCallGetStatesFromBeanManagedBean_ReturnsStatesForCountry() throws Exception { - - String[] expectedStates = { "Texas", "Alabama", "Alaska", "Arizona", "Arkansas" }; - - CountryState countryStateBean = (CountryState) context.lookup("java:global/ejb-beans/CountryStateBeanManagedBean"); - List actualStates = countryStateBean.getStates("UnitedStates"); - assertNotNull(actualStates); - assertArrayEquals(expectedStates, actualStates.toArray()); - } - - @Test - public void whenCallSetStatesFromContainerManagedBean_SetsStatesForCountry() throws Exception { - - String[] expectedStates = { "California", "Florida", "Hawaii", "Pennsylvania", "Michigan" }; - - CountryState countryStateBean = (CountryState) context.lookup("java:global/ejb-beans/CountryStateContainerManagedBean"); - countryStateBean.setStates("UnitedStates", Arrays.asList(expectedStates)); - - List actualStates = countryStateBean.getStates("UnitedStates"); - assertNotNull(actualStates); - assertArrayEquals(expectedStates, actualStates.toArray()); - } - - @Test - public void whenCallSetStatesFromBeanManagedBean_SetsStatesForCountry() throws Exception { - - String[] expectedStates = { "California", "Florida", "Hawaii", "Pennsylvania", "Michigan" }; - - CountryState countryStateBean = (CountryState) context.lookup("java:global/ejb-beans/CountryStateBeanManagedBean"); - countryStateBean.setStates("UnitedStates", Arrays.asList(expectedStates)); - - List actualStates = countryStateBean.getStates("UnitedStates"); - assertNotNull(actualStates); - assertArrayEquals(expectedStates, actualStates.toArray()); - } - - @After - public void close() { - if (ejbContainer != null) - ejbContainer.close(); - } -} diff --git a/spring-ejb/ejb-beans/src/test/java/com/baeldung/singletonbean/CountryStateCacheBeanUnitTest.java b/spring-ejb/ejb-beans/src/test/java/com/baeldung/singletonbean/CountryStateCacheBeanUnitTest.java new file mode 100644 index 0000000000..4cec01a4f7 --- /dev/null +++ b/spring-ejb/ejb-beans/src/test/java/com/baeldung/singletonbean/CountryStateCacheBeanUnitTest.java @@ -0,0 +1,83 @@ +package com.baeldung.singletonbean; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import javax.ejb.embeddable.EJBContainer; +import javax.naming.Context; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class CountryStateCacheBeanUnitTest { + + private EJBContainer ejbContainer = null; + + private Context context = null; + + @Before + public void init() { + + ejbContainer = EJBContainer.createEJBContainer(); + context = ejbContainer.getContext(); + } + + @Test + public void whenCallGetStatesFromContainerManagedBean_ReturnsStatesForCountry() throws Exception { + + String[] expectedStates = { "Texas", "Alabama", "Alaska", "Arizona", "Arkansas" }; + + CountryState countryStateBean = (CountryState) context.lookup("java:global/ejb-beans/CountryStateContainerManagedBean"); + List actualStates = countryStateBean.getStates("UnitedStates"); + assertNotNull(actualStates); + assertArrayEquals(expectedStates, actualStates.toArray()); + } + + @Test + public void whenCallGetStatesFromBeanManagedBean_ReturnsStatesForCountry() throws Exception { + + String[] expectedStates = { "Texas", "Alabama", "Alaska", "Arizona", "Arkansas" }; + + CountryState countryStateBean = (CountryState) context.lookup("java:global/ejb-beans/CountryStateBeanManagedBean"); + List actualStates = countryStateBean.getStates("UnitedStates"); + assertNotNull(actualStates); + assertArrayEquals(expectedStates, actualStates.toArray()); + } + + @Test + public void whenCallSetStatesFromContainerManagedBean_SetsStatesForCountry() throws Exception { + + String[] expectedStates = { "California", "Florida", "Hawaii", "Pennsylvania", "Michigan" }; + + CountryState countryStateBean = (CountryState) context.lookup("java:global/ejb-beans/CountryStateContainerManagedBean"); + countryStateBean.setStates("UnitedStates", Arrays.asList(expectedStates)); + + List actualStates = countryStateBean.getStates("UnitedStates"); + assertNotNull(actualStates); + assertArrayEquals(expectedStates, actualStates.toArray()); + } + + @Test + public void whenCallSetStatesFromBeanManagedBean_SetsStatesForCountry() throws Exception { + + String[] expectedStates = { "California", "Florida", "Hawaii", "Pennsylvania", "Michigan" }; + + CountryState countryStateBean = (CountryState) context.lookup("java:global/ejb-beans/CountryStateBeanManagedBean"); + countryStateBean.setStates("UnitedStates", Arrays.asList(expectedStates)); + + List actualStates = countryStateBean.getStates("UnitedStates"); + assertNotNull(actualStates); + assertArrayEquals(expectedStates, actualStates.toArray()); + } + + @After + public void close() { + if (ejbContainer != null) + ejbContainer.close(); + } +} diff --git a/spring-ejb/ejb-remote-for-spring/pom.xml b/spring-ejb/ejb-remote-for-spring/pom.xml index 9978196725..21256fa801 100755 --- a/spring-ejb/ejb-remote-for-spring/pom.xml +++ b/spring-ejb/ejb-remote-for-spring/pom.xml @@ -7,7 +7,7 @@ com.baeldung.spring.ejb - ejb-for-spring + spring-ejb 1.0.1 @@ -20,7 +20,7 @@ org.assertj assertj-core - 3.9.0 + ${assertj.version} test @@ -45,7 +45,7 @@ wildfly10x - http://download.jboss.org/wildfly/10.1.0.Final/wildfly-10.1.0.Final.zip + http://download.jboss.org/wildfly/12.0.0.Final/wildfly-12.0.0.Final.zip @@ -66,7 +66,7 @@ - 7.0 + 3.9.0 1.6.1 diff --git a/spring-ejb/ejb-remote-for-spring/src/main/resources/logback.xml b/spring-ejb/ejb-remote-for-spring/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-ejb/ejb-remote-for-spring/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-ejb/pom.xml b/spring-ejb/pom.xml index 188ba0b8fe..31cde720f9 100755 --- a/spring-ejb/pom.xml +++ b/spring-ejb/pom.xml @@ -1,12 +1,12 @@ + 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.ejb - ejb-for-spring + spring-ejb 1.0.1 pom - ejb + spring-ejb Spring EJB Tutorial @@ -37,19 +37,19 @@ com.baeldung.spring.ejb ejb-remote-for-spring - 1.0.1 + ${ejb-remote-for-spring.version} ejb javax javaee-api - 7.0 + ${javaee.version} provided org.wildfly wildfly-ejb-client-bom - 10.1.0.Final + ${wildfly-ejb.version} pom import @@ -61,9 +61,9 @@ maven-ejb-plugin - 2.4 + ${maven-ejb-plugin.version} - 3.2 + ${ejb.version} @@ -72,7 +72,15 @@ ejb-remote-for-spring - spring-ejb-client ejb-beans + + + 1.0.1 + 8.0 + 12.0.0.Final + 2.4 + 3.2 + + diff --git a/spring-ejb/spring-ejb-client/pom.xml b/spring-ejb/spring-ejb-client/pom.xml index f7b42212be..c935e1f14a 100644 --- a/spring-ejb/spring-ejb-client/pom.xml +++ b/spring-ejb/spring-ejb-client/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-ejb-client @@ -11,17 +11,11 @@ com.baeldung - parent-boot-5 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-2 - - UTF-8 - UTF-8 - 1.8 - - org.springframework.boot @@ -31,14 +25,14 @@ org.wildfly wildfly-ejb-client-bom - 10.1.0.Final + ${wildfly-ejb.version} pom com.baeldung.spring.ejb ejb-remote-for-spring - 1.0.1 + ${ejb-remote-for-spring.version} ejb @@ -47,6 +41,12 @@ spring-boot-starter-test test + + + io.undertow + undertow-servlet + + @@ -58,43 +58,9 @@ - - - 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 - - - - + + 1.0.1 + 12.0.0.Final + diff --git a/spring-ejb/spring-ejb-client/src/main/java/com/baeldung/springejbclient/SpringEjbClientApplication.java b/spring-ejb/spring-ejb-client/src/main/java/com/baeldung/springejbclient/SpringEjbClientApplication.java index d3542a2158..0a1e389113 100644 --- a/spring-ejb/spring-ejb-client/src/main/java/com/baeldung/springejbclient/SpringEjbClientApplication.java +++ b/spring-ejb/spring-ejb-client/src/main/java/com/baeldung/springejbclient/SpringEjbClientApplication.java @@ -47,4 +47,5 @@ public class SpringEjbClientApplication { public static void main(String[] args) { SpringApplication.run(SpringEjbClientApplication.class, args); } + } diff --git a/spring-ejb/spring-ejb-client/src/main/resources/logback.xml b/spring-ejb/spring-ejb-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-ejb/spring-ejb-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-exceptions/pom.xml b/spring-exceptions/pom.xml index a9ea8239f6..16f6286606 100644 --- a/spring-exceptions/pom.xml +++ b/spring-exceptions/pom.xml @@ -1,5 +1,5 @@ + 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-exceptions @@ -174,6 +174,7 @@ + 4.3.4.RELEASE 4.2.0.RELEASE diff --git a/spring-exceptions/src/main/resources/logback.xml b/spring-exceptions/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-exceptions/src/main/resources/logback.xml +++ b/spring-exceptions/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-freemarker/pom.xml b/spring-freemarker/pom.xml index f2771857c7..f0626195fd 100644 --- a/spring-freemarker/pom.xml +++ b/spring-freemarker/pom.xml @@ -1,8 +1,8 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 - com.freemarker.example - spring4-freemarker-example + com.baeldung.freemarker + spring-freemarker war 1.0-SNAPSHOT Spring Freemarker Example @@ -13,16 +13,7 @@ 1.0.0-SNAPSHOT - - 1.8 - 4.3.4.RELEASE - 2.3.23 - 3.1.0 - false - - - org.springframework spring-webmvc @@ -34,13 +25,11 @@ - org.springframework spring-context-support ${spring.version} - @@ -49,7 +38,6 @@ ${servletapi.version} provided - org.freemarker @@ -59,4 +47,11 @@ - \ No newline at end of file + + 5.0.8.RELEASE + 2.3.28 + 3.1.0 + false + + + diff --git a/spring-freemarker/src/main/resources/logback.xml b/spring-freemarker/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-freemarker/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-groovy/pom.xml b/spring-groovy/pom.xml index eec78d21a6..42cdb93fd2 100644 --- a/spring-groovy/pom.xml +++ b/spring-groovy/pom.xml @@ -1,65 +1,68 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldug spring-groovy 0.0.1-SNAPSHOT jar - spring-groovy http://maven.apache.org com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring + parent-spring-4 + 0.0.1-SNAPSHOT + ../parent-spring-4 - + org.springframework.integration spring-integration-groovy - 4.3.7.RELEASE + ${spring-integration-groovy.version} org.codehaus.groovy groovy-all - 2.4.12 + ${groovy-all.version} + maven-compiler-plugin - 3.7.0 + ${maven-compiler-plugin.version} groovy-eclipse-compiler true - 1.8 - 1.8 + ${java.version} + ${java.version} ${project.build.sourceEncoding} org.codehaus.groovy groovy-eclipse-compiler - 2.9.2-01 + ${groovy-eclipse-compiler.version} org.codehaus.groovy groovy-eclipse-batch - 2.4.3-01 + ${groovy-eclipse-batch.version} - + - UTF-8 + 2.9.2-01 + 2.4.3-01 + 4.3.7.RELEASE + 2.4.12 - + diff --git a/spring-groovy/src/main/resources/logback.xml b/spring-groovy/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-groovy/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-hibernate3/src/main/resources/logback.xml b/spring-hibernate3/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-hibernate3/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-hibernate4/README.md b/spring-hibernate4/README.md index 88ee7fadd3..b15b7278f4 100644 --- a/spring-hibernate4/README.md +++ b/spring-hibernate4/README.md @@ -11,7 +11,6 @@ - [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial) - [Hibernate: save, persist, update, merge, saveOrUpdate](http://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate) - [Eager/Lazy Loading In Hibernate](http://www.baeldung.com/hibernate-lazy-eager-loading) -- [Hibernate Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries) - [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) - [Guide to @Immutable Annotation in Hibernate](http://www.baeldung.com/hibernate-immutable) - [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) diff --git a/spring-hibernate4/pom.xml b/spring-hibernate4/pom.xml index be27ba6f6a..505a218a94 100644 --- a/spring-hibernate4/pom.xml +++ b/spring-hibernate4/pom.xml @@ -1,5 +1,5 @@ + 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-hibernate4 @@ -127,6 +127,12 @@ ${hsqldb.version} test + + com.h2database + h2 + ${h2.version} + test + @@ -138,12 +144,6 @@ true - - - - - - @@ -159,6 +159,7 @@ 8.5.8 1.1 2.3.4 + 1.4.193 5.3.3.Final @@ -177,7 +178,6 @@ 2.7 1.6.1 - diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java deleted file mode 100644 index 83e3c2f9a5..0000000000 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java +++ /dev/null @@ -1,251 +0,0 @@ -/** - * ApplicationViewer is the class that starts the application - * First it creates the session object and then creates the - * criteria query. - * - * @author Pritam Banerjee - * @version 1.0 - * @since 07/20/2016 - */ - -package com.baeldung.hibernate.criteria.view; - -import java.util.List; - -import org.hibernate.Criteria; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.LogicalExpression; -import org.hibernate.criterion.Order; -import org.hibernate.criterion.Projections; -import org.hibernate.criterion.Restrictions; - -import com.baeldung.hibernate.criteria.model.Item; -import com.baeldung.hibernate.criteria.util.HibernateUtil; - -public class ApplicationView { - - // default Constructor - public ApplicationView() { - - } - - public boolean checkIfCriteriaTimeLower() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - Transaction tx = null; - - // calculate the time taken by criteria - final long startTimeCriteria = System.nanoTime(); - cr.add(Restrictions.like("itemName", "%item One%")); - final List results = cr.list(); - final long endTimeCriteria = System.nanoTime(); - final long durationCriteria = (endTimeCriteria - startTimeCriteria) / 1000; - - // calculate the time taken by HQL - final long startTimeHQL = System.nanoTime(); - tx = session.beginTransaction(); - final List items = session.createQuery("FROM Item where itemName like '%item One%'").list(); - final long endTimeHQL = System.nanoTime(); - final long durationHQL = (endTimeHQL - startTimeHQL) / 1000; - - if (durationCriteria > durationHQL) { - return false; - } else { - return true; - } - } - - // To get items having price more than 1000 - public String[] greaterThanCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.gt("itemPrice", 1000)); - final List greaterThanItemsList = cr.list(); - final String greaterThanItems[] = new String[greaterThanItemsList.size()]; - for (int i = 0; i < greaterThanItemsList.size(); i++) { - greaterThanItems[i] = greaterThanItemsList.get(i).getItemName(); - } - session.close(); - return greaterThanItems; - } - - // To get items having price less than 1000 - public String[] lessThanCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.lt("itemPrice", 1000)); - final List lessThanItemsList = cr.list(); - final String lessThanItems[] = new String[lessThanItemsList.size()]; - for (int i = 0; i < lessThanItemsList.size(); i++) { - lessThanItems[i] = lessThanItemsList.get(i).getItemName(); - } - session.close(); - return lessThanItems; - } - - // To get items whose Name start with Chair - public String[] likeCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.like("itemName", "%chair%")); - final List likeItemsList = cr.list(); - final String likeItems[] = new String[likeItemsList.size()]; - for (int i = 0; i < likeItemsList.size(); i++) { - likeItems[i] = likeItemsList.get(i).getItemName(); - } - session.close(); - return likeItems; - } - - // Case sensitive search - public String[] likeCaseCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.ilike("itemName", "%Chair%")); - final List ilikeItemsList = cr.list(); - final String ilikeItems[] = new String[ilikeItemsList.size()]; - for (int i = 0; i < ilikeItemsList.size(); i++) { - ilikeItems[i] = ilikeItemsList.get(i).getItemName(); - } - session.close(); - return ilikeItems; - } - - // To get records having itemPrice in between 100 and 200 - public String[] betweenCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - // To get items having price more than 1000 - cr.add(Restrictions.between("itemPrice", 100, 200)); - final List betweenItemsList = cr.list(); - final String betweenItems[] = new String[betweenItemsList.size()]; - for (int i = 0; i < betweenItemsList.size(); i++) { - betweenItems[i] = betweenItemsList.get(i).getItemName(); - } - session.close(); - return betweenItems; - } - - // To check if the given property is null - public String[] nullCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.isNull("itemDescription")); - final List nullItemsList = cr.list(); - final String nullDescItems[] = new String[nullItemsList.size()]; - for (int i = 0; i < nullItemsList.size(); i++) { - nullDescItems[i] = nullItemsList.get(i).getItemName(); - } - session.close(); - return nullDescItems; - } - - // To check if the given property is not null - public String[] notNullCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.isNotNull("itemDescription")); - final List notNullItemsList = cr.list(); - final String notNullDescItems[] = new String[notNullItemsList.size()]; - for (int i = 0; i < notNullItemsList.size(); i++) { - notNullDescItems[i] = notNullItemsList.get(i).getItemName(); - } - session.close(); - return notNullDescItems; - } - - // Adding more than one expression in one cr - public String[] twoCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.isNull("itemDescription")); - cr.add(Restrictions.like("itemName", "chair%")); - final List notNullItemsList = cr.list(); - final String notNullDescItems[] = new String[notNullItemsList.size()]; - for (int i = 0; i < notNullItemsList.size(); i++) { - notNullDescItems[i] = notNullItemsList.get(i).getItemName(); - } - session.close(); - return notNullDescItems; - } - - // To get items matching with the above defined conditions joined - // with Logical AND - public String[] andLogicalCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); - final Criterion chairItems = Restrictions.like("itemName", "Chair%"); - final LogicalExpression andExample = Restrictions.and(greaterThanPrice, chairItems); - cr.add(andExample); - final List andItemsList = cr.list(); - final String andItems[] = new String[andItemsList.size()]; - for (int i = 0; i < andItemsList.size(); i++) { - andItems[i] = andItemsList.get(i).getItemName(); - } - session.close(); - return andItems; - } - - // To get items matching with the above defined conditions joined - // with Logical OR - public String[] orLogicalCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); - final Criterion chairItems = Restrictions.like("itemName", "Chair%"); - final LogicalExpression orExample = Restrictions.or(greaterThanPrice, chairItems); - cr.add(orExample); - final List orItemsList = cr.list(); - final String orItems[] = new String[orItemsList.size()]; - for (int i = 0; i < orItemsList.size(); i++) { - orItems[i] = orItemsList.get(i).getItemName(); - } - session.close(); - return orItems; - } - - // Sorting example - public String[] sortingCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.addOrder(Order.asc("itemName")); - cr.addOrder(Order.desc("itemPrice")).list(); - final List sortedItemsList = cr.list(); - final String sortedItems[] = new String[sortedItemsList.size()]; - for (int i = 0; i < sortedItemsList.size(); i++) { - sortedItems[i] = sortedItemsList.get(i).getItemName(); - } - session.close(); - return sortedItems; - } - - // Set projections Row Count - public Long[] projectionRowCount() { - final Session session = HibernateUtil.getHibernateSession(); - final List itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount()).list(); - final Long projectedRowCount[] = new Long[itemProjected.size()]; - for (int i = 0; i < itemProjected.size(); i++) { - projectedRowCount[i] = itemProjected.get(i); - } - session.close(); - return projectedRowCount; - } - - // Set projections average of itemPrice - public Double[] projectionAverage() { - final Session session = HibernateUtil.getHibernateSession(); - final List avgItemPriceList = session.createCriteria(Item.class).setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list(); - - final Double avgItemPrice[] = new Double[avgItemPriceList.size()]; - for (int i = 0; i < avgItemPriceList.size(); i++) { - avgItemPrice[i] = (Double) avgItemPriceList.get(i); - } - session.close(); - return avgItemPrice; - } - -} diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java index 2559d5f048..9fda4c43bb 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java @@ -16,7 +16,7 @@ public class UserEager implements Serializable { @Column(name = "USER_ID") private Long userId; - @OneToMany(fetch = FetchType.EAGER, mappedBy = "user") + @OneToMany(fetch = FetchType.EAGER) private Set orderDetail = new HashSet(); public UserEager() { diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java index 5852e74418..a78eaa4ac0 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java @@ -16,7 +16,7 @@ public class UserLazy implements Serializable { @Column(name = "USER_ID") private Long userId; - @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") + @OneToMany(fetch = FetchType.LAZY) private Set orderDetail = new HashSet(); public UserLazy() { diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java index 1a5142c5c2..35cdd254e3 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/view/FetchingAppView.java @@ -20,7 +20,7 @@ public class FetchingAppView { public Set lazyLoaded() { final Session sessionLazy = HibernateUtil.getHibernateSession("lazy"); List users = sessionLazy.createQuery("From UserLazy").list(); - UserLazy userLazyLoaded = users.get(3); + UserLazy userLazyLoaded = users.get(0); // since data is lazyloaded so data won't be initialized return (userLazyLoaded.getOrderDetail()); } @@ -31,7 +31,7 @@ public class FetchingAppView { // data should be loaded in the following line // also note the queries generated List user = sessionEager.createQuery("From UserEager").list(); - UserEager userEagerLoaded = user.get(3); + UserEager userEagerLoaded = user.get(0); return userEagerLoaded.getOrderDetail(); } diff --git a/spring-hibernate4/src/main/resources/criteria.cfg.xml b/spring-hibernate4/src/main/resources/criteria.cfg.xml deleted file mode 100644 index a39a32e151..0000000000 --- a/spring-hibernate4/src/main/resources/criteria.cfg.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - com.mysql.jdbc.Driver - jdbc:mysql://localhost:3306/test - root - iamtheking - org.hibernate.dialect.MySQLDialect - true - - - \ No newline at end of file diff --git a/spring-hibernate4/src/main/resources/criteria_create_queries.sql b/spring-hibernate4/src/main/resources/criteria_create_queries.sql deleted file mode 100644 index 3a627dd38c..0000000000 --- a/spring-hibernate4/src/main/resources/criteria_create_queries.sql +++ /dev/null @@ -1,7 +0,0 @@ -CREATE TABLE `item` ( - `ITEM_ID` int(11) NOT NULL AUTO_INCREMENT, - `ITEM_DESC` varchar(100) DEFAULT NULL, - `ITEM_PRICE` int(11) NOT NULL, - `ITEM_NAME` varchar(255) NOT NULL, - PRIMARY KEY (`ITEM_ID`) -) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=latin1; diff --git a/spring-hibernate4/src/main/resources/logback.xml b/spring-hibernate4/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-hibernate4/src/main/resources/logback.xml +++ b/spring-hibernate4/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java index ed2e111c8f..2f23a9a532 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java @@ -5,11 +5,6 @@ import static org.junit.Assert.assertNotNull; import java.util.List; -import com.baeldung.persistence.model.Foo; -import com.baeldung.persistence.service.IBarAuditableService; -import com.baeldung.persistence.service.IFooAuditableService; -import com.baeldung.spring.PersistenceConfig; -import com.baeldung.persistence.model.Bar; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.junit.After; @@ -26,8 +21,14 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; +import com.baeldung.persistence.model.Bar; +import com.baeldung.persistence.model.Foo; +import com.baeldung.persistence.service.IBarAuditableService; +import com.baeldung.persistence.service.IFooAuditableService; +import com.baeldung.spring.config.PersistenceTestConfig; + @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) public class EnversFooBarAuditIntegrationTest { private static Logger logger = LoggerFactory.getLogger(EnversFooBarAuditIntegrationTest.class); diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java index b63a4b989b..733074a6a3 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java @@ -7,10 +7,6 @@ import static org.junit.Assert.assertTrue; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; -import com.baeldung.persistence.model.Bar; -import com.baeldung.persistence.model.Bar.OPERATION; -import com.baeldung.persistence.service.IBarService; -import com.baeldung.spring.PersistenceConfig; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; @@ -25,8 +21,13 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; +import com.baeldung.persistence.model.Bar; +import com.baeldung.persistence.model.Bar.OPERATION; +import com.baeldung.persistence.service.IBarService; +import com.baeldung.spring.config.PersistenceTestConfig; + @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) public class JPABarAuditIntegrationTest { private static Logger logger = LoggerFactory.getLogger(JPABarAuditIntegrationTest.class); diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java index e794b282f6..18227abd28 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java @@ -6,9 +6,6 @@ import static org.junit.Assert.assertTrue; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; -import com.baeldung.persistence.model.Bar; -import com.baeldung.persistence.service.IBarService; -import com.baeldung.spring.PersistenceConfig; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; @@ -24,8 +21,12 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; +import com.baeldung.persistence.model.Bar; +import com.baeldung.persistence.service.IBarService; +import com.baeldung.spring.config.PersistenceTestConfig; + @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) public class SpringDataJPABarAuditIntegrationTest { private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class); diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java index 721b20db68..fd7bc4aabf 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java @@ -7,9 +7,6 @@ import static org.junit.Assert.assertThat; import java.util.List; -import com.baeldung.persistence.model.Foo; -import com.baeldung.persistence.service.IFooService; -import com.baeldung.spring.PersistenceConfig; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.ScrollMode; @@ -26,10 +23,13 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; +import com.baeldung.persistence.model.Foo; +import com.baeldung.persistence.service.IFooService; +import com.baeldung.spring.config.PersistenceTestConfig; import com.google.common.collect.Lists; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) public class FooPaginationPersistenceIntegrationTest { @Autowired diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java index 0f76526960..8173088af0 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java @@ -5,9 +5,6 @@ import static org.junit.Assert.assertNull; import java.util.List; import java.util.Set; -import com.baeldung.persistence.model.Bar; -import com.baeldung.persistence.model.Foo; -import com.baeldung.spring.PersistenceConfig; import org.hibernate.Criteria; import org.hibernate.NullPrecedence; import org.hibernate.Query; @@ -23,8 +20,12 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; +import com.baeldung.persistence.model.Bar; +import com.baeldung.persistence.model.Foo; +import com.baeldung.spring.config.PersistenceTestConfig; + @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) @SuppressWarnings("unchecked") public class FooSortingPersistenceIntegrationTest { diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServiceBasicPersistenceIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServiceBasicPersistenceIntegrationTest.java index c77f5dfb95..146f8e9622 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServiceBasicPersistenceIntegrationTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServiceBasicPersistenceIntegrationTest.java @@ -2,8 +2,6 @@ package com.baeldung.persistence.service; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import com.baeldung.persistence.model.Foo; -import com.baeldung.spring.PersistenceConfig; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.junit.After; @@ -15,8 +13,11 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; +import com.baeldung.persistence.model.Foo; +import com.baeldung.spring.config.PersistenceTestConfig; + @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) public class FooServiceBasicPersistenceIntegrationTest { @Autowired diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java index b82d4621ab..6d426849a6 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java @@ -2,8 +2,6 @@ package com.baeldung.persistence.service; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import com.baeldung.persistence.model.Foo; -import com.baeldung.spring.PersistenceConfig; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; @@ -16,8 +14,11 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; +import com.baeldung.persistence.model.Foo; +import com.baeldung.spring.config.PersistenceTestConfig; + @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) public class FooServicePersistenceIntegrationTest { @Autowired diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java deleted file mode 100644 index db64107405..0000000000 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.baeldung.persistence.service; - -import java.util.List; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.junit.Assert.assertEquals; - -import org.hibernate.Query; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.exception.SQLGrammarException; -import org.junit.After; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import com.baeldung.persistence.model.Foo; -import com.baeldung.spring.PersistenceConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class FooStoredProceduresIntegrationTest { - - private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresIntegrationTest.class); - - @Autowired - private SessionFactory sessionFactory; - - @Autowired - private IFooService fooService; - - private Session session; - - @Before - public final void before() { - session = sessionFactory.openSession(); - Assume.assumeTrue(getAllFoosExists()); - Assume.assumeTrue(getFoosByNameExists()); - } - - private boolean getFoosByNameExists() { - try { - Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); - sqlQuery.list(); - return true; - } catch (SQLGrammarException e) { - LOGGER.error("WARNING : GetFoosByName() Procedure is may be missing ", e); - return false; - } - } - - private boolean getAllFoosExists() { - try { - Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); - sqlQuery.list(); - return true; - } catch (SQLGrammarException e) { - LOGGER.error("WARNING : GetAllFoos() Procedure is may be missing ", e); - return false; - } - } - - @After - public final void after() { - session.close(); - } - - @Test - public final void getAllFoosUsingStoredProcedures() { - - fooService.create(new Foo(randomAlphabetic(6))); - - // Stored procedure getAllFoos using createSQLQuery - Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); - @SuppressWarnings("unchecked") - List allFoos = sqlQuery.list(); - for (Foo foo : allFoos) { - LOGGER.info("getAllFoos() SQL Query result : {}", foo.getName()); - } - assertEquals(allFoos.size(), fooService.findAll().size()); - - // Stored procedure getAllFoos using a Named Query - Query namedQuery = session.getNamedQuery("callGetAllFoos"); - @SuppressWarnings("unchecked") - List allFoos2 = namedQuery.list(); - for (Foo foo : allFoos2) { - LOGGER.info("getAllFoos() NamedQuery result : {}", foo.getName()); - } - assertEquals(allFoos2.size(), fooService.findAll().size()); - } - - @Test - public final void getFoosByNameUsingStoredProcedures() { - - fooService.create(new Foo("NewFooName")); - - // Stored procedure getFoosByName using createSQLQuery() - Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName"); - @SuppressWarnings("unchecked") - List allFoosByName = sqlQuery.list(); - for (Foo foo : allFoosByName) { - LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString()); - } - - // Stored procedure getFoosByName using getNamedQuery() - Query namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName"); - @SuppressWarnings("unchecked") - List allFoosByName2 = namedQuery.list(); - for (Foo foo : allFoosByName2) { - LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString()); - } - - } -} diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java new file mode 100644 index 0000000000..9ec04d297c --- /dev/null +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java @@ -0,0 +1,121 @@ +package com.baeldung.persistence.service; + +import java.util.List; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.junit.Assert.assertEquals; + +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.exception.SQLGrammarException; +import org.junit.After; +import org.junit.Assume; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.persistence.model.Foo; +import com.baeldung.spring.PersistenceConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class FooStoredProceduresLiveTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresLiveTest.class); + + @Autowired + private SessionFactory sessionFactory; + + @Autowired + private IFooService fooService; + + private Session session; + + @Before + public final void before() { + session = sessionFactory.openSession(); + Assume.assumeTrue(getAllFoosExists()); + Assume.assumeTrue(getFoosByNameExists()); + } + + private boolean getFoosByNameExists() { + try { + Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); + sqlQuery.list(); + return true; + } catch (SQLGrammarException e) { + LOGGER.error("WARNING : GetFoosByName() Procedure is may be missing ", e); + return false; + } + } + + private boolean getAllFoosExists() { + try { + Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); + sqlQuery.list(); + return true; + } catch (SQLGrammarException e) { + LOGGER.error("WARNING : GetAllFoos() Procedure is may be missing ", e); + return false; + } + } + + @After + public final void after() { + session.close(); + } + + @Test + public final void getAllFoosUsingStoredProcedures() { + + fooService.create(new Foo(randomAlphabetic(6))); + + // Stored procedure getAllFoos using createSQLQuery + Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); + @SuppressWarnings("unchecked") + List allFoos = sqlQuery.list(); + for (Foo foo : allFoos) { + LOGGER.info("getAllFoos() SQL Query result : {}", foo.getName()); + } + assertEquals(allFoos.size(), fooService.findAll().size()); + + // Stored procedure getAllFoos using a Named Query + Query namedQuery = session.getNamedQuery("callGetAllFoos"); + @SuppressWarnings("unchecked") + List allFoos2 = namedQuery.list(); + for (Foo foo : allFoos2) { + LOGGER.info("getAllFoos() NamedQuery result : {}", foo.getName()); + } + assertEquals(allFoos2.size(), fooService.findAll().size()); + } + + @Test + public final void getFoosByNameUsingStoredProcedures() { + + fooService.create(new Foo("NewFooName")); + + // Stored procedure getFoosByName using createSQLQuery() + Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName"); + @SuppressWarnings("unchecked") + List allFoosByName = sqlQuery.list(); + for (Foo foo : allFoosByName) { + LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString()); + } + + // Stored procedure getFoosByName using getNamedQuery() + Query namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName"); + @SuppressWarnings("unchecked") + List allFoosByName2 = namedQuery.list(); + for (Foo foo : allFoosByName2) { + LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString()); + } + + } +} diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java index 9e8c4aba92..5a73e39ca2 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java @@ -1,8 +1,5 @@ package com.baeldung.persistence.service; -import com.baeldung.persistence.model.Child; -import com.baeldung.persistence.model.Parent; -import com.baeldung.spring.PersistenceConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -11,8 +8,12 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; +import com.baeldung.persistence.model.Child; +import com.baeldung.persistence.model.Parent; +import com.baeldung.spring.config.PersistenceTestConfig; + @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) public class ParentServicePersistenceIntegrationTest { @Autowired diff --git a/spring-hibernate4/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java b/spring-hibernate4/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java new file mode 100644 index 0000000000..9bf55c902a --- /dev/null +++ b/spring-hibernate4/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java @@ -0,0 +1,179 @@ +package com.baeldung.spring.config; + +import java.util.Properties; + +import javax.sql.DataSource; + +import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.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.EnableJpaAuditing; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.hibernate4.HibernateTransactionManager; +import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.JpaVendorAdapter; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.baeldung.persistence.dao.IBarAuditableDao; +import com.baeldung.persistence.dao.IBarDao; +import com.baeldung.persistence.dao.IFooAuditableDao; +import com.baeldung.persistence.dao.IFooDao; +import com.baeldung.persistence.dao.impl.BarAuditableDao; +import com.baeldung.persistence.dao.impl.BarDao; +import com.baeldung.persistence.dao.impl.BarJpaDao; +import com.baeldung.persistence.dao.impl.FooAuditableDao; +import com.baeldung.persistence.dao.impl.FooDao; +import com.baeldung.persistence.service.IBarAuditableService; +import com.baeldung.persistence.service.IBarService; +import com.baeldung.persistence.service.IFooAuditableService; +import com.baeldung.persistence.service.IFooService; +import com.baeldung.persistence.service.impl.BarAuditableService; +import com.baeldung.persistence.service.impl.BarJpaService; +import com.baeldung.persistence.service.impl.BarSpringDataJpaService; +import com.baeldung.persistence.service.impl.FooAuditableService; +import com.baeldung.persistence.service.impl.FooService; +import com.google.common.base.Preconditions; + +@Configuration +@EnableTransactionManagement +@EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager") +@EnableJpaAuditing +@PropertySource({ "classpath:persistence-h2.properties" }) +@ComponentScan({ "com.baeldung.persistence" }) +public class PersistenceTestConfig { + + @Autowired + private Environment env; + + public PersistenceTestConfig() { + super(); + } + + @Bean + public LocalSessionFactoryBean sessionFactory() { + final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); + sessionFactory.setDataSource(restDataSource()); + sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + sessionFactory.setHibernateProperties(hibernateProperties()); + + return sessionFactory; + } + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); + emf.setDataSource(restDataSource()); + emf.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + + final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + emf.setJpaVendorAdapter(vendorAdapter); + emf.setJpaProperties(hibernateProperties()); + + return emf; + } + + @Bean + public DataSource restDataSource() { + final BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + public PlatformTransactionManager hibernateTransactionManager() { + final HibernateTransactionManager transactionManager = new HibernateTransactionManager(); + transactionManager.setSessionFactory(sessionFactory().getObject()); + return transactionManager; + } + + @Bean + public PlatformTransactionManager jpaTransactionManager() { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + @Bean + public IBarService barJpaService() { + return new BarJpaService(); + } + + @Bean + public IBarService barSpringDataJpaService() { + return new BarSpringDataJpaService(); + } + + @Bean + public IFooService fooHibernateService() { + return new FooService(); + } + + @Bean + public IBarAuditableService barHibernateAuditableService() { + return new BarAuditableService(); + } + + @Bean + public IFooAuditableService fooHibernateAuditableService() { + return new FooAuditableService(); + } + + @Bean + public IBarDao barJpaDao() { + return new BarJpaDao(); + } + + @Bean + public IBarDao barHibernateDao() { + return new BarDao(); + } + + @Bean + public IBarAuditableDao barHibernateAuditableDao() { + return new BarAuditableDao(); + } + + @Bean + public IFooDao fooHibernateDao() { + return new FooDao(); + } + + @Bean + public IFooAuditableDao fooHibernateAuditableDao() { + return new FooAuditableDao(); + } + + private final Properties hibernateProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + + hibernateProperties.setProperty("hibernate.show_sql", "true"); + // hibernateProperties.setProperty("hibernate.format_sql", "true"); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + + // Envers properties + hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); + + return hibernateProperties; + } + +} \ No newline at end of file diff --git a/spring-hibernate4/src/test/resources/criteria.cfg.xml b/spring-hibernate4/src/test/resources/criteria.cfg.xml deleted file mode 100644 index 653b5a188a..0000000000 --- a/spring-hibernate4/src/test/resources/criteria.cfg.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - com.mysql.jdbc.Driver - jdbc:mysql://localhost:3306/test - root - iamtheking - org.hibernate.dialect.MySQLDialect - true - - - \ No newline at end of file diff --git a/spring-hibernate4/src/test/resources/fetching.cfg.xml b/spring-hibernate4/src/test/resources/fetching.cfg.xml index acee7008ba..55a3aeb51c 100644 --- a/spring-hibernate4/src/test/resources/fetching.cfg.xml +++ b/spring-hibernate4/src/test/resources/fetching.cfg.xml @@ -5,14 +5,15 @@ - com.mysql.jdbc.Driver - jdbc:mysql://localhost:3306/test - root - iamtheking - org.hibernate.dialect.MySQLDialect + org.h2.Driver + jdbc:h2:mem:testdb + sa + + org.hibernate.dialect.H2Dialect + update true - + \ No newline at end of file diff --git a/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml b/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml index 1dc37d0cf8..8fcf578660 100644 --- a/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml +++ b/spring-hibernate4/src/test/resources/fetchingLazy.cfg.xml @@ -5,14 +5,15 @@ - com.mysql.jdbc.Driver - jdbc:mysql://localhost:3306/test - root - iamtheking - org.hibernate.dialect.MySQLDialect + org.h2.Driver + jdbc:h2:mem:testdb + sa + + org.hibernate.dialect.H2Dialect + update true - + \ No newline at end of file diff --git a/spring-hibernate4/src/test/resources/persistence-h2.properties b/spring-hibernate4/src/test/resources/persistence-h2.properties new file mode 100644 index 0000000000..911619193b --- /dev/null +++ b/spring-hibernate4/src/test/resources/persistence-h2.properties @@ -0,0 +1,13 @@ +# jdbc.X +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:test +jdbc.user=sa +jdbc.pass= + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create-drop + +# envers.X +envers.audit_table_suffix=_audit_log diff --git a/spring-integration/README.md b/spring-integration/README.md index d782862901..e116f934c8 100644 --- a/spring-integration/README.md +++ b/spring-integration/README.md @@ -1,6 +1,7 @@ ### Relevant Articles: - [Introduction to Spring Integration](http://www.baeldung.com/spring-integration) - [Security In Spring Integration](http://www.baeldung.com/spring-integration-security) +- [Spring Integration Java DSL](https://www.baeldung.com/spring-integration-java-dsl) ### Running the Sample Executing the `mvn exec:java` maven command (either from the command line or from an IDE) will start up the application. Follow the command prompt for further instructions. diff --git a/spring-integration/pom.xml b/spring-integration/pom.xml index 7cb2be45e0..457645a144 100644 --- a/spring-integration/pom.xml +++ b/spring-integration/pom.xml @@ -1,5 +1,5 @@ + 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.samples.spring.integration spring-integration @@ -14,52 +14,6 @@ 1.0.0-SNAPSHOT - - UTF-8 - 5.0.3.RELEASE - 1.1.4.RELEASE - 1.4.7 - 1.1.1 - 4.12 - 2.10 - 1.5.0 - - - - - repo.springsource.org.milestone - Spring Framework Maven Milestone Repository - https://repo.springsource.org/milestone - - - - - - - maven-eclipse-plugin - ${maven-eclipse-plugin.version} - - - org.springframework.ide.eclipse.core.springnature - - - org.springframework.ide.eclipse.core.springbuilder - - true - true - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - com.baeldung.samples.FileCopyConfig - - - - - @@ -121,12 +75,52 @@ ${spring.version} test - - junit - junit - ${junit.version} - test - + + + + maven-eclipse-plugin + ${maven-eclipse-plugin.version} + + + org.springframework.ide.eclipse.core.springnature + + + org.springframework.ide.eclipse.core.springbuilder + + true + true + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + com.baeldung.samples.FileCopyConfig + + + + + + + + repo.springsource.org.milestone + Spring Framework Maven Milestone Repository + https://repo.springsource.org/milestone + + + + + UTF-8 + 5.0.3.RELEASE + 1.1.4.RELEASE + 1.4.7 + 1.1.1 + 4.12 + 2.10 + 1.5.0 + + diff --git a/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java b/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java new file mode 100644 index 0000000000..7e91345f04 --- /dev/null +++ b/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java @@ -0,0 +1,146 @@ +package com.baeldung.dsl; + +import java.io.File; +import java.util.Scanner; +import java.util.concurrent.TimeUnit; + +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.integration.annotation.IntegrationComponentScan; +import org.springframework.integration.channel.PriorityChannel; +import org.springframework.integration.config.EnableIntegration; +import org.springframework.integration.core.GenericSelector; +import org.springframework.integration.core.MessageSource; +import org.springframework.integration.dsl.IntegrationFlow; +import org.springframework.integration.dsl.IntegrationFlows; +import org.springframework.integration.dsl.Pollers; +import org.springframework.integration.file.FileReadingMessageSource; +import org.springframework.integration.file.FileWritingMessageHandler; +import org.springframework.messaging.MessageHandler; + +/** + * JavaDSLFileCopyConfig contains various Integration Flows created from various spring integration components. + * Activate only one flow at a time by un-commenting @Bean annotation from IntegrationFlow beans. + *

    + * Different flows are :
    + * - {@link #fileMover()} - default app - activated
    + * - {@link #fileMoverWithLambda()} - app with file writing expressions as lambda
    + * - {@link #fileMoverWithPriorityChannel()} - app with priority channel
    + * - {@link #fileReader()}, {@link #fileWriter()}, {@link #anotherFileWriter()} - app with bridge + */ +@Configuration +@EnableIntegration +@IntegrationComponentScan +public class JavaDSLFileCopyConfig { + + public static final String INPUT_DIR = "source"; + public static final String OUTPUT_DIR = "target"; + public static final String OUTPUT_DIR2 = "target2"; + + @Bean + public MessageSource sourceDirectory() { + FileReadingMessageSource messageSource = new FileReadingMessageSource(); + messageSource.setDirectory(new File(INPUT_DIR)); + return messageSource; + } + + @Bean + public GenericSelector onlyJpgs() { + return new GenericSelector() { + + @Override + public boolean accept(File source) { + return source.getName() + .endsWith(".jpg"); + } + }; + } + + @Bean + public MessageHandler targetDirectory() { + FileWritingMessageHandler handler = new FileWritingMessageHandler(new File(OUTPUT_DIR)); + handler.setExpectReply(false); // end of pipeline, reply not needed + return handler; + } + + @Bean + public IntegrationFlow fileMover() { + return IntegrationFlows.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10000))) + .filter(onlyJpgs()) + .handle(targetDirectory()) + .get(); + } + + // @Bean + public IntegrationFlow fileMoverWithLambda() { + return IntegrationFlows.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10000))) + .filter(message -> ((File) message).getName() + .endsWith(".jpg")) + .handle(targetDirectory()) + .get(); + } + + @Bean + public PriorityChannel alphabetically() { + return new PriorityChannel(1000, (left, right) -> ((File) left.getPayload()).getName() + .compareTo(((File) right.getPayload()).getName())); + } + + // @Bean + public IntegrationFlow fileMoverWithPriorityChannel() { + return IntegrationFlows.from(sourceDirectory()) + .filter(onlyJpgs()) + .channel("alphabetically") + .handle(targetDirectory()) + .get(); + } + + @Bean + public MessageHandler anotherTargetDirectory() { + FileWritingMessageHandler handler = new FileWritingMessageHandler(new File(OUTPUT_DIR2)); + handler.setExpectReply(false); // end of pipeline, reply not needed + return handler; + } + + // @Bean + public IntegrationFlow fileReader() { + return IntegrationFlows.from(sourceDirectory()) + .filter(onlyJpgs()) + .channel("holdingTank") + .get(); + } + + // @Bean + public IntegrationFlow fileWriter() { + return IntegrationFlows.from("holdingTank") + .bridge(e -> e.poller(Pollers.fixedRate(1, TimeUnit.SECONDS, 20))) + .handle(targetDirectory()) + .get(); + } + + // @Bean + public IntegrationFlow anotherFileWriter() { + return IntegrationFlows.from("holdingTank") + .bridge(e -> e.poller(Pollers.fixedRate(2, TimeUnit.SECONDS, 10))) + .handle(anotherTargetDirectory()) + .get(); + } + + public static void main(final String... args) { + final AbstractApplicationContext context = new AnnotationConfigApplicationContext(JavaDSLFileCopyConfig.class); + context.registerShutdownHook(); + final Scanner scanner = new Scanner(System.in); + System.out.print("Please enter a string and press : "); + while (true) { + final String input = scanner.nextLine(); + if ("q".equals(input.trim())) { + context.close(); + scanner.close(); + break; + } + } + System.exit(0); + } +} diff --git a/spring-integration/src/main/resources/logback.xml b/spring-integration/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-integration/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-integration/src/test/resources/logback-test.xml b/spring-integration/src/test/resources/logback-test.xml index a807be0ca2..8f1be4eb7a 100644 --- a/spring-integration/src/test/resources/logback-test.xml +++ b/spring-integration/src/test/resources/logback-test.xml @@ -1,5 +1,15 @@ - - + + + # Pattern of log message for console appender + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-jenkins-pipeline/pom.xml b/spring-jenkins-pipeline/pom.xml index c43952e277..85336f9689 100644 --- a/spring-jenkins-pipeline/pom.xml +++ b/spring-jenkins-pipeline/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-jenkins-pipeline 0.0.1-SNAPSHOT @@ -9,10 +9,10 @@ Intro to Jenkins 2 and the power of pipelines - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -29,6 +29,12 @@ spring-boot-starter-test test + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + ${de.flapdoodle.embed.mongo.version} + test + @@ -55,6 +61,7 @@ **/*IntegrationTest.java + **/*IntTest.java @@ -68,10 +75,8 @@ - UTF-8 - UTF-8 - 1.8 2.17 + 2.0.0 diff --git a/spring-jenkins-pipeline/src/main/resources/logback.xml b/spring-jenkins-pipeline/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-jenkins-pipeline/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-jenkins-pipeline/src/test/java/com/baeldung/SomeIntegrationTest.java b/spring-jenkins-pipeline/src/test/java/com/baeldung/SomeIntegrationTest.java index 092ebb93fd..477a7d2adb 100644 --- a/spring-jenkins-pipeline/src/test/java/com/baeldung/SomeIntegrationTest.java +++ b/spring-jenkins-pipeline/src/test/java/com/baeldung/SomeIntegrationTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertNotEquals; @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest +@SpringBootTest(classes = {SpringJenkinsPipelineApplication.class, TestMongoConfig.class }) public class SomeIntegrationTest { @Autowired private StudentRepository studentRepository; diff --git a/spring-jenkins-pipeline/src/test/java/com/baeldung/TestMongoConfig.java b/spring-jenkins-pipeline/src/test/java/com/baeldung/TestMongoConfig.java new file mode 100644 index 0000000000..a85491cf7e --- /dev/null +++ b/spring-jenkins-pipeline/src/test/java/com/baeldung/TestMongoConfig.java @@ -0,0 +1,11 @@ +package com.baeldung; + +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableAutoConfiguration(exclude = { EmbeddedMongoAutoConfiguration.class }) +public class TestMongoConfig { + +} \ No newline at end of file diff --git a/spring-jersey/README.md b/spring-jersey/README.md index 8b2eecc0e1..37928620d3 100644 --- a/spring-jersey/README.md +++ b/spring-jersey/README.md @@ -3,3 +3,4 @@ ## REST API with Jersey & Spring Example Project - [REST API with Jersey and Spring](http://www.baeldung.com/jersey-rest-api-with-spring) - [JAX-RS Client with Jersey](http://www.baeldung.com/jersey-jax-rs-client) +- [Reactive JAX-RS Client API](https://www.baeldung.com/jax-rs-reactive-client) diff --git a/spring-jersey/pom.xml b/spring-jersey/pom.xml index 4a37f4b2ab..40dc91a88d 100644 --- a/spring-jersey/pom.xml +++ b/spring-jersey/pom.xml @@ -1,8 +1,7 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-jersey 0.1-SNAPSHOT @@ -14,37 +13,6 @@ 1.0.0-SNAPSHOT - - spring-jersey - - - maven-war-plugin - ${maven-war-plugin.version} - - false - - - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - 8082 - - - - - - - @@ -108,6 +76,49 @@ test + + org.glassfish.jersey.inject + jersey-hk2 + ${jersey.version} + + + org.glassfish.jersey.ext.rx + jersey-rx-client-rxjava + ${jersey.version} + + + org.glassfish.jersey.ext.rx + jersey-rx-client-rxjava2 + ${jersey.version} + + + com.github.tomakehurst + wiremock + 1.58 + test + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + 2.6.0 + + + com.fasterxml.jackson.core + jackson-databind + 2.6.0 + + + org.slf4j + slf4j-jdk14 + 1.7.25 + + + org.assertj + assertj-core + 3.10.0 + test + + @@ -127,6 +138,7 @@ **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java @@ -169,8 +181,39 @@ + + spring-jersey + + + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + 8082 + + + + + + + - 2.26 + 2.27 3.2.0 1.6.1 4.4.9 diff --git a/spring-jersey/src/main/resources/logback.xml b/spring-jersey/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-jersey/src/main/resources/logback.xml +++ b/spring-jersey/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-jersey/src/test/java/com/baeldung/clientrx/ClientOrchestrationIntegrationTest.java b/spring-jersey/src/test/java/com/baeldung/clientrx/ClientOrchestrationIntegrationTest.java new file mode 100644 index 0000000000..990279a481 --- /dev/null +++ b/spring-jersey/src/test/java/com/baeldung/clientrx/ClientOrchestrationIntegrationTest.java @@ -0,0 +1,272 @@ +package com.baeldung.clientrx; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static org.assertj.core.api.Assertions.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.InvocationCallback; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; + +import org.glassfish.jersey.client.rx.rxjava.RxObservableInvoker; +import org.glassfish.jersey.client.rx.rxjava.RxObservableInvokerProvider; +import org.glassfish.jersey.client.rx.rxjava2.RxFlowableInvoker; +import org.glassfish.jersey.client.rx.rxjava2.RxFlowableInvokerProvider; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.tomakehurst.wiremock.junit.WireMockRule; + +import io.reactivex.Flowable; +import rx.Observable; + +/** + * + * @author baeldung + */ +public class ClientOrchestrationIntegrationTest { + + private Client client = ClientBuilder.newClient(); + + private WebTarget userIdService = client.target("http://localhost:8080/id-service/ids"); + private WebTarget nameService = client.target("http://localhost:8080/name-service/users/{userId}/name"); + private WebTarget hashService = client.target("http://localhost:8080/hash-service/{rawValue}"); + + private Logger logger = LoggerFactory.getLogger(ClientOrchestrationIntegrationTest.class); + + private String expectedUserIds = "[1,2,3,4,5,6]"; + + private List expectedNames = Arrays.asList("n/a", "Thor", "Hulk", "BlackWidow", "BlackPanther", "TheTick", "Hawkeye"); + + private List expectedHashValues = Arrays.asList("roht1", "kluh2", "WodiwKcalb3", "RehtnapKclab4", "kciteht5", "eyekwah6"); + + @Rule + public WireMockRule wireMockServer = new WireMockRule(); + + @Before + public void setup() { + + stubFor(get(urlEqualTo("/id-service/ids")).willReturn(aResponse().withBody(expectedUserIds).withHeader("Content-Type", "application/json"))); + + stubFor(get(urlEqualTo("/name-service/users/1/name")).willReturn(aResponse().withBody(expectedNames.get(1)))); + stubFor(get(urlEqualTo("/name-service/users/2/name")).willReturn(aResponse().withBody(expectedNames.get(2)))); + stubFor(get(urlEqualTo("/name-service/users/3/name")).willReturn(aResponse().withBody(expectedNames.get(3)))); + stubFor(get(urlEqualTo("/name-service/users/4/name")).willReturn(aResponse().withBody(expectedNames.get(4)))); + stubFor(get(urlEqualTo("/name-service/users/5/name")).willReturn(aResponse().withBody(expectedNames.get(5)))); + stubFor(get(urlEqualTo("/name-service/users/6/name")).willReturn(aResponse().withBody(expectedNames.get(6)))); + + stubFor(get(urlEqualTo("/hash-service/Thor1")).willReturn(aResponse().withBody(expectedHashValues.get(0)))); + stubFor(get(urlEqualTo("/hash-service/Hulk2")).willReturn(aResponse().withBody(expectedHashValues.get(1)))); + stubFor(get(urlEqualTo("/hash-service/BlackWidow3")).willReturn(aResponse().withBody(expectedHashValues.get(2)))); + stubFor(get(urlEqualTo("/hash-service/BlackPanther4")).willReturn(aResponse().withBody(expectedHashValues.get(3)))); + stubFor(get(urlEqualTo("/hash-service/TheTick5")).willReturn(aResponse().withBody(expectedHashValues.get(4)))); + stubFor(get(urlEqualTo("/hash-service/Hawkeye6")).willReturn(aResponse().withBody(expectedHashValues.get(5)))); + + } + + @Test + public void callBackOrchestrate() throws InterruptedException { + List receivedHashValues = new ArrayList<>(); + + final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls + + userIdService.request().accept(MediaType.APPLICATION_JSON).async().get(new InvocationCallback>() { + @Override + public void completed(List employeeIds) { + logger.info("[CallbackExample] id-service result: {}", employeeIds); + employeeIds.forEach((id) -> { + // for each employee ID, get the name + nameService.resolveTemplate("userId", id).request().async().get(new InvocationCallback() { + + @Override + public void completed(String response) { + logger.info("[CallbackExample] name-service result: {}", response); + + hashService.resolveTemplate("rawValue", response + id).request().async().get(new InvocationCallback() { + @Override + public void completed(String response) { + logger.info("[CallbackExample] hash-service result: {}", response); + receivedHashValues.add(response); + completionTracker.countDown(); + } + + @Override + public void failed(Throwable throwable) { + logger.warn("[CallbackExample] An error has occurred in the hashing request step!", throwable); + } + }); + } + + @Override + public void failed(Throwable throwable) { + logger.warn("[CallbackExample] An error has occurred in the username request step!", throwable); + } + }); + }); + + } + + @Override + public void failed(Throwable throwable) { + logger.warn("[CallbackExample] An error has occurred in the userId request step!", throwable); + } + }); + + // wait for async calls to complete + try { + // wait for inner requests to complete in 10 seconds + if (!completionTracker.await(10, TimeUnit.SECONDS)) { + logger.warn("[CallbackExample] Some requests didn't complete within the timeout"); + } + } catch (InterruptedException e) { + logger.error("Interrupted!", e); + } + + assertThat(receivedHashValues).containsAll(expectedHashValues); + } + + @Test + public void rxOrchestrate() throws InterruptedException { + List receivedHashValues = new ArrayList<>(); + + final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls + + CompletionStage> userIdStage = userIdService.request().accept(MediaType.APPLICATION_JSON).rx().get(new GenericType>() { + }).exceptionally((throwable) -> { + logger.warn("[CompletionStageExample] An error has occurred"); + return null; + }); + + userIdStage.thenAcceptAsync(employeeIds -> { + logger.info("[CompletionStageExample] id-service result: {}", employeeIds); + employeeIds.forEach((Long id) -> { + CompletableFuture completable = nameService.resolveTemplate("userId", id).request().rx().get(String.class).toCompletableFuture(); + + completable.thenAccept((String userName) -> { + logger.info("[CompletionStageExample] name-service result: {}", userName); + hashService.resolveTemplate("rawValue", userName + id).request().rx().get(String.class).toCompletableFuture().thenAcceptAsync(hashValue -> { + logger.info("[CompletionStageExample] hash-service result: {}", hashValue); + receivedHashValues.add(hashValue); + completionTracker.countDown(); + }).exceptionally((throwable) -> { + logger.warn("[CompletionStageExample] Hash computation failed for {}", id); + completionTracker.countDown(); + return null; + }); + + }); + + }); + }); + + // wait for async calls to complete + try { + // wait for inner requests to complete in 10 seconds + if (!completionTracker.await(10, TimeUnit.SECONDS)) { + logger.warn("[CallbackExample] Some requests didn't complete within the timeout"); + } + } catch (InterruptedException e) { + logger.error("Interrupted!", e); + } + + assertThat(receivedHashValues).containsAll(expectedHashValues); + } + + @Test + public void observableJavaOrchestrate() throws InterruptedException { + List receivedHashValues = new ArrayList<>(); + + final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls + + Observable> observableUserIdService = userIdService.register(RxObservableInvokerProvider.class).request().accept(MediaType.APPLICATION_JSON).rx(RxObservableInvoker.class).get(new GenericType>() { + }).asObservable(); + + observableUserIdService.subscribe((List employeeIds) -> { + logger.info("[ObservableExample] id-service result: {}", employeeIds); + Observable.from(employeeIds).subscribe(id -> nameService.register(RxObservableInvokerProvider.class).resolveTemplate("userId", id).request().rx(RxObservableInvoker.class).get(String.class).asObservable() // gotten the name for the given + // userId + .doOnError((throwable) -> { + logger.warn("[ObservableExample] An error has occurred in the username request step {}", throwable.getMessage()); + }).subscribe(userName -> { + logger.info("[ObservableExample] name-service result: {}", userName); + hashService.register(RxObservableInvokerProvider.class).resolveTemplate("rawValue", userName + id).request().rx(RxObservableInvoker.class).get(String.class).asObservable() // gotten the hash value for + // userId+username + .doOnError((throwable) -> { + logger.warn("[ObservableExample] An error has occurred in the hashing request step {}", throwable.getMessage()); + }).subscribe(hashValue -> { + logger.info("[ObservableExample] hash-service result: {}", hashValue); + receivedHashValues.add(hashValue); + completionTracker.countDown(); + }); + })); + }); + + // wait for async calls to complete + try { + // wait for inner requests to complete in 10 seconds + if (!completionTracker.await(10, TimeUnit.SECONDS)) { + logger.warn("[CallbackExample] Some requests didn't complete within the timeout"); + } + } catch (InterruptedException e) { + logger.error("Interrupted!", e); + } + + assertThat(receivedHashValues).containsAll(expectedHashValues); + } + + @Test + public void flowableJavaOrchestrate() throws InterruptedException { + List receivedHashValues = new ArrayList<>(); + + final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls + + Flowable> userIdFlowable = userIdService.register(RxFlowableInvokerProvider.class).request().rx(RxFlowableInvoker.class).get(new GenericType>() { + }); + + userIdFlowable.subscribe((List employeeIds) -> { + logger.info("[FlowableExample] id-service result: {}", employeeIds); + Flowable.fromIterable(employeeIds).subscribe(id -> { + nameService.register(RxFlowableInvokerProvider.class).resolveTemplate("userId", id).request().rx(RxFlowableInvoker.class).get(String.class) // gotten the name for the given userId + .doOnError((throwable) -> { + logger.warn("[FlowableExample] An error has occurred in the username request step {}", throwable.getMessage()); + }).subscribe(userName -> { + logger.info("[FlowableExample] name-service result: {}", userName); + hashService.register(RxFlowableInvokerProvider.class).resolveTemplate("rawValue", userName + id).request().rx(RxFlowableInvoker.class).get(String.class) // gotten the hash value for userId+username + .doOnError((throwable) -> { + logger.warn(" [FlowableExample] An error has occurred in the hashing request step!", throwable); + }).subscribe(hashValue -> { + logger.info("[FlowableExample] hash-service result: {}", hashValue); + receivedHashValues.add(hashValue); + completionTracker.countDown(); + }); + }); + }); + }); + + // wait for async calls to complete + try { + // wait for inner requests to complete in 10 seconds + if (!completionTracker.await(10, TimeUnit.SECONDS)) { + logger.warn("[CallbackExample] Some requests didn't complete within the timeout"); + } + } catch (InterruptedException e) { + logger.error("Interrupted!", e); + } + + assertThat(receivedHashValues).containsAll(expectedHashValues); + } + +} diff --git a/spring-jinq/pom.xml b/spring-jinq/pom.xml index 30d8cef823..f142b3ee2f 100644 --- a/spring-jinq/pom.xml +++ b/spring-jinq/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-jinq 0.1-SNAPSHOT @@ -13,18 +13,6 @@ 1.0.0-SNAPSHOT - - - - org.springframework.boot - spring-boot-dependencies - 1.5.9.RELEASE - pom - import - - - - org.jinq @@ -71,9 +59,20 @@ + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + - UTF-8 - 1.8 + 1.5.9.RELEASE 1.8.22 diff --git a/spring-jinq/src/main/resources/logback.xml b/spring-jinq/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-jinq/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-jms/pom.xml b/spring-jms/pom.xml index 6547327161..949a78b2a1 100644 --- a/spring-jms/pom.xml +++ b/spring-jms/pom.xml @@ -1,5 +1,5 @@ + 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-jms diff --git a/spring-jms/src/main/resources/logback.xml b/spring-jms/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-jms/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-jooq/pom.xml b/spring-jooq/pom.xml index bd8bc6f404..744ae34cc8 100644 --- a/spring-jooq/pom.xml +++ b/spring-jooq/pom.xml @@ -1,28 +1,15 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-jooq - 0.0.1-SNAPSHOT - + + parent-boot-1 com.baeldung - parent-modules - 1.0.0-SNAPSHOT + 0.0.1-SNAPSHOT + ../parent-boot-1 - - - - - org.springframework.boot - spring-boot-dependencies - 1.4.4.RELEASE - pom - import - - - - @@ -55,6 +42,10 @@ org.springframework.boot spring-boot-starter-jooq + + org.springframework.boot + spring-boot-starter-test + @@ -62,11 +53,6 @@ spring-test test - - org.springframework.boot - spring-boot-starter-test - - @@ -151,8 +137,7 @@ - + org.eclipse.m2e lifecycle-mapping @@ -185,15 +170,29 @@ + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + 3.8.6 1.4.193 - 4.3.4.RELEASE + 4.3.17.RELEASE 1.0.0 1.5 1.0.0 - + 1.5.13.RELEASE + org.jooq.example.spring.Application \ No newline at end of file diff --git a/spring-jooq/src/main/resources/logback.xml b/spring-jooq/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-jooq/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-jooq/src/test/java/com/baeldung/jooq/springboot/SpringBootIntegrationTest.java b/spring-jooq/src/test/java/com/baeldung/jooq/springboot/SpringBootIntegrationTest.java index 25317309ee..5e76fb3c93 100644 --- a/spring-jooq/src/test/java/com/baeldung/jooq/springboot/SpringBootIntegrationTest.java +++ b/spring-jooq/src/test/java/com/baeldung/jooq/springboot/SpringBootIntegrationTest.java @@ -12,14 +12,16 @@ import org.jooq.impl.DSL; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; import org.springframework.dao.DataAccessException; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -@Transactional("transactionManager") +import com.baeldung.jooq.introduction.PersistenceContextIntegrationTest; + +@ContextConfiguration(classes = PersistenceContextIntegrationTest.class) +@Transactional(transactionManager = "transactionManager") +@RunWith(SpringJUnit4ClassRunner.class) public class SpringBootIntegrationTest { @Autowired diff --git a/spring-kafka/pom.xml b/spring-kafka/pom.xml index 3891be1ec3..3060dc00b3 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -1,5 +1,5 @@ + 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-kafka @@ -8,10 +8,10 @@ Intro to Kafka with Spring - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-kafka/src/main/resources/logback.xml b/spring-kafka/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-kafka/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index 27075de747..39648a982c 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -7,10 +7,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -33,7 +33,7 @@ io.katharsis - katharsis-servlet + katharsis-spring ${katharsis.version} @@ -45,12 +45,12 @@ org.reflections reflections - 0.9.10 + ${reflections.version} org.apache.commons commons-lang3 - 3.7 + ${commons-lang3.version} @@ -134,7 +134,9 @@ 3.0.2 + 0.9.10 1.6.1 + 3.7 diff --git a/spring-katharsis/src/main/java/org/baeldung/Application.java b/spring-katharsis/src/main/java/org/baeldung/Application.java index ee072305d8..5ce4ac7e08 100644 --- a/spring-katharsis/src/main/java/org/baeldung/Application.java +++ b/spring-katharsis/src/main/java/org/baeldung/Application.java @@ -1,10 +1,14 @@ package org.baeldung; +import io.katharsis.spring.boot.v3.KatharsisConfigV3; + import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.context.annotation.Import; @SpringBootApplication +@Import(KatharsisConfigV3.class) public class Application extends SpringBootServletInitializer { public static void main(String[] args) { diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/JsonApiFilter.java b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/JsonApiFilter.java deleted file mode 100644 index 3d0d441357..0000000000 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/JsonApiFilter.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.baeldung.persistence.katharsis; - -import io.katharsis.invoker.internal.legacy.KatharsisInvokerBuilder; -import io.katharsis.legacy.locator.JsonServiceLocator; -import io.katharsis.servlet.legacy.AbstractKatharsisFilter; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.stereotype.Component; - -@Component -public class JsonApiFilter extends AbstractKatharsisFilter implements BeanFactoryAware { - - private static final String DEFAULT_RESOURCE_SEARCH_PACKAGE = "org.baeldung.persistence"; - - private static final String RESOURCE_DEFAULT_DOMAIN = "http://localhost:8080"; - - private BeanFactory beanFactory; - - @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.beanFactory = beanFactory; - } - - @Override - protected KatharsisInvokerBuilder createKatharsisInvokerBuilder() { - final KatharsisInvokerBuilder builder = new KatharsisInvokerBuilder(); - - builder.resourceSearchPackage(DEFAULT_RESOURCE_SEARCH_PACKAGE).resourceDefaultDomain(RESOURCE_DEFAULT_DOMAIN).jsonServiceLocator(new JsonServiceLocator() { - @Override - public T getInstance(Class clazz) { - return beanFactory.getBean(clazz); - } - }); - - return builder; - } - -} diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/RoleResourceRepository.java b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/RoleResourceRepository.java index 52ca40e26e..1998c414bb 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/RoleResourceRepository.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/RoleResourceRepository.java @@ -1,7 +1,9 @@ package org.baeldung.persistence.katharsis; -import io.katharsis.legacy.queryParams.QueryParams; -import io.katharsis.legacy.repository.ResourceRepository; + +import io.katharsis.queryspec.QuerySpec; +import io.katharsis.repository.ResourceRepositoryV2; +import io.katharsis.resource.list.ResourceList; import org.baeldung.persistence.dao.RoleRepository; import org.baeldung.persistence.model.Role; @@ -9,23 +11,23 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component -public class RoleResourceRepository implements ResourceRepository { +public class RoleResourceRepository implements ResourceRepositoryV2 { @Autowired private RoleRepository roleRepository; @Override - public Role findOne(Long id, QueryParams params) { + public Role findOne(Long id, QuerySpec querySpec) { return roleRepository.findOne(id); } @Override - public Iterable findAll(QueryParams params) { - return roleRepository.findAll(); + public ResourceList findAll(QuerySpec querySpec) { + return querySpec.apply(roleRepository.findAll()); } @Override - public Iterable findAll(Iterable ids, QueryParams params) { - return roleRepository.findAll(ids); + public ResourceList findAll(Iterable ids, QuerySpec querySpec) { + return querySpec.apply(roleRepository.findAll(ids)); } @Override @@ -38,4 +40,14 @@ public class RoleResourceRepository implements ResourceRepository { roleRepository.delete(id); } + @Override + public Class getResourceClass() { + return Role.class; + } + + @Override + public S create(S entity) { + return save(entity); + } + } diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserResourceRepository.java b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserResourceRepository.java index a36c3c3c0a..9b3de31601 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserResourceRepository.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserResourceRepository.java @@ -1,7 +1,8 @@ package org.baeldung.persistence.katharsis; -import io.katharsis.legacy.queryParams.QueryParams; -import io.katharsis.legacy.repository.ResourceRepository; +import io.katharsis.queryspec.QuerySpec; +import io.katharsis.repository.ResourceRepositoryV2; +import io.katharsis.resource.list.ResourceList; import org.baeldung.persistence.dao.UserRepository; import org.baeldung.persistence.model.User; @@ -9,24 +10,24 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component -public class UserResourceRepository implements ResourceRepository { +public class UserResourceRepository implements ResourceRepositoryV2 { @Autowired private UserRepository userRepository; @Override - public User findOne(Long id, QueryParams params) { + public User findOne(Long id, QuerySpec querySpec) { return userRepository.findOne(id); } @Override - public Iterable findAll(QueryParams params) { - return userRepository.findAll(); + public ResourceList findAll(QuerySpec querySpec) { + return querySpec.apply(userRepository.findAll()); } @Override - public Iterable findAll(Iterable ids, QueryParams params) { - return userRepository.findAll(ids); + public ResourceList findAll(Iterable ids, QuerySpec querySpec) { + return querySpec.apply(userRepository.findAll(ids)); } @Override @@ -39,4 +40,14 @@ public class UserResourceRepository implements ResourceRepository { userRepository.delete(id); } + @Override + public Class getResourceClass() { + return User.class; + } + + @Override + public S create(S entity) { + return save(entity); + } + } diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java index 19007a285f..dbeb769fac 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java @@ -1,7 +1,8 @@ package org.baeldung.persistence.katharsis; -import io.katharsis.legacy.queryParams.QueryParams; -import io.katharsis.legacy.repository.RelationshipRepository; +import io.katharsis.queryspec.QuerySpec; +import io.katharsis.repository.RelationshipRepositoryV2; +import io.katharsis.resource.list.ResourceList; import java.util.HashSet; import java.util.Set; @@ -14,7 +15,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component -public class UserToRoleRelationshipRepository implements RelationshipRepository { +public class UserToRoleRelationshipRepository implements RelationshipRepositoryV2 { @Autowired private UserRepository userRepository; @@ -52,14 +53,25 @@ public class UserToRoleRelationshipRepository implements RelationshipRepository< } @Override - public Role findOneTarget(Long sourceId, String fieldName, QueryParams QueryParams) { + public Role findOneTarget(Long sourceId, String fieldName, QuerySpec querySpec) { // not for many-to-many return null; } @Override - public Iterable findManyTargets(Long sourceId, String fieldName, QueryParams QueryParams) { + public ResourceList findManyTargets(Long sourceId, String fieldName, QuerySpec querySpec) { final User user = userRepository.findOne(sourceId); - return user.getRoles(); + return querySpec.apply(user.getRoles()); } + + @Override + public Class getSourceResourceClass() { + return User.class; + } + + @Override + public Class getTargetResourceClass() { + return Role.class; + } + } diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/model/Role.java b/spring-katharsis/src/main/java/org/baeldung/persistence/model/Role.java index fcaf40ac2c..f391efd37c 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/model/Role.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/model/Role.java @@ -1,8 +1,8 @@ package org.baeldung.persistence.model; import io.katharsis.resource.annotations.JsonApiId; +import io.katharsis.resource.annotations.JsonApiRelation; import io.katharsis.resource.annotations.JsonApiResource; -import io.katharsis.resource.annotations.JsonApiToMany; import java.util.Set; @@ -25,7 +25,7 @@ public class Role { private String name; @ManyToMany(mappedBy = "roles") - @JsonApiToMany + @JsonApiRelation private Set users; // @@ -66,23 +66,30 @@ public class Role { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } final Role other = (Role) obj; if (id == null) { - if (other.id != null) + if (other.id != null) { return false; - } else if (!id.equals(other.id)) + } + } else if (!id.equals(other.id)) { return false; + } if (name == null) { - if (other.name != null) + if (other.name != null) { return false; - } else if (!name.equals(other.name)) + } + } else if (!name.equals(other.name)) { return false; + } return true; } diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java b/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java index 58a92002c8..7c55e29599 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java @@ -1,9 +1,9 @@ package org.baeldung.persistence.model; import io.katharsis.resource.annotations.JsonApiId; -import io.katharsis.resource.annotations.JsonApiIncludeByDefault; +import io.katharsis.resource.annotations.JsonApiRelation; import io.katharsis.resource.annotations.JsonApiResource; -import io.katharsis.resource.annotations.JsonApiToMany; +import io.katharsis.resource.annotations.SerializeType; import java.util.Set; @@ -31,8 +31,7 @@ public class User { @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) - @JsonApiToMany - @JsonApiIncludeByDefault + @JsonApiRelation(serialize=SerializeType.EAGER) private Set roles; public User() { @@ -87,15 +86,19 @@ public class User { @Override public boolean equals(final Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } final User user = (User) obj; - if (!email.equals(user.email)) + if (!email.equals(user.email)) { return false; + } return true; } diff --git a/spring-katharsis/src/main/resources/application.properties b/spring-katharsis/src/main/resources/application.properties index b55fdbba03..120b3c62ee 100644 --- a/spring-katharsis/src/main/resources/application.properties +++ b/spring-katharsis/src/main/resources/application.properties @@ -6,4 +6,7 @@ spring.jpa.hibernate.ddl-auto = create-drop spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect server.port=8082 -server.context-path=/spring-katharsis \ No newline at end of file +server.context-path=/spring-katharsis + +katharsis.domainName=http://localhost:8082/spring-katharsis +katharsis.pathPrefix=/ \ No newline at end of file diff --git a/spring-katharsis/src/main/resources/logback.xml b/spring-katharsis/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-katharsis/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-ldap/pom.xml b/spring-ldap/pom.xml index 2f806e89f8..3b2525d899 100644 --- a/spring-ldap/pom.xml +++ b/spring-ldap/pom.xml @@ -1,8 +1,7 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - spring-ldap 0.1-SNAPSHOT jar @@ -13,17 +12,6 @@ 1.0.0-SNAPSHOT - - 2.3.1.RELEASE - 4.3.6.RELEASE - 1.5.5 - 0.9.15 - - - - spring-ldap - - @@ -101,15 +89,20 @@ org.springframework.data spring-data-ldap - 1.0.6.RELEASE + ${spring-data-ldap.version} org.springframework.data spring-data-jpa - 1.11.6.RELEASE + ${spring-data-jpa.version} + + spring-ldap + + + live @@ -118,6 +111,7 @@ org.apache.maven.plugins maven-surefire-plugin + ${maven-surefire-plugin.version} integration-test @@ -127,6 +121,7 @@ **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java @@ -139,4 +134,14 @@ + + + 2.3.1.RELEASE + 4.3.6.RELEASE + 1.5.5 + 0.9.15 + 1.0.6.RELEASE + 1.11.6.RELEASE + + \ No newline at end of file diff --git a/spring-ldap/src/main/resources/logback.xml b/spring-ldap/src/main/resources/logback.xml index 32b78577ee..7bd5154680 100644 --- a/spring-ldap/src/main/resources/logback.xml +++ b/spring-ldap/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-mobile/pom.xml b/spring-mobile/pom.xml index 6916bb9320..d65820594f 100644 --- a/spring-mobile/pom.xml +++ b/spring-mobile/pom.xml @@ -1,6 +1,6 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 com.baeldung @@ -11,10 +11,10 @@ http://maven.apache.org - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-mobile/src/main/resources/logback.xml b/spring-mobile/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-mobile/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-mockito/README.md b/spring-mockito/README.md index 3ced7161fa..969954c15e 100644 --- a/spring-mockito/README.md +++ b/spring-mockito/README.md @@ -5,3 +5,4 @@ ### Relevant Articles: - [Injecting Mockito Mocks into Spring Beans](http://www.baeldung.com/injecting-mocks-in-spring) +- [Mockito ArgumentMatchers](http://www.baeldung.com/mockito-argument-matchers) diff --git a/spring-mockito/pom.xml b/spring-mockito/pom.xml index 63a5521c98..d1fa7f410e 100644 --- a/spring-mockito/pom.xml +++ b/spring-mockito/pom.xml @@ -1,37 +1,36 @@ + 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-mockito 0.0.1-SNAPSHOT jar - spring-mockito Injecting Mockito Mocks into Spring Beans - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 org.springframework.boot - spring-boot-starter + spring-boot-starter-web org.mockito - mockito-all + mockito-core ${mockito.version} - 1.10.19 + 2.21.0 diff --git a/spring-mockito/src/main/java/com/baeldung/app/api/Flower.java b/spring-mockito/src/main/java/com/baeldung/app/api/Flower.java new file mode 100644 index 0000000000..dc1c36e3ff --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/app/api/Flower.java @@ -0,0 +1,28 @@ +package com.baeldung.app.api; + +public class Flower { + + private String name; + private Integer petals; + + public Flower(String name, Integer petals) { + this.name = name; + this.petals = petals; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getPetals() { + return petals; + } + + public void setPetals(Integer petals) { + this.petals = petals; + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/app/api/MessageApi.java b/spring-mockito/src/main/java/com/baeldung/app/api/MessageApi.java new file mode 100644 index 0000000000..edbe5a1d5a --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/app/api/MessageApi.java @@ -0,0 +1,31 @@ +package com.baeldung.app.api; + +public class MessageApi { + private String from; + private String to; + private String text; + + public String getFrom() { + return from; + } + + public void setFrom(String from) { + this.from = from; + } + + public String getTo() { + return to; + } + + public void setTo(String to) { + this.to = to; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/app/rest/FlowerController.java b/spring-mockito/src/main/java/com/baeldung/app/rest/FlowerController.java new file mode 100644 index 0000000000..b3d8888cec --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/app/rest/FlowerController.java @@ -0,0 +1,27 @@ +package com.baeldung.app.rest; + +import com.baeldung.app.api.Flower; +import com.baeldung.domain.service.FlowerService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping("/flowers") +public class FlowerController { + + @Autowired + private FlowerService flowerService; + + @PostMapping("/isAFlower") + public String isAFlower (@RequestBody String flower) { + return flowerService.analize(flower); + } + + @PostMapping("/isABigFlower") + public Boolean isABigFlower (@RequestBody Flower flower) { + return flowerService.isABigFlower(flower.getName(), flower.getPetals()); + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/app/rest/MessageController.java b/spring-mockito/src/main/java/com/baeldung/app/rest/MessageController.java new file mode 100644 index 0000000000..e23c2e7607 --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/app/rest/MessageController.java @@ -0,0 +1,34 @@ +package com.baeldung.app.rest; + +import com.baeldung.app.api.MessageApi; +import com.baeldung.domain.model.Message; +import com.baeldung.domain.service.MessageService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; + +import java.time.Instant; +import java.util.Date; +import java.util.UUID; + +@Controller +@RequestMapping("/message") +public class MessageController { + + @Autowired + private MessageService messageService; + + @PostMapping + public Message createMessage (@RequestBody MessageApi messageDTO) { + Message message = new Message(); + message.setText(messageDTO.getText()); + message.setFrom(messageDTO.getFrom()); + message.setTo(messageDTO.getTo()); + message.setDate(Date.from(Instant.now())); + message.setId(UUID.randomUUID()); + + return messageService.deliverMessage(message); + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/domain/model/Message.java b/spring-mockito/src/main/java/com/baeldung/domain/model/Message.java new file mode 100644 index 0000000000..a516d5619b --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/domain/model/Message.java @@ -0,0 +1,53 @@ +package com.baeldung.domain.model; + +import java.util.Date; +import java.util.UUID; + +public class Message { + + private String from; + private String to; + private String text; + private Date date; + private UUID id; + + public String getFrom() { + return from; + } + + public void setFrom(String from) { + this.from = from; + } + + public String getTo() { + return to; + } + + public void setTo(String to) { + this.to = to; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/domain/service/FlowerService.java b/spring-mockito/src/main/java/com/baeldung/domain/service/FlowerService.java new file mode 100644 index 0000000000..3c76cb5d76 --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/domain/service/FlowerService.java @@ -0,0 +1,28 @@ +package com.baeldung.domain.service; + +import org.springframework.stereotype.Service; + +import java.util.Arrays; +import java.util.List; + +@Service +public class FlowerService { + + private List flowers = Arrays.asList("Poppy", "Ageratum", "Carnation", "Diascia", "Lantana"); + + public String analize(String name) { + if(flowers.contains(name)) { + return "flower"; + } + return null; + } + + public boolean isABigFlower(String name, int petals) { + if(flowers.contains(name)) { + if(petals > 10) { + return true; + } + } + return false; + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/domain/service/MessageService.java b/spring-mockito/src/main/java/com/baeldung/domain/service/MessageService.java new file mode 100644 index 0000000000..d156c59571 --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/domain/service/MessageService.java @@ -0,0 +1,13 @@ +package com.baeldung.domain.service; + +import com.baeldung.domain.model.Message; +import org.springframework.stereotype.Service; + +@Service +public class MessageService { + + public Message deliverMessage (Message message) { + + return message; + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/domain/util/MessageMatcher.java b/spring-mockito/src/main/java/com/baeldung/domain/util/MessageMatcher.java new file mode 100644 index 0000000000..51db07fde7 --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/domain/util/MessageMatcher.java @@ -0,0 +1,22 @@ +package com.baeldung.domain.util; + +import com.baeldung.domain.model.Message; +import org.mockito.ArgumentMatcher; + +public class MessageMatcher implements ArgumentMatcher { + + private Message left; + + public MessageMatcher(Message message) { + this.left = message; + } + + @Override + public boolean matches(Message right) { + return left.getFrom().equals(right.getFrom()) && + left.getTo().equals(right.getTo()) && + left.getText().equals(right.getText()) && + right.getDate() != null && + right.getId() != null; + } +} \ No newline at end of file diff --git a/spring-mockito/src/main/resources/logback.xml b/spring-mockito/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-mockito/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationTest.java b/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationTest.java deleted file mode 100644 index d70f916b12..0000000000 --- a/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@ActiveProfiles("test") -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = MocksApplication.class) -public class UserServiceIntegrationTest { - - @Autowired - private UserService userService; - - @Autowired - private NameService nameService; - - @Test - public void whenUserIdIsProvided_thenRetrievedNameIsCorrect() { - Mockito.when(nameService.getUserName("SomeId")).thenReturn("Mock user name"); - - String testName = userService.getUserName("SomeId"); - - Assert.assertEquals("Mock user name", testName); - } -} \ No newline at end of file diff --git a/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationUnitTest.java b/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationUnitTest.java new file mode 100644 index 0000000000..573a37a9a4 --- /dev/null +++ b/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@ActiveProfiles("test") +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = MocksApplication.class) +public class UserServiceIntegrationUnitTest { + + @Autowired + private UserService userService; + + @Autowired + private NameService nameService; + + @Test + public void whenUserIdIsProvided_thenRetrievedNameIsCorrect() { + Mockito.when(nameService.getUserName("SomeId")).thenReturn("Mock user name"); + + String testName = userService.getUserName("SomeId"); + + Assert.assertEquals("Mock user name", testName); + } +} \ No newline at end of file diff --git a/spring-mockito/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java b/spring-mockito/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java new file mode 100644 index 0000000000..f30af140af --- /dev/null +++ b/spring-mockito/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.app.rest; + +import com.baeldung.app.api.Flower; +import com.baeldung.domain.service.FlowerService; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.mockito.Matchers.anyInt; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class FlowerControllerUnitTest { + + @Mock + private FlowerService flowerService; + + @InjectMocks + private FlowerController flowerController; + + @Test + public void isAFlower_withMockito_OK() { + when(flowerService.analize(eq("violetta"))).thenReturn("Flower"); + + String response = flowerController.isAFlower("violetta"); + + Assert.assertEquals("Flower", response); + } + + @Test + public void isABigFlower_withMockito_OK() { + when(flowerService.isABigFlower(eq("violetta"), anyInt())).thenReturn(true); + + Flower flower = new Flower("violetta", 15); + + Boolean response = flowerController.isABigFlower(flower); + + Assert.assertTrue(response); + } +} diff --git a/spring-mockito/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java b/spring-mockito/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java new file mode 100644 index 0000000000..e303c85caf --- /dev/null +++ b/spring-mockito/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.app.rest; + +import com.baeldung.app.api.MessageApi; +import com.baeldung.domain.model.Message; +import com.baeldung.domain.service.MessageService; +import com.baeldung.domain.util.MessageMatcher; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.mockito.Mockito.times; + +@RunWith(MockitoJUnitRunner.class) +public class MessageControllerUnitTest { + + @Mock + private MessageService messageService; + + @InjectMocks + private MessageController messageController; + + @Test + public void createMessage_NewMessage_OK() { + MessageApi messageApi = new MessageApi(); + messageApi.setFrom("me"); + messageApi.setTo("you"); + messageApi.setText("Hello, you!"); + + messageController.createMessage(messageApi); + + Message message = new Message(); + message.setFrom("me"); + message.setTo("you"); + message.setText("Hello, you!"); + + Mockito.verify(messageService, times(1)).deliverMessage(Matchers.argThat(new MessageMatcher(message))); + } +} diff --git a/spring-mustache/pom.xml b/spring-mustache/pom.xml index 45fee6b10e..4e7a1ba5a3 100644 --- a/spring-mustache/pom.xml +++ b/spring-mustache/pom.xml @@ -7,24 +7,16 @@ spring-mustache 0.0.1-SNAPSHOT jar - spring-mustache Demo project for Spring Boot - org.springframework.boot - spring-boot-starter-parent - 1.5.4.RELEASE - - + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-1 - - UTF-8 - UTF-8 - 1.8 - - org.springframework.boot @@ -39,12 +31,12 @@ org.webjars bootstrap - 3.3.7 + ${bootstrap.version} org.fluttercode.datafactory datafactory - 0.8 + ${datafactory.version} @@ -57,5 +49,12 @@ - + + UTF-8 + UTF-8 + 1.8 + 3.3.7 + 0.8 + + diff --git a/spring-mustache/src/main/resources/logback.xml b/spring-mustache/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-mustache/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-email/README.md b/spring-mvc-email/README.md deleted file mode 100644 index aa880188d7..0000000000 --- a/spring-mvc-email/README.md +++ /dev/null @@ -1,17 +0,0 @@ -## Relevant articles: - -- [Guide to Spring Email](http://www.baeldung.com/spring-email) - -## Spring MVC Email - -Example Spring MVC project to send email from web form. - -### Installing and Running - -Just run the Spring Boot application. -Type http://localhost:8080 in your browser to open the application. - - -### Sending test emails - -Follow UI links to send simple email, email using template or email with attachment. diff --git a/spring-mvc-email/pom.xml b/spring-mvc-email/pom.xml deleted file mode 100644 index 436b4155fa..0000000000 --- a/spring-mvc-email/pom.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - 4.0.0 - - org.baeldung.spring - spring-mvc-email - 1.0 - spring-mvc-email - war - - - parent-boot-5 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-5 - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - - org.springframework.boot - spring-boot-starter-mail - - - - javax.servlet - jstl - - - - diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java b/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java deleted file mode 100644 index bc5d6b3151..0000000000 --- a/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.spring; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.support.SpringBootServletInitializer; - - -@SpringBootApplication -public class Application extends SpringBootServletInitializer { - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } -} diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/app/config/AppConfig.java b/spring-mvc-email/src/main/java/com/baeldung/spring/app/config/AppConfig.java deleted file mode 100644 index 9078d44764..0000000000 --- a/spring-mvc-email/src/main/java/com/baeldung/spring/app/config/AppConfig.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.spring.app.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.mail.SimpleMailMessage; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; -import org.springframework.web.servlet.view.UrlBasedViewResolver; - -/** - * Created with IntelliJ IDEA. - * User: Olga - */ -@Configuration -@ComponentScan("com.baeldung.spring") -@EnableWebMvc //tha same as -public class AppConfig extends WebMvcConfigurerAdapter { - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); - } - - @Bean - public UrlBasedViewResolver urlBasedViewResolver() { - UrlBasedViewResolver resolver = new UrlBasedViewResolver(); - resolver.setOrder(0); - resolver.setPrefix("/WEB-INF/views/"); - resolver.setSuffix(".jsp"); - resolver.setCache(false); - resolver.setViewClass(JstlView.class); - return resolver; - } - - @Bean - public InternalResourceViewResolver internalResourceViewResolver() { - InternalResourceViewResolver resolver = new InternalResourceViewResolver(); - resolver.setOrder(1); - resolver.setPrefix("/WEB-INF/views/"); - resolver.setSuffix(".jsp"); - resolver.setViewClass(JstlView.class); - return resolver; - } - - @Bean - public SimpleMailMessage templateSimpleMessage() { - SimpleMailMessage message = new SimpleMailMessage(); - message.setText("This is the test email template for your email:\n%s\n"); - return message; - } -} diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/HomeController.java b/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/HomeController.java deleted file mode 100644 index 656e237a9e..0000000000 --- a/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/HomeController.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.spring.controllers; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -/** - * Created with IntelliJ IDEA. - * User: Olga - */ -@Controller -@RequestMapping({"/","/home"}) -public class HomeController { - - @RequestMapping(method = RequestMethod.GET) - public String showHomePage() { - return "home"; - } -} diff --git a/spring-mvc-email/src/main/resources/META-INF/application.xml b/spring-mvc-email/src/main/resources/META-INF/application.xml deleted file mode 100644 index 759a312bd4..0000000000 --- a/spring-mvc-email/src/main/resources/META-INF/application.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - SpringMVCEmail.war - SpringMVCEmail - - - - - web.war - SpringMVCEmailWeb - - - \ No newline at end of file diff --git a/spring-mvc-email/src/main/resources/application.properties b/spring-mvc-email/src/main/resources/application.properties deleted file mode 100644 index 61a42050e5..0000000000 --- a/spring-mvc-email/src/main/resources/application.properties +++ /dev/null @@ -1,20 +0,0 @@ -# Gmail SMTP -spring.mail.host=smtp.gmail.com -spring.mail.port=587 -spring.mail.username=username -spring.mail.password=password -spring.mail.properties.mail.smtp.auth=true -spring.mail.properties.mail.smtp.starttls.enable=true - -# Amazon SES SMTP -#spring.mail.host=email-smtp.us-west-2.amazonaws.com -#spring.mail.username=username -#spring.mail.password=password -#spring.mail.properties.mail.transport.protocol=smtp -#spring.mail.properties.mail.smtp.port=25 -#spring.mail.properties.mail.smtp.auth=true -#spring.mail.properties.mail.smtp.starttls.enable=true -#spring.mail.properties.mail.smtp.starttls.required=true - -# path to attachment file -attachment.invoice=path_to_file \ No newline at end of file diff --git a/spring-mvc-email/src/main/webapp/WEB-INF/web.xml b/spring-mvc-email/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 4cd41216d9..0000000000 --- a/spring-mvc-email/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - simpleweb - org.springframework.web.servlet.DispatcherServlet - - contextClass - - org.springframework.web.context.support.AnnotationConfigWebApplicationContext - - - - contextConfigLocation - com.baeldung.spring.app.config.AppConfig - - 1 - - - - simpleweb - / - - - diff --git a/spring-mvc-forms-jsp/README.md b/spring-mvc-forms-jsp/README.md index 44786d5ec7..588828c9cf 100644 --- a/spring-mvc-forms-jsp/README.md +++ b/spring-mvc-forms-jsp/README.md @@ -4,5 +4,4 @@ - [MaxUploadSizeExceededException in Spring](http://www.baeldung.com/spring-maxuploadsizeexceeded) - [Getting Started with Forms in Spring MVC](http://www.baeldung.com/spring-mvc-form-tutorial) - [Form Validation with AngularJS and Spring MVC](http://www.baeldung.com/validation-angularjs-spring-mvc) -- [Guide to JSTL](http://www.baeldung.com/guide-to-jstl) - [A Guide to the JSTL Library](http://www.baeldung.com/jstl) diff --git a/spring-mvc-forms-jsp/pom.xml b/spring-mvc-forms-jsp/pom.xml index 359e186f52..6c75c9299b 100644 --- a/spring-mvc-forms-jsp/pom.xml +++ b/spring-mvc-forms-jsp/pom.xml @@ -1,27 +1,26 @@ - + 4.0.0 com.baeldung 0.1-SNAPSHOT spring-mvc-forms-jsp - spring-mvc-forms-jsp war com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 org.springframework spring-webmvc - ${springframework.version} + ${spring.version} commons-logging @@ -29,51 +28,43 @@ - javax.servlet javax.servlet-api ${javax.servlet-api.version} - javax.servlet.jsp javax.servlet.jsp-api ${javax.servlet.jsp-api.version} - javax.servlet jstl ${jstl.version} - mysql mysql-connector-java - 6.0.6 + ${mysql-connector-java.version} - org.hibernate hibernate-validator ${hibernate-validator.version} - commons-fileupload commons-fileupload ${fileupload.version} - com.fasterxml.jackson.core jackson-databind - ${jackson.version} + ${jackson-databind.version} - - + @@ -84,7 +75,6 @@ - org.apache.maven.plugins maven-war-plugin @@ -93,10 +83,8 @@ src/main/webapp spring-mvc-forms false - ${deploy-path} - spring-mvc-forms @@ -104,26 +92,15 @@ - - - 1 - jstl - https://mvnrepository.com/artifact/javax.servlet/jstl - - - - 4.3.7.RELEASE 2.6 1.2 2.3.1 3.1.0 - 5.4.0.Final - server default deploy directory - 1.3.2 - 2.8.7 + 6.0.10.Final + 1.3.3 5.2.5.Final - 5.1.40 + 6.0.6 diff --git a/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java b/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java index 93fab9caf8..b8b36df84e 100644 --- a/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java +++ b/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java @@ -8,14 +8,13 @@ import org.springframework.web.multipart.MultipartResolver; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc @ComponentScan(basePackages = {"com.baeldung.springmvcforms", "com.baeldung.jstl"}) -class ApplicationConfiguration extends WebMvcConfigurerAdapter { +class ApplicationConfiguration implements WebMvcConfigurer { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { diff --git a/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/User.java b/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/User.java index 49f006f422..9e0e7c99be 100644 --- a/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/User.java +++ b/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/User.java @@ -1,13 +1,12 @@ package com.baeldung.springmvcforms.domain; import javax.validation.constraints.Digits; +import javax.validation.constraints.Email; import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; -import org.hibernate.validator.constraints.Email; -import org.hibernate.validator.constraints.NotBlank; - public class User { @NotNull diff --git a/spring-mvc-forms-jsp/src/main/resources/logback.xml b/spring-mvc-forms-jsp/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-mvc-forms-jsp/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-forms-thymeleaf/README.md b/spring-mvc-forms-thymeleaf/README.md index 450b10433c..f0f7e35a98 100644 --- a/spring-mvc-forms-thymeleaf/README.md +++ b/spring-mvc-forms-thymeleaf/README.md @@ -1,3 +1,4 @@ ### Relevant articles - [Session Attributes in Spring MVC](http://www.baeldung.com/spring-mvc-session-attributes) +- [Binding a List in Thymeleaf](http://www.baeldung.com/thymeleaf-list) diff --git a/spring-mvc-forms-thymeleaf/pom.xml b/spring-mvc-forms-thymeleaf/pom.xml index 408e7643d2..504ad1dcb2 100644 --- a/spring-mvc-forms-thymeleaf/pom.xml +++ b/spring-mvc-forms-thymeleaf/pom.xml @@ -1,21 +1,18 @@ + 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-mvc-forms-thymeleaf - 0.0.1-SNAPSHOT jar - spring-mvc-forms-thymeleaf spring forms examples using thymeleaf - org.springframework.boot - spring-boot-starter-parent - 2.0.0.RELEASE - + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 @@ -41,34 +38,8 @@ - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - methods - true - - **/*IntegrationTest.java - **/*LiveTest.java - - - - - - - UTF-8 - UTF-8 3.0.9.RELEASE + com.baeldung.sessionattrs.SessionAttrsApplication - diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Book.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Book.java new file mode 100644 index 0000000000..823ff436fb --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Book.java @@ -0,0 +1,73 @@ +package com.baeldung.listbindingexample; + +public class Book { + + private long id; + + private String title; + + private String author; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((author == null) ? 0 : author.hashCode()); + result = prime * result + (int) (id ^ (id >>> 32)); + result = prime * result + ((title == null) ? 0 : title.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; + Book other = (Book) obj; + if (author == null) { + if (other.author != null) + return false; + } else if (!author.equals(other.author)) + return false; + if (id != other.id) + return false; + if (title == null) { + if (other.title != null) + return false; + } else if (!title.equals(other.title)) + return false; + return true; + } + + @Override + public String toString() { + return "Book [id=" + id + ", title=" + title + ", author=" + author + "]"; + } +} diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BookService.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BookService.java new file mode 100644 index 0000000000..c72d8fe70d --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BookService.java @@ -0,0 +1,10 @@ +package com.baeldung.listbindingexample; + +import java.util.List; + +public interface BookService { + + List findAll(); + + void saveAll(List books); +} diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BooksCreationDto.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BooksCreationDto.java new file mode 100644 index 0000000000..a25418815b --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BooksCreationDto.java @@ -0,0 +1,29 @@ +package com.baeldung.listbindingexample; + +import java.util.ArrayList; +import java.util.List; + +public class BooksCreationDto { + + private List books; + + public BooksCreationDto() { + this.books = new ArrayList<>(); + } + + public BooksCreationDto(List books) { + this.books = books; + } + + public List getBooks() { + return books; + } + + public void setBooks(List books) { + this.books = books; + } + + public void addBook(Book book) { + this.books.add(book); + } +} diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Config.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Config.java new file mode 100644 index 0000000000..00e1a0393e --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Config.java @@ -0,0 +1,33 @@ +package com.baeldung.listbindingexample; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; +import org.thymeleaf.templateresolver.ITemplateResolver; + +@EnableWebMvc +@Configuration +public class Config implements WebMvcConfigurer { + + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/") + .setViewName("index"); + registry.setOrder(Ordered.HIGHEST_PRECEDENCE); + } + + @Bean + public ITemplateResolver templateResolver() { + ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver(); + resolver.setPrefix("templates/books/"); + resolver.setSuffix(".html"); + resolver.setTemplateMode(TemplateMode.HTML); + resolver.setCharacterEncoding("UTF-8"); + return resolver; + } +} diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/InMemoryBookService.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/InMemoryBookService.java new file mode 100644 index 0000000000..b35522a3ee --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/InMemoryBookService.java @@ -0,0 +1,44 @@ +package com.baeldung.listbindingexample; + +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +@Service +public class InMemoryBookService implements BookService { + + static Map booksDB = new HashMap<>(); + + @Override + public List findAll() { + return new ArrayList<>(booksDB.values()); + } + + @Override + public void saveAll(List books) { + long nextId = getNextId(); + for (Book book : books) { + if (book.getId() == 0) { + book.setId(nextId++); + } + } + + Map bookMap = books.stream() + .collect(Collectors.toMap(Book::getId, Function.identity())); + + booksDB.putAll(bookMap); + } + + private Long getNextId() { + return booksDB.keySet() + .stream() + .mapToLong(value -> value) + .max() + .orElse(0) + 1; + } +} diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/ListBindingApplication.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/ListBindingApplication.java new file mode 100644 index 0000000000..261954fcff --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/ListBindingApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.listbindingexample; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; + +@SpringBootApplication(exclude = { SecurityAutoConfiguration.class, DataSourceAutoConfiguration.class }) +public class ListBindingApplication { + + public static void main(String[] args) { + SpringApplication.run(ListBindingApplication.class, args); + } +} diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/MultipleBooksController.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/MultipleBooksController.java new file mode 100644 index 0000000000..1ed44778c6 --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/MultipleBooksController.java @@ -0,0 +1,61 @@ +package com.baeldung.listbindingexample; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +import java.util.ArrayList; +import java.util.List; + +@Controller +@RequestMapping("/books") +public class MultipleBooksController { + + @Autowired + private BookService bookService; + + @GetMapping(value = "/all") + public String showAll(Model model) { + model.addAttribute("books", bookService.findAll()); + + return "allBooks"; + } + + @GetMapping(value = "/create") + public String showCreateForm(Model model) { + BooksCreationDto booksForm = new BooksCreationDto(); + + for (int i = 1; i <= 3; i++) { + booksForm.addBook(new Book()); + } + + model.addAttribute("form", booksForm); + + return "createBooksForm"; + } + + @GetMapping(value = "/edit") + public String showEditForm(Model model) { + List books = new ArrayList<>(); + bookService.findAll() + .iterator() + .forEachRemaining(books::add); + + model.addAttribute("form", new BooksCreationDto(books)); + + return "editBooksForm"; + } + + @PostMapping(value = "/save") + public String saveBooks(@ModelAttribute BooksCreationDto form, Model model) { + bookService.saveAll(form.getBooks()); + + model.addAttribute("books", bookService.findAll()); + + return "redirect:/books/all"; + } +} diff --git a/spring-mvc-forms-thymeleaf/src/main/resources/logback.xml b/spring-mvc-forms-thymeleaf/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/allBooks.html b/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/allBooks.html new file mode 100644 index 0000000000..9f75bec8bd --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/allBooks.html @@ -0,0 +1,40 @@ + + + All Books + + + +

    +
    +
    +

    Books

    +
    +
    +
    +
    + + + + + + + + + + + + + + + + +
    Title Author
    No Books Available
    Title Author
    +
    + +
    +
    + + diff --git a/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/createBooksForm.html b/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/createBooksForm.html new file mode 100644 index 0000000000..9f88762882 --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/createBooksForm.html @@ -0,0 +1,45 @@ + + + Add Books + + + +
    +
    +
    +

    Add Books

    +
    +
    +
    +
    + Back to All Books +
    +
    + + + + + + + + + + + + + + + + + +
    Title Author
    +
    +
    +
    +
    +
    + + diff --git a/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/editBooksForm.html b/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/editBooksForm.html new file mode 100644 index 0000000000..9278d98018 --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/editBooksForm.html @@ -0,0 +1,49 @@ + + + Edit Books + + + +
    +
    +
    +

    Add Books

    +
    +
    +
    +
    + Back to All Books +
    +
    + + + + + + + + + + + + + + + + + + + +
    Title Author
    +
    +
    +
    +
    +
    + + diff --git a/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/index.html b/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/index.html new file mode 100644 index 0000000000..59780b84aa --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/index.html @@ -0,0 +1,22 @@ + + + + Binding a List in Thymeleaf + + + + + + + +
    +

    +

    Binding a List in Thymeleaf - Example

    +

    +
    + + + diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 5f62f71211..44b1d65bc8 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -2,7 +2,7 @@ ## Spring MVC with Java Configuration Example Project -###The Course +### The Course The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: @@ -26,4 +26,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [The HttpMediaTypeNotAcceptableException in Spring MVC](http://www.baeldung.com/spring-httpmediatypenotacceptable) - [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) - [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) -- [Spring MVC @PathVariable with a dot (.) gets truncated](http://www.baeldung.com/spring-mvc-pathvariable-dot) \ No newline at end of file +- [Spring MVC @PathVariable with a dot (.) gets truncated](http://www.baeldung.com/spring-mvc-pathvariable-dot) +- [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) +- [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) +- [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index f8d1d32f63..9d3e0ca1b2 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -1,81 +1,58 @@ + 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-mvc-java 0.1-SNAPSHOT spring-mvc-java + war - parent-boot-5 + parent-spring-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-spring-5 - - - org.springframework.boot - spring-boot-starter-thymeleaf + + org.springframework + spring-webmvc + ${spring.version} - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.boot - spring-boot-devtools - - - org.springframework.boot - spring-boot-test - test - - - org.springframework.boot - spring-boot-starter-aop - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-websocket - - - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - javax.servlet javax.servlet-api - ${javax.servlet-api.version} - provided + 4.0.1 + + + javax.servlet.jsp + javax.servlet.jsp-api + 2.3.3 javax.servlet jstl ${jstl.version} - runtime + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-databind.version} org.aspectj aspectjrt - ${aspectj.version} + 1.9.1 org.aspectj aspectjweaver - ${aspectj.version} + 1.9.1 @@ -87,7 +64,7 @@ net.sourceforge.htmlunit htmlunit - ${net.sourceforge.htmlunit} + 2.32 commons-logging @@ -111,12 +88,13 @@ com.jayway.jsonpath json-path - ${jsonpath.version} test + 2.4.0 org.springframework spring-test + ${spring.version} test @@ -129,32 +107,29 @@ - javax.validation - validation-api - 1.1.0.Final - - - org.hibernate + org.hibernate.validator hibernate-validator ${hibernate-validator.version} - - javax.el - javax.el-api - 2.2.4 - - - org.glassfish.web - javax.el - 2.2.4 - com.google.code.gson gson + 2.8.5 + + org.springframework + spring-websocket + ${spring.version} + + + + org.springframework + spring-messaging + ${spring.version} + @@ -223,6 +198,7 @@ **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java @@ -266,18 +242,14 @@ - - 2.1.5.RELEASE - 2.9.4 + 3.0.9.RELEASE - 5.2.5.Final + 6.0.10.Final 5.1.40 - 5.4.1.Final - 3.1.0 - 1.2 + 6.0.10.Final 19.0 @@ -292,15 +264,19 @@ 2.23 - 2.6 + 3.2.2 2.7 1.6.1 + 3.1.0 - 1.8.9 + 1.9.1 3.16-beta1 + + 3.0.1-b06 + diff --git a/spring-mvc-java/src/main/java/com/baeldung/app/Application.java b/spring-mvc-java/src/main/java/com/baeldung/app/Application.java deleted file mode 100644 index 301caffca9..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/app/Application.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.app; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.support.SpringBootServletInitializer; -import org.springframework.context.annotation.ComponentScan; - -@EnableAutoConfiguration -@ComponentScan(value = {"com.baeldung.web.controller"}, resourcePattern = "**/FileUploadController.class") -@SpringBootApplication -public class Application extends SpringBootServletInitializer { - - public static void main(final String[] args) { - SpringApplication.run(Application.class, args); - } -} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/config/AppInitializer.java b/spring-mvc-java/src/main/java/com/baeldung/config/AppInitializer.java index 9cf6e384f1..eec12f466f 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/config/AppInitializer.java +++ b/spring-mvc-java/src/main/java/com/baeldung/config/AppInitializer.java @@ -14,13 +14,20 @@ public class AppInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext container) throws ServletException { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); - context.setConfigLocation("org.baeldung.config"); + + context.scan("com.baeldung"); container.addListener(new ContextLoaderListener(context)); - ServletRegistration.Dynamic dispatcher = container.addServlet("java-servlet", new DispatcherServlet(context)); + ServletRegistration.Dynamic dispatcher = container.addServlet("mvc", new DispatcherServlet(context)); dispatcher.setLoadOnStartup(1); - dispatcher.addMapping("/java-servlet/*"); + dispatcher.addMapping("/"); + + // final MultipartConfigElement multipartConfigElement = new + // MultipartConfigElement(TMP_FOLDER, MAX_UPLOAD_SIZE, + // MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2); + // + // appServlet.setMultipartConfig(multipartConfigElement); } } diff --git a/spring-mvc-java/src/main/java/com/baeldung/dialect/CustomDialect.java b/spring-mvc-java/src/main/java/com/baeldung/dialect/CustomDialect.java deleted file mode 100644 index 0c6a7c3ae0..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/dialect/CustomDialect.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.dialect; - -import java.util.HashSet; -import java.util.Set; - -import com.baeldung.processor.NameProcessor; -import org.thymeleaf.dialect.AbstractDialect; -import org.thymeleaf.processor.IProcessor; - -public class CustomDialect extends AbstractDialect { - - @Override - public String getPrefix() { - return "custom"; - } - - @Override - public Set getProcessors() { - final Set processors = new HashSet(); - processors.add(new NameProcessor()); - return processors; - } - -} diff --git a/spring-mvc-java/src/main/java/com/baeldung/processor/NameProcessor.java b/spring-mvc-java/src/main/java/com/baeldung/processor/NameProcessor.java deleted file mode 100644 index 9a7857198c..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/processor/NameProcessor.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.processor; - -import org.thymeleaf.Arguments; -import org.thymeleaf.dom.Element; -import org.thymeleaf.processor.attr.AbstractTextChildModifierAttrProcessor; - -public class NameProcessor extends AbstractTextChildModifierAttrProcessor { - - public NameProcessor() { - super("name"); - } - - @Override - protected String getText(final Arguments arguements, final Element elements, final String attributeName) { - return "Hello, " + elements.getAttributeValue(attributeName) + "!"; - } - - @Override - public int getPrecedence() { - return 1000; - } - -} diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ApplicationConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ApplicationConfig.java deleted file mode 100644 index 261d5793dc..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ApplicationConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.spring.web.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; - -@EnableWebMvc -@Configuration -@ComponentScan(basePackages = { "com.baeldung.web.controller" }) -public class ApplicationConfig extends WebMvcConfigurerAdapter { - - public ApplicationConfig() { - super(); - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/").setViewName("index"); - } - - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/jsp/"); - bean.setSuffix(".jsp"); - return bean; - } -} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java deleted file mode 100644 index 1b30479685..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.baeldung.spring.web.config; - -import java.util.HashSet; -import java.util.Set; - -import com.baeldung.dialect.CustomDialect; -import org.springframework.context.MessageSource; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Description; -import org.springframework.context.support.ResourceBundleMessageSource; -import org.springframework.web.servlet.ViewResolver; -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; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; -import org.thymeleaf.dialect.IDialect; -import org.thymeleaf.spring4.SpringTemplateEngine; -import org.thymeleaf.spring4.view.ThymeleafViewResolver; -import org.thymeleaf.templateresolver.ServletContextTemplateResolver; - -@EnableWebMvc -@Configuration -public class ClientWebConfig extends WebMvcConfigurerAdapter { - - public ClientWebConfig() { - super(); - } - - // API - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - - registry.addViewController("/sample.html"); - } - - @Bean - public ViewResolver thymeleafViewResolver() { - final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); - viewResolver.setTemplateEngine(templateEngine()); - viewResolver.setOrder(1); - return viewResolver; - } - - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - bean.setOrder(0); - return bean; - } - - @Bean - @Description("Thymeleaf template resolver serving HTML 5") - public ServletContextTemplateResolver templateResolver() { - final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); - templateResolver.setPrefix("/WEB-INF/templates/"); - templateResolver.setSuffix(".html"); - templateResolver.setTemplateMode("HTML5"); - return templateResolver; - } - - @Bean - @Description("Thymeleaf template engine with Spring integration") - public SpringTemplateEngine templateEngine() { - final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); - templateEngine.setTemplateResolver(templateResolver()); - final Set dialects = new HashSet<>(); - dialects.add(new CustomDialect()); - templateEngine.setAdditionalDialects(dialects); - return templateEngine; - } - - @Bean - @Description("Spring message resolver") - public MessageSource messageSource() { - final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); - messageSource.setBasename("messages"); - return messageSource; - } - - @Override - public void addResourceHandlers(final ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); - } - -} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ContentManagementWebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ContentManagementWebConfig.java deleted file mode 100644 index 498105ded1..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ContentManagementWebConfig.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.spring.web.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.MediaType; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; - -@EnableWebMvc -@Configuration -public class ContentManagementWebConfig extends WebMvcConfigurerAdapter { - - public ContentManagementWebConfig() { - super(); - } - - // API - - @Override - public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { - configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true).useJaf(false).defaultContentType(MediaType.APPLICATION_JSON).mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", - MediaType.APPLICATION_JSON); - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/sample.html"); - } - - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - bean.setOrder(0); - return bean; - } - -} diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java deleted file mode 100644 index 80ce22edd6..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.spring.web.config; - -import org.springframework.web.WebApplicationInitializer; -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.context.support.GenericWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; -import java.util.Set; - -public class MainWebAppInitializer implements WebApplicationInitializer { - - private static final String TMP_FOLDER = "/tmp"; - private static final int MAX_UPLOAD_SIZE = 5 * 1024 * 1024; // 5 MB - - /** - * Register and configure all Servlet container components necessary to power the web application. - */ - @Override - public void onStartup(final ServletContext sc) throws ServletException { - - // Create the 'root' Spring application context - final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); - root.scan("com.baeldung.spring.web.config"); - // root.getEnvironment().setDefaultProfiles("embedded"); - - sc.addListener(new ContextLoaderListener(root)); - - // Handles requests into the application - final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext())); - appServlet.setLoadOnStartup(1); - - // final MultipartConfigElement multipartConfigElement = new - // MultipartConfigElement(TMP_FOLDER, MAX_UPLOAD_SIZE, - // MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2); - // - // appServlet.setMultipartConfig(multipartConfigElement); - - final Set mappingConflicts = appServlet.addMapping("/"); - if (!mappingConflicts.isEmpty()) { - throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278"); - } - } - -} diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 11be08a79d..191d721dfb 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -3,40 +3,105 @@ package com.baeldung.spring.web.config; import java.util.ArrayList; import java.util.List; +import javax.servlet.ServletContext; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Description; +import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.core.io.ClassPathResource; import org.springframework.http.MediaType; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; import org.springframework.web.servlet.view.ResourceBundleViewResolver; import org.springframework.web.servlet.view.XmlViewResolver; import org.springframework.web.util.UrlPathHelper; -import com.baeldung.excel.*; +import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.view.ThymeleafViewResolver; +import org.thymeleaf.templateresolver.ServletContextTemplateResolver; + +import com.baeldung.excel.ExcelPOIHelper; -@Configuration @EnableWebMvc -@ComponentScan("com.baeldung.web") -public class WebConfig extends WebMvcConfigurerAdapter { +@Configuration +@ComponentScan(basePackages = { "com.baeldung.web.controller" }) +public class WebConfig implements WebMvcConfigurer { - public WebConfig() { - super(); + @Autowired + private ServletContext ctx; + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("index"); + } + + @Bean + public ViewResolver thymeleafViewResolver() { + final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + viewResolver.setOrder(1); + return viewResolver; } - // @Bean - // public StandardServletMultipartResolver multipartResolver() { - // return new StandardServletMultipartResolver(); - // } + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + bean.setOrder(0); + return bean; + } + @Bean + @Description("Thymeleaf template resolver serving HTML 5") + public ServletContextTemplateResolver templateResolver() { + final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(ctx); + templateResolver.setPrefix("/WEB-INF/templates/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); + return templateResolver; + } + + @Bean + @Description("Thymeleaf template engine with Spring integration") + public SpringTemplateEngine templateEngine() { + final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(templateResolver()); + return templateEngine; + } + + @Bean + @Description("Spring message resolver") + public MessageSource messageSource() { + final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setBasename("messages"); + return messageSource; + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } + + @Override + public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { + configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true).useRegisteredExtensionsOnly(false).defaultContentType(MediaType.APPLICATION_JSON).mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", + MediaType.APPLICATION_JSON); + } @Bean(name = "multipartResolver") public CommonsMultipartResolver multipartResolver() { @@ -45,23 +110,7 @@ public class WebConfig extends WebMvcConfigurerAdapter { return multipartResolver; } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/sample.html"); - } - - @Bean - public ViewResolver internalResourceViewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - bean.setOrder(2); - return bean; - } - + @Bean public ViewResolver xmlViewResolver() { final XmlViewResolver bean = new XmlViewResolver(); @@ -112,5 +161,4 @@ public class WebConfig extends WebMvcConfigurerAdapter { public ExcelPOIHelper excelPOIHelper() { return new ExcelPOIHelper(); } - -} +} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java index 93ec13da58..0793658e90 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java @@ -2,13 +2,13 @@ package com.baeldung.spring.web.config; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; -import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; @Configuration @EnableWebSocketMessageBroker -public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { +public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(final MessageBrokerRegistry config) { diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketSendToUserConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketSendToUserConfig.java index 7f14380e5e..dbd52e20ba 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketSendToUserConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketSendToUserConfig.java @@ -6,9 +6,9 @@ import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.WebSocketHandler; -import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; import org.springframework.web.socket.server.support.DefaultHandshakeHandler; import javax.servlet.http.HttpSession; @@ -16,7 +16,7 @@ import java.util.Map; @Configuration @EnableWebSocketMessageBroker -public class WebSocketSendToUserConfig extends AbstractWebSocketMessageBrokerConfigurer { +public class WebSocketSendToUserConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/SampleController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/SampleController.java new file mode 100644 index 0000000000..c13986e005 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/SampleController.java @@ -0,0 +1,13 @@ +package com.baeldung.web.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class SampleController { + @GetMapping("/sample") + public String showForm() { + return "sample"; + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/WebsocketSendToUserController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/WebsocketSendToUserController.java index d4c15aead9..4b55bcc00f 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/WebsocketSendToUserController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/WebsocketSendToUserController.java @@ -1,23 +1,19 @@ package com.baeldung.web.controller; -import com.google.gson.Gson; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.messaging.handler.annotation.MessageExceptionHandler; -import org.springframework.messaging.handler.annotation.MessageMapping; -import org.springframework.messaging.handler.annotation.Payload; -import org.springframework.messaging.simp.SimpMessageSendingOperations; -import org.springframework.messaging.simp.annotation.SendToUser; -import org.springframework.stereotype.Controller; - import java.security.Principal; import java.util.Map; +import org.springframework.messaging.handler.annotation.MessageExceptionHandler; +import org.springframework.messaging.handler.annotation.MessageMapping; +import org.springframework.messaging.handler.annotation.Payload; +import org.springframework.messaging.simp.annotation.SendToUser; +import org.springframework.stereotype.Controller; + +import com.google.gson.Gson; + @Controller public class WebsocketSendToUserController { - @Autowired - private SimpMessageSendingOperations messagingTemplate; - private Gson gson = new Gson(); @MessageMapping("/message") diff --git a/spring-mvc-java/src/main/resources/logback.xml b/spring-mvc-java/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-mvc-java/src/main/resources/logback.xml +++ b/spring-mvc-java/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/ControllerClassNameHandlerMappingConfig.java b/spring-mvc-java/src/test/java/com/baeldung/config/ControllerClassNameHandlerMappingConfig.java deleted file mode 100644 index 6e9318602f..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/config/ControllerClassNameHandlerMappingConfig.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.config; - -import com.baeldung.web.controller.handlermapping.WelcomeController; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping; -import org.springframework.web.servlet.view.InternalResourceViewResolver; - -@Configuration -public class ControllerClassNameHandlerMappingConfig { - - @Bean - public ViewResolver viewResolver() { - InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); - viewResolver.setPrefix("/"); - viewResolver.setSuffix(".jsp"); - return viewResolver; - } - - @Bean - public ControllerClassNameHandlerMapping controllerClassNameHandlerMapping() { - ControllerClassNameHandlerMapping controllerClassNameHandlerMapping = new ControllerClassNameHandlerMapping(); - return controllerClassNameHandlerMapping; - } - - @Bean - public WelcomeController welcome() { - return new WelcomeController(); - } - - -} diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingIntegrationTest.java deleted file mode 100644 index b84998470d..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingIntegrationTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.handlermappings; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.MockitoAnnotations; -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.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import com.baeldung.config.ControllerClassNameHandlerMappingConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = ControllerClassNameHandlerMappingConfig.class) -public class ControllerClassNameHandlerMappingIntegrationTest { - - @Autowired - private WebApplicationContext webAppContext; - private MockMvc mockMvc; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build(); - } - - @Test - public void whenControllerClassNameMapping_thenMappedOK() throws Exception { - mockMvc.perform(get("/welcome")).andExpect(status().isOk()).andExpect(view().name("welcome")).andDo(print()); - } -} \ No newline at end of file diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java index 479b02e77f..e734676b98 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java @@ -9,7 +9,6 @@ import org.junit.Test; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; -import com.gargoylesoftware.htmlunit.html.HtmlHeading1; import com.gargoylesoftware.htmlunit.html.HtmlPage; public class HtmlUnitWebScrapingLiveTest { @@ -37,7 +36,7 @@ public class HtmlUnitWebScrapingLiveTest { final HtmlAnchor latestPostLink = (HtmlAnchor) page.getByXPath(xpath).get(0); final HtmlPage postPage = latestPostLink.click(); - final List h1 = (List) postPage.getByXPath("//h1"); + final List h1 = postPage.getByXPath("//h1"); Assert.assertTrue(h1.size() > 0); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java index 17a68d67a5..5b86b59095 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java @@ -1,10 +1,14 @@ package com.baeldung.htmlunit; +import javax.servlet.ServletContext; + +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.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; @@ -13,8 +17,11 @@ import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.baeldung.web.controller" }) -public class TestConfig extends WebMvcConfigurerAdapter { +public class TestConfig implements WebMvcConfigurer { + @Autowired + private ServletContext ctx; + @Bean public ViewResolver thymeleafViewResolver() { final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); @@ -25,7 +32,7 @@ public class TestConfig extends WebMvcConfigurerAdapter { @Bean public ServletContextTemplateResolver templateResolver() { - final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); + final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(ctx); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode("HTML5"); diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java index b628228b7e..384bd85ec6 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java @@ -20,12 +20,12 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.spring.web.config.ApplicationConfig; +import com.baeldung.spring.web.config.WebConfig; import com.baeldung.spring.web.config.WebConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(classes = { ApplicationConfig.class, WebConfig.class }) +@ContextConfiguration(classes = { WebConfig.class, WebConfig.class }) public class GreetControllerIntegrationTest { @Autowired diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java new file mode 100644 index 0000000000..23be3a1655 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java @@ -0,0 +1,35 @@ +package com.baeldung.web.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import com.baeldung.web.controller.SimpleBookController; + +public class SimpleBookControllerIntegrationTest { + + private MockMvc mockMvc; + private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; + + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new SimpleBookController()).build(); + } + + @Test + public void givenBookId_whenMockMVC_thenVerifyResponse() throws Exception { + this.mockMvc + .perform(get("/books/42")) + .andExpect(status().isOk()) + .andExpect(content().contentType(CONTENT_TYPE)) + .andExpect(jsonPath("$.id").value(42)); + } + +} + diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerTest.java deleted file mode 100644 index 4be0ded963..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.web.controller; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -import com.baeldung.web.controller.SimpleBookController; - -public class SimpleBookControllerTest { - - private MockMvc mockMvc; - private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; - - @Before - public void setup() { - this.mockMvc = MockMvcBuilders.standaloneSetup(new SimpleBookController()).build(); - } - - @Test - public void givenBookId_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc - .perform(get("/books/42")) - .andExpect(status().isOk()) - .andExpect(content().contentType(CONTENT_TYPE)) - .andExpect(jsonPath("$.id").value(42)); - } - -} - diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java new file mode 100644 index 0000000000..c5bd53f1a7 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java @@ -0,0 +1,35 @@ +package com.baeldung.web.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import com.baeldung.web.controller.SimpleBookController; + +public class SimpleBookRestControllerIntegrationTest { + + private MockMvc mockMvc; + private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; + + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new SimpleBookController()).build(); + } + + @Test + public void givenBookId_whenMockMVC_thenVerifyResponse() throws Exception { + this.mockMvc + .perform(get("/books/42")) + .andExpect(status().isOk()) + .andExpect(content().contentType(CONTENT_TYPE)) + .andExpect(jsonPath("$.id").value(42)); + } + +} + diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerTest.java deleted file mode 100644 index 23b8c639d3..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.web.controller; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -import com.baeldung.web.controller.SimpleBookController; - -public class SimpleBookRestControllerTest { - - private MockMvc mockMvc; - private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; - - @Before - public void setup() { - this.mockMvc = MockMvcBuilders.standaloneSetup(new SimpleBookController()).build(); - } - - @Test - public void givenBookId_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc - .perform(get("/books/42")) - .andExpect(status().isOk()) - .andExpect(content().contentType(CONTENT_TYPE)) - .andExpect(jsonPath("$.id").value(42)); - } - -} - diff --git a/spring-mvc-java/src/test/resources/logback-test.xml b/spring-mvc-java/src/test/resources/logback-test.xml index e0721aa890..e35a9680bb 100644 --- a/spring-mvc-java/src/test/resources/logback-test.xml +++ b/spring-mvc-java/src/test/resources/logback-test.xml @@ -3,7 +3,7 @@ - %date [%thread] %-5level %logger{6} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-mvc-kotlin/pom.xml b/spring-mvc-kotlin/pom.xml index cc2bd18255..59b60ebd3c 100644 --- a/spring-mvc-kotlin/pom.xml +++ b/spring-mvc-kotlin/pom.xml @@ -1,126 +1,83 @@ - - 4.0.0 - spring-mvc-kotlin - 0.1-SNAPSHOT - spring-mvc-kotlin - war + + 4.0.0 + spring-mvc-kotlin + spring-mvc-kotlin + war - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + parent-kotlin + com.baeldung + 1.0.0-SNAPSHOT + ../parent-kotlin + - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - + + + org.springframework + spring-web + + + org.springframework + spring-webmvc + + + org.thymeleaf + thymeleaf + - - org.springframework - spring-web - ${spring.version} - - - org.springframework - spring-webmvc - ${spring.version} - - - org.thymeleaf - thymeleaf - ${thymeleaf.version} - + + org.thymeleaf + thymeleaf-spring4 + ${thymeleaf.version} + + + org.hibernate + hibernate-core + + + org.hibernate + hibernate-testing + test + + + com.h2database + h2 + test + + + org.springframework + spring-test + test + + - - org.thymeleaf - thymeleaf-spring4 - ${thymeleaf.version} - - - org.hibernate - hibernate-core - ${hibernate.version} - - - org.hibernate - hibernate-testing - ${hibernate.version} - test - - - com.h2database - h2 - ${h2.version} - test - - - org.springframework - spring-test - ${spring.version} - test - - + + + + kotlin-maven-plugin + org.jetbrains.kotlin + ${kotlin.version} + + + spring + jpa + + + + + org.jetbrains.kotlin + kotlin-maven-noarg + ${kotlin.version} + + + + + - - ${project.basedir}/src/main/kotlin - ${project.basedir}/src/test/kotlin - - - kotlin-maven-plugin - org.jetbrains.kotlin - ${kotlin.version} - - - spring - jpa - - 1.8 - - - - compile - compile - - compile - - - - test-compile - test-compile - - test-compile - - - - - - org.jetbrains.kotlin - kotlin-maven-allopen - ${kotlin.version} - - - org.jetbrains.kotlin - kotlin-maven-noarg - ${kotlin.version} - - - - - - - - UTF-8 - 5.2.15.Final - 1.2.30 - 4.3.10.RELEASE - 3.0.7.RELEASE - 1.4.196 - + + 3.0.7.RELEASE + \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/resources/logback.xml b/spring-mvc-kotlin/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-mvc-kotlin/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-simple/README.md b/spring-mvc-simple/README.md index 600a448076..39053534fa 100644 --- a/spring-mvc-simple/README.md +++ b/spring-mvc-simple/README.md @@ -4,3 +4,5 @@ - [Template Engines for Spring](http://www.baeldung.com/spring-template-engines) - [Spring 5 and Servlet 4 – The PushBuilder](http://www.baeldung.com/spring-5-push) - [Servlet Redirect vs Forward](http://www.baeldung.com/servlet-redirect-forward) +- [Apache Tiles Integration with Spring MVC](http://www.baeldung.com/spring-mvc-apache-tiles) +- [Guide to Spring Email](http://www.baeldung.com/spring-email) diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index 07d7221048..bd63b5ed1c 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 spring-mvc-simple war @@ -9,9 +9,9 @@ com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 @@ -20,6 +20,15 @@ spring-oxm ${spring-oxm.version} + + org.springframework + spring-context-support + + + com.sun.mail + javax.mail + 1.6.1 + javax.servlet javax.servlet-api @@ -48,7 +57,12 @@ org.springframework spring-webmvc - ${springframework.version} + ${spring.version} + + + org.springframework + spring-tx + ${spring.version} @@ -72,7 +86,7 @@ org.springframework spring-context-support - ${springframework.version} + ${spring.version} @@ -89,11 +103,17 @@ ${jade.version} + + org.apache.tiles + tiles-jsp + ${apache-tiles.version} + + org.springframework spring-test - ${springframework.version} + ${spring.version} test @@ -116,6 +136,14 @@ json ${json.version} + + org.apache.maven.surefire + surefire-logger-api + ${maven-surefire-plugin.version} + + test + true + @@ -152,29 +180,25 @@ - springMvcSimple + spring-mvc-simple 1.8 1.8 - UTF-8 - 5.0.2.RELEASE 3.2.0 3.7.0 2.21.0 1.2 2.3.2-b02 4.0.0 - 5.4.1.Final + 6.0.10.Final enter-location-of-server 1.3.2 - 1.8 3.0.7.RELEASE 2.4.12 2.3.27-incubating 1.2.5 - 5.0.2 1.0.2 1.9.0 2.9.4 @@ -182,6 +206,7 @@ 5.1.0 20180130 5.0.2.RELEASE + 3.0.8 diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java index c4c6791f9a..284be6c212 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java @@ -8,23 +8,27 @@ import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.feed.RssChannelHttpMessageConverter; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.multipart.MultipartResolver; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.ContentNegotiatingViewResolver; import org.springframework.web.servlet.view.InternalResourceViewResolver; import java.util.ArrayList; import java.util.List; +import java.util.Properties; @Configuration @EnableWebMvc -@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" }) -public class ApplicationConfiguration extends WebMvcConfigurerAdapter { +@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator", "com.baeldung.spring.mail" }) +public class ApplicationConfiguration implements WebMvcConfigurer { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { @@ -59,7 +63,30 @@ public class ApplicationConfiguration extends WebMvcConfigurerAdapter { converters.add(new StringHttpMessageConverter()); converters.add(new RssChannelHttpMessageConverter()); converters.add(new JsonChannelHttpMessageConverter()); - - super.configureMessageConverters(converters); + } + + @Bean + public SimpleMailMessage templateSimpleMessage() { + SimpleMailMessage message = new SimpleMailMessage(); + message.setText("This is the test email template for your email:\n%s\n"); + return message; + } + + @Bean + public JavaMailSender getJavaMailSender() { + JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); + mailSender.setHost("smtp.gmail.com"); + mailSender.setPort(587); + + mailSender.setUsername("my.gmail@gmail.com"); + mailSender.setPassword("password"); + + Properties props = mailSender.getJavaMailProperties(); + props.put("mail.transport.protocol", "smtp"); + props.put("mail.smtp.auth", "true"); + props.put("mail.smtp.starttls.enable", "true"); + props.put("mail.debug", "true"); + + return mailSender; } } diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/TilesApplicationConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/TilesApplicationConfiguration.java new file mode 100644 index 0000000000..de2b7fe68f --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/TilesApplicationConfiguration.java @@ -0,0 +1,47 @@ +package com.baeldung.spring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.view.tiles3.TilesConfigurer; +import org.springframework.web.servlet.view.tiles3.TilesViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = "com.baeldung.spring.controller.tiles") +public class TilesApplicationConfiguration implements WebMvcConfigurer { + + /** + * Configure TilesConfigurer. + */ + @Bean + public TilesConfigurer tilesConfigurer() { + TilesConfigurer tilesConfigurer = new TilesConfigurer(); + tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/views/**/tiles.xml" }); + tilesConfigurer.setCheckRefresh(true); + return tilesConfigurer; + } + + /** + * Configure ViewResolvers to deliver views. + */ + @Override + public void configureViewResolvers(ViewResolverRegistry registry) { + TilesViewResolver viewResolver = new TilesViewResolver(); + registry.viewResolver(viewResolver); + } + + /** + * Configure ResourceHandlers to serve static resources + */ + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/static/**").addResourceLocations("/static/"); + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java index 09030a8347..74094a11c7 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java @@ -21,6 +21,8 @@ public class WebInitializer implements WebApplicationInitializer { // ctx.register(JadeTemplateConfiguration.class); // ctx.register(PushConfiguration.class); // ctx.setServletContext(container); + + //ctx.register(TilesApplicationConfiguration.class); // Manage the lifecycle of the root application context container.addListener(new ContextLoaderListener(ctx)); diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/MailController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/MailController.java similarity index 95% rename from spring-mvc-email/src/main/java/com/baeldung/spring/controllers/MailController.java rename to spring-mvc-simple/src/main/java/com/baeldung/spring/controller/MailController.java index ff828ca9ec..16d1202eef 100644 --- a/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/MailController.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/MailController.java @@ -1,9 +1,8 @@ -package com.baeldung.spring.controllers; +package com.baeldung.spring.controller; import com.baeldung.spring.mail.EmailServiceImpl; -import com.baeldung.spring.web.dto.MailObject; +import com.baeldung.spring.domain.MailObject; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.SimpleMailMessage; import org.springframework.stereotype.Controller; @@ -62,6 +61,11 @@ public class MailController { props.put("additionalInfo", "To make sure that you send an attachment with this email, change the value for the 'attachment.invoice' in the application.properties file to the path to the attachment."); labels.put("sendAttachment", props); } + + @RequestMapping(method = RequestMethod.GET) + public String showEmailsPage() { + return "emails"; + } @RequestMapping(value = {"/send", "/sendTemplate", "/sendAttachment"}, method = RequestMethod.GET) public String createMail(Model model, diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/push/PushController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/push/PushController.java index b557c65c93..88448d4885 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/push/PushController.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/push/PushController.java @@ -11,9 +11,7 @@ public class PushController { @GetMapping(path = "/demoWithPush") public String demoWithPush(PushBuilder pushBuilder) { if (null != pushBuilder) { - pushBuilder.path("resources/logo.png") - .addHeader("Content-Type", "image/png") - .push(); + pushBuilder.path("resources/logo.png").push(); } return "demo"; } @@ -22,4 +20,4 @@ public class PushController { public String demoWithoutPush() { return "demo"; } -} \ No newline at end of file +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/tiles/TilesController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/tiles/TilesController.java new file mode 100644 index 0000000000..319340b886 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/tiles/TilesController.java @@ -0,0 +1,26 @@ +package com.baeldung.spring.controller.tiles; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +@RequestMapping("/") +public class TilesController { + + @RequestMapping(value = { "/" }, method = RequestMethod.GET) + public String homePage(ModelMap model) { + return "home"; + } + + @RequestMapping(value = { "/apachetiles" }, method = RequestMethod.GET) + public String productsPage(ModelMap model) { + return "apachetiles"; + } + + @RequestMapping(value = { "/springmvc" }, method = RequestMethod.GET) + public String contactUsPage(ModelMap model) { + return "springmvc"; + } +} diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/web/dto/MailObject.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/MailObject.java similarity index 89% rename from spring-mvc-email/src/main/java/com/baeldung/spring/web/dto/MailObject.java rename to spring-mvc-simple/src/main/java/com/baeldung/spring/domain/MailObject.java index 9623ff5d78..aceaf685fa 100644 --- a/spring-mvc-email/src/main/java/com/baeldung/spring/web/dto/MailObject.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/MailObject.java @@ -1,7 +1,6 @@ -package com.baeldung.spring.web.dto; - -import org.hibernate.validator.constraints.Email; +package com.baeldung.spring.domain; +import javax.validation.constraints.Email; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/mail/EmailService.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/mail/EmailService.java similarity index 100% rename from spring-mvc-email/src/main/java/com/baeldung/spring/mail/EmailService.java rename to spring-mvc-simple/src/main/java/com/baeldung/spring/mail/EmailService.java diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java similarity index 99% rename from spring-mvc-email/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java rename to spring-mvc-simple/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java index ca418a7d90..039b970d8e 100644 --- a/spring-mvc-email/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java @@ -8,9 +8,10 @@ import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; +import java.io.File; + import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; -import java.io.File; /** * Created by Olga on 7/15/2016. diff --git a/spring-mvc-simple/src/main/resources/application.properties b/spring-mvc-simple/src/main/resources/application.properties new file mode 100644 index 0000000000..9a804c07d8 --- /dev/null +++ b/spring-mvc-simple/src/main/resources/application.properties @@ -0,0 +1,22 @@ +#this property file will have to be loaded explicitly as this is not a Spring Boot project + +# Gmail SMTP +spring.mail.host=smtp.gmail.com +spring.mail.port=587 +spring.mail.username=username +spring.mail.password=password +spring.mail.properties.mail.smtp.auth=true +spring.mail.properties.mail.smtp.starttls.enable=true + +# Amazon SES SMTP +#spring.mail.host=email-smtp.us-west-2.amazonaws.com +#spring.mail.username=username +#spring.mail.password=password +#spring.mail.properties.mail.transport.protocol=smtp +#spring.mail.properties.mail.smtp.port=25 +#spring.mail.properties.mail.smtp.auth=true +#spring.mail.properties.mail.smtp.starttls.enable=true +#spring.mail.properties.mail.smtp.starttls.required=true + +# path to attachment file +attachment.invoice=path_to_file \ No newline at end of file diff --git a/spring-mvc-simple/src/main/resources/logback.xml b/spring-mvc-simple/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-mvc-simple/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-email/src/main/webapp/WEB-INF/views/home.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/emails.jsp similarity index 100% rename from spring-mvc-email/src/main/webapp/WEB-INF/views/home.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/emails.jsp diff --git a/spring-mvc-email/src/main/webapp/WEB-INF/views/mail/send.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/mail/send.jsp similarity index 100% rename from spring-mvc-email/src/main/webapp/WEB-INF/views/mail/send.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/mail/send.jsp diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp similarity index 97% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp index 9936957c04..918c52ab45 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp @@ -1,12 +1,12 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> - - - - -Apache Tiles - - -

    Tiles with Spring MVC Demo

    - +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Apache Tiles + + +

    Tiles with Spring MVC Demo

    + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/home.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/home.jsp new file mode 100644 index 0000000000..47157a5d2a --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/home.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Home + + +

    Welcome to Apache Tiles integration with Spring MVC

    + + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/springmvc.jsp similarity index 97% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/springmvc.jsp index 209b1004de..497e04901a 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/springmvc.jsp @@ -1,12 +1,12 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> - - - - -Spring MVC - - -

    Spring MVC configured to work with Apache Tiles

    - +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Spring MVC + + +

    Spring MVC configured to work with Apache Tiles

    + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp similarity index 96% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp index 2370ad4ab1..064f3ee78b 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp @@ -1,25 +1,25 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> -<%@ page isELIgnored="false"%> -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> -<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%> - - - - - -<tiles:getAsString name="title" /> - - - - -
    - - -
    - -
    - -
    - - +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ page isELIgnored="false"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%> + + + + + +<tiles:getAsString name="title" /> + + + + +
    + + +
    + +
    + +
    + + diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp similarity index 95% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp index 3849cc5230..0946549e06 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp @@ -1,2 +1,2 @@ - -
    copyright © Baeldung
    + +
    copyright © Baeldung
    diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp similarity index 97% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp index 8a878c857d..4ad29d82e0 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp @@ -1,3 +1,3 @@ -
    -

    Welcome to Spring MVC integration with Apache Tiles

    +
    +

    Welcome to Spring MVC integration with Apache Tiles

    \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp similarity index 97% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp index 2c91eace85..17502fd051 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp @@ -1,8 +1,8 @@ - + diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/tiles.xml similarity index 97% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/tiles.xml index 789fbd809a..648ecb44fe 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/tiles.xml @@ -1,34 +1,34 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/static/css/app.css b/spring-mvc-simple/src/main/webapp/static/css/app.css similarity index 100% rename from spring-mvc-tiles/src/main/webapp/static/css/app.css rename to spring-mvc-simple/src/main/webapp/static/css/app.css diff --git a/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/HelloServletIntegrationTest.java b/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/HelloServletIntegrationTest.java new file mode 100644 index 0000000000..46cc280875 --- /dev/null +++ b/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/HelloServletIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.spring.servlets; + +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import javax.servlet.ServletException; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class HelloServletIntegrationTest { + @Test + public void whenRequested_thenForwardToCorrectUrl() throws ServletException, IOException { + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hello"); + request.addParameter("name", "Dennis"); + MockHttpServletResponse response = new MockHttpServletResponse(); + HelloServlet servlet = new HelloServlet(); + + servlet.doGet(request, response); + + assertEquals("/forwarded", response.getForwardedUrl()); + assertEquals(200, response.getStatus()); + } +} diff --git a/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/HelloServletTest.java b/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/HelloServletTest.java deleted file mode 100644 index e8dd8f1b73..0000000000 --- a/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/HelloServletTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.spring.servlets; - -import org.junit.jupiter.api.Test; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import javax.servlet.ServletException; -import java.io.IOException; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class HelloServletTest { - @Test - public void whenRequested_thenForwardToCorrectUrl() throws ServletException, IOException { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hello"); - request.addParameter("name", "Dennis"); - MockHttpServletResponse response = new MockHttpServletResponse(); - HelloServlet servlet = new HelloServlet(); - - servlet.doGet(request, response); - - assertEquals("/forwarded", response.getForwardedUrl()); - assertEquals(200, response.getStatus()); - } -} diff --git a/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/WelcomeServletIntegrationTest.java b/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/WelcomeServletIntegrationTest.java new file mode 100644 index 0000000000..d942fdd8d6 --- /dev/null +++ b/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/WelcomeServletIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.spring.servlets; + +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import javax.servlet.ServletException; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class WelcomeServletIntegrationTest { + @Test + public void whenRequested_thenRedirectedToCorrectUrl() throws ServletException, IOException { + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome"); + request.addParameter("name", "Dennis"); + WelcomeServlet servlet = new WelcomeServlet(); + MockHttpServletResponse response = new MockHttpServletResponse(); + + servlet.doGet(request, response); + + assertEquals("/redirected", response.getRedirectedUrl()); + assertEquals(302, response.getStatus()); + } +} diff --git a/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/WelcomeServletTest.java b/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/WelcomeServletTest.java deleted file mode 100644 index 9ec177a452..0000000000 --- a/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/WelcomeServletTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.spring.servlets; - -import org.junit.jupiter.api.Test; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import javax.servlet.ServletException; -import java.io.IOException; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class WelcomeServletTest { - @Test - public void whenRequested_thenRedirectedToCorrectUrl() throws ServletException, IOException { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome"); - request.addParameter("name", "Dennis"); - WelcomeServlet servlet = new WelcomeServlet(); - MockHttpServletResponse response = new MockHttpServletResponse(); - - servlet.doGet(request, response); - - assertEquals("/redirected", response.getRedirectedUrl()); - assertEquals(302, response.getStatus()); - } -} diff --git a/spring-mvc-tiles/README.md b/spring-mvc-tiles/README.md deleted file mode 100644 index 58991005f5..0000000000 --- a/spring-mvc-tiles/README.md +++ /dev/null @@ -1,2 +0,0 @@ -###Relevant Articles: -- [Apache Tiles Integration with Spring MVC](http://www.baeldung.com/spring-mvc-apache-tiles) diff --git a/spring-mvc-tiles/pom.xml b/spring-mvc-tiles/pom.xml deleted file mode 100644 index 94908d5d8b..0000000000 --- a/spring-mvc-tiles/pom.xml +++ /dev/null @@ -1,94 +0,0 @@ - - 4.0.0 - com.baeldung - spring-mvc-tiles - 0.0.1-SNAPSHOT - war - spring-mvc-tiles - Integrating Spring MVC with Apache Tiles - - - com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring - - - - - - org.springframework - spring-core - ${springframework.version} - - - commons-logging - commons-logging - - - - - org.springframework - spring-web - ${springframework.version} - - - org.springframework - spring-webmvc - ${springframework.version} - - - - org.apache.tiles - tiles-jsp - ${apache-tiles.version} - - - - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - - - javax.servlet.jsp - javax.servlet.jsp-api - ${javax.servlet.jsp-api.version} - - - javax.servlet - jstl - ${jstl.version} - - - - - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - src/main/webapp - spring-mvc-tiles - false - - - - - spring-mvc-tiles - - - - 4.3.4.RELEASE - 3.0.7 - 3.1.0 - 2.3.1 - 1.2 - 2.6 - - - diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java deleted file mode 100644 index d2e90a4f53..0000000000 --- a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.tiles.springmvc; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.view.tiles3.TilesConfigurer; -import org.springframework.web.servlet.view.tiles3.TilesViewResolver; - -@Configuration -@EnableWebMvc -@ComponentScan(basePackages = "com.baeldung.tiles.springmvc") -public class ApplicationConfiguration extends WebMvcConfigurerAdapter { - - /** - * Configure TilesConfigurer. - */ - @Bean - public TilesConfigurer tilesConfigurer() { - TilesConfigurer tilesConfigurer = new TilesConfigurer(); - tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/views/**/tiles.xml" }); - tilesConfigurer.setCheckRefresh(true); - return tilesConfigurer; - } - - /** - * Configure ViewResolvers to deliver views. - */ - @Override - public void configureViewResolvers(ViewResolverRegistry registry) { - TilesViewResolver viewResolver = new TilesViewResolver(); - registry.viewResolver(viewResolver); - } - - /** - * Configure ResourceHandlers to serve static resources - */ - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/static/**").addResourceLocations("/static/"); - } - -} diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java deleted file mode 100644 index 1a348d1c26..0000000000 --- a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.tiles.springmvc; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -@Controller -@RequestMapping("/") -public class ApplicationController { - - @RequestMapping(value = { "/" }, method = RequestMethod.GET) - public String homePage(ModelMap model) { - return "home"; - } - - @RequestMapping(value = { "/apachetiles" }, method = RequestMethod.GET) - public String productsPage(ModelMap model) { - return "apachetiles"; - } - - @RequestMapping(value = { "/springmvc" }, method = RequestMethod.GET) - public String contactUsPage(ModelMap model) { - return "springmvc"; - } -} diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java deleted file mode 100644 index 79583dbe83..0000000000 --- a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.tiles.springmvc; - -import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; - -public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { - - @Override - protected Class[] getRootConfigClasses() { - return new Class[] { ApplicationConfiguration.class }; - } - - @Override - protected Class[] getServletConfigClasses() { - return null; - } - - @Override - protected String[] getServletMappings() { - return new String[] { "/" }; - } - -} diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp deleted file mode 100644 index b501d4968e..0000000000 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp +++ /dev/null @@ -1,12 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> - - - - -Home - - -

    Welcome to Apache Tiles integration with Spring MVC

    - - \ No newline at end of file diff --git a/spring-mvc-velocity/pom.xml b/spring-mvc-velocity/pom.xml index 07d7182b7d..dc5adcf3cf 100644 --- a/spring-mvc-velocity/pom.xml +++ b/spring-mvc-velocity/pom.xml @@ -1,150 +1,127 @@ - 4.0.0 - com.baeldung - 0.1-SNAPSHOT - spring-mvc-velocity + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + 0.1-SNAPSHOT + spring-mvc-velocity - spring-mvc-velocity - war + spring-mvc-velocity + war - - com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring - + + com.baeldung + parent-spring-4 + 0.0.1-SNAPSHOT + ../parent-spring-4 + - + - + - - org.springframework - spring-web - ${spring.version} - - - org.springframework - spring-webmvc - ${spring.version} - - - org.springframework - spring-context-support - ${spring.version} - + + org.springframework + spring-web + ${spring.version} + + + org.springframework + spring-webmvc + ${spring.version} + + + org.springframework + spring-context-support + ${spring.version} + - + - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - provided - + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + provided + - - org.apache.velocity - velocity - ${velocity.version} - + + org.apache.velocity + velocity + ${velocity.version} + - - org.apache.velocity - velocity-tools - ${velocity-tools.version} - - - commons-logging - commons-logging - - - + + org.apache.velocity + velocity-tools + ${velocity-tools.version} + + + commons-logging + commons-logging + + + - - - org.powermock - powermock-module-junit4 - ${powermock.version} - test - - - org.powermock - powermock-api-mockito - ${powermock.version} - test - - - org.springframework - spring-test - ${spring.version} - test - + + + org.powermock + powermock-module-junit4 + ${powermock.version} + test + + + org.powermock + powermock-api-mockito + ${powermock.version} + test + + + org.springframework + spring-test + ${spring.version} + test + - + - - spring-mvc-velocity - - - src/main/resources - true - - + + spring-mvc-velocity + + + src/main/resources + true + + - + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - false - - + - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - - **/*IntegrationTest.java - - - - - - + + 1.6.6 - + 4.4.5 + 4.5.2 - + 3.1.0 + 1.7 + 2.0 + 2.9.0 + + 2.6 + 2.7 + 1.6.1 - - - 4.3.4.RELEASE - - - - 1.6.6 - - 4.4.5 - 4.5.2 - - 3.1.0 - 1.7 - 2.0 - 2.9.0 - - - 2.6 - 2.7 - 1.6.1 - - + \ No newline at end of file diff --git a/spring-mvc-velocity/src/main/resources/logback.xml b/spring-mvc-velocity/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-mvc-velocity/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-webflow/pom.xml b/spring-mvc-webflow/pom.xml index f0a991912a..f7070efb94 100644 --- a/spring-mvc-webflow/pom.xml +++ b/spring-mvc-webflow/pom.xml @@ -1,10 +1,9 @@ + 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 0.1-SNAPSHOT spring-mvc-webflow - spring-mvc-webflow war @@ -36,21 +35,18 @@ - javax.servlet javax.servlet-api ${javax.servlet-api.version} provided - javax.servlet jstl ${jstl.version} runtime - org.slf4j log4j-over-slf4j @@ -67,7 +63,6 @@ true - org.apache.maven.plugins @@ -78,15 +73,14 @@ - - 4.3.4.RELEASE + 5.0.1.RELEASE - 2.4.4.RELEASE + 2.5.0.RELEASE 3.1.0 1.2 @@ -94,8 +88,6 @@ 4.4.5 4.5.2 - 2.9.0 - 2.6 2.7 diff --git a/spring-mvc-webflow/src/main/java/org/baeldung/spring/WebMvcConfig.java b/spring-mvc-webflow/src/main/java/org/baeldung/spring/WebMvcConfig.java index 434f49615b..46bf322f1d 100644 --- a/spring-mvc-webflow/src/main/java/org/baeldung/spring/WebMvcConfig.java +++ b/spring-mvc-webflow/src/main/java/org/baeldung/spring/WebMvcConfig.java @@ -2,12 +2,10 @@ package org.baeldung.spring; 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.ImportResource; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; import org.springframework.webflow.mvc.servlet.FlowHandlerAdapter; @@ -15,7 +13,7 @@ import org.springframework.webflow.mvc.servlet.FlowHandlerMapping; @EnableWebMvc @Configuration -public class WebMvcConfig extends WebMvcConfigurerAdapter { +public class WebMvcConfig implements WebMvcConfigurer { @Autowired private WebFlowConfig webFlowConfig; diff --git a/spring-mvc-webflow/src/main/resources/logback.xml b/spring-mvc-webflow/src/main/resources/logback.xml index 1146dade63..5ce05b3361 100644 --- a/spring-mvc-webflow/src/main/resources/logback.xml +++ b/spring-mvc-webflow/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-mvc-webflow/src/main/webapp/WEB-INF/flows/activation-flow.xml b/spring-mvc-webflow/src/main/webapp/WEB-INF/flows/activation-flow.xml index ab9eb1a9b7..bad5c5f78c 100644 --- a/spring-mvc-webflow/src/main/webapp/WEB-INF/flows/activation-flow.xml +++ b/spring-mvc-webflow/src/main/webapp/WEB-INF/flows/activation-flow.xml @@ -2,7 +2,7 @@ + http://www.springframework.org/schema/webflow/spring-webflow.xsd"> diff --git a/spring-mvc-xml/README.md b/spring-mvc-xml/README.md index 6333b20e11..442a533d1b 100644 --- a/spring-mvc-xml/README.md +++ b/spring-mvc-xml/README.md @@ -10,7 +10,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Spring MVC Tutorial](http://www.baeldung.com/spring-mvc-tutorial) - [Servlet Session Timeout](http://www.baeldung.com/servlet-session-timeout) -- [Basic Forms with Spring MVC](http://www.baeldung.com/spring-mvc-form-tutorial) - [Returning Image/Media Data with Spring MVC](http://www.baeldung.com/spring-mvc-image-media-data) - [Geolocation by IP in Java](http://www.baeldung.com/geolocation-by-ip-with-maxmind) - [Guide to JavaServer Pages (JSP)](http://www.baeldung.com/jsp) diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index 8ec2ff10e5..fd33c25241 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -1,5 +1,5 @@ + 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 0.1-SNAPSHOT @@ -37,13 +37,6 @@ - - com.fasterxml.jackson.core - jackson-databind - 2.9.2 - - - javax.servlet javax.servlet-api @@ -64,8 +57,8 @@ ${hibernate-validator.version} - + com.fasterxml.jackson.core jackson-databind @@ -125,12 +118,11 @@ + 5.0.2.RELEASE - 4.2.0.RELEASE - 5.2.5.Final 5.1.40 @@ -138,10 +130,10 @@ 4.5.2 - 5.3.3.Final + 6.0.10.Final 1.2 3.1.0 - 2.8.5 + 2.9.6 19.0 @@ -149,9 +141,6 @@ 2.5 2.8.0 - - 2.9.0 - 2.6 1.6.1 diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java index b5238b04d5..9752526963 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java @@ -2,11 +2,11 @@ package com.baeldung.spring; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @ImportResource("classpath:webMvcConfig.xml") @Configuration -public class ClientWebConfig extends WebMvcConfigurerAdapter { +public class ClientWebConfig implements WebMvcConfigurer { public ClientWebConfig() { super(); diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java index f299c46dbc..7925fa451d 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java @@ -9,13 +9,13 @@ import org.springframework.context.support.MessageSourceResourceBundle; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; //@EnableWebMvc //@Configuration -public class ClientWebConfigJava extends WebMvcConfigurerAdapter { +public class ClientWebConfigJava implements WebMvcConfigurer { public ClientWebConfigJava() { super(); @@ -38,8 +38,6 @@ public class ClientWebConfigJava extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/sample.html"); } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java deleted file mode 100644 index fa76933f8f..0000000000 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.spring.controller; - -import java.util.HashMap; -import java.util.Map; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.servlet.ModelAndView; - -import com.baeldung.spring.form.Employee; - -@Controller -public class EmployeeController { - - Map employeeMap = new HashMap<>(); - - @RequestMapping(value = "/employee", method = RequestMethod.GET) - public ModelAndView showForm() { - return new ModelAndView("employeeHome", "employee", new Employee()); - } - - @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { - return employeeMap.get(Id); - } - - @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) - public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { - if (result.hasErrors()) { - return "error"; - } - model.addAttribute("name", employee.getName()); - model.addAttribute("contactNumber", employee.getContactNumber()); - model.addAttribute("id", employee.getId()); - employeeMap.put(employee.getId(), employee); - return "employeeView"; - } - -} diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GeoIPTestController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GeoIPTestController.java index eeaddcf8e0..0e2fe48160 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GeoIPTestController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GeoIPTestController.java @@ -11,7 +11,8 @@ import org.springframework.web.bind.annotation.ResponseBody; import com.baeldung.spring.form.GeoIP; import com.baeldung.spring.service.RawDBDemoGeoIPLocationService; -@Controller +//@Controller +//add db file and uncomment to see the working example public class GeoIPTestController { private RawDBDemoGeoIPLocationService locationService; diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Employee.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Employee.java deleted file mode 100644 index 66b2e9f185..0000000000 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Employee.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.spring.form; - -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement -public class Employee { - - private long id; - - @NotNull - @Size(min = 1) - private String name; - @NotNull - @Size(min = 1) - private String contactNumber; - - public Employee() { - super(); - } - - // - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public long getId() { - return id; - } - - public void setId(final long id) { - this.id = id; - } - - public String getContactNumber() { - return contactNumber; - } - - public void setContactNumber(final String contactNumber) { - this.contactNumber = contactNumber; - } - -} diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java index 01638fbe76..307a36b10f 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java @@ -2,7 +2,8 @@ package com.baeldung.spring.form; import java.util.List; -import org.hibernate.validator.constraints.NotEmpty; +import javax.validation.constraints.NotEmpty; + import org.springframework.web.multipart.MultipartFile; public class Person { diff --git a/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml b/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml index 75d5c1ecd6..8a0671ca87 100644 --- a/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml +++ b/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml @@ -4,11 +4,11 @@ xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans-4.3.xsd + http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context - http://www.springframework.org/schema/context/spring-context-4.3.xsd + http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc - http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> + http://www.springframework.org/schema/mvc/spring-mvc.xsd"> diff --git a/spring-mvc-xml/src/main/resources/logback.xml b/spring-mvc-xml/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-mvc-xml/src/main/resources/logback.xml +++ b/spring-mvc-xml/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-mvc-xml/src/main/resources/webMvcConfig.xml b/spring-mvc-xml/src/main/resources/webMvcConfig.xml index 37aebe1d1d..4bdb405237 100644 --- a/spring-mvc-xml/src/main/resources/webMvcConfig.xml +++ b/spring-mvc-xml/src/main/resources/webMvcConfig.xml @@ -3,11 +3,11 @@ xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans-4.3.xsd + http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context - http://www.springframework.org/schema/context/spring-context-4.3.xsd + http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc - http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd" + http://www.springframework.org/schema/mvc/spring-mvc.xsd" > diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeHome.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeHome.jsp deleted file mode 100644 index 588678cdcf..0000000000 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeHome.jsp +++ /dev/null @@ -1,33 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> -<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> - - - -Form Example - Register an Employee - - -

    Welcome, Enter The Employee Details

    - - - - - - - - - - - - - - - - - - -
    Name
    Id
    Contact Number
    -
    - - - - \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeView.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeView.jsp deleted file mode 100644 index 1457bc5fc8..0000000000 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeView.jsp +++ /dev/null @@ -1,24 +0,0 @@ -<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> - - -Spring MVC Form Handling - - - -

    Submitted Employee Information

    - - - - - - - - - - - - - -
    Name :${name}
    ID :${id}
    Contact Number :${contactNumber}
    - - \ No newline at end of file diff --git a/spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java b/spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java index 0e957f3400..0aa23842b1 100644 --- a/spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java +++ b/spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java @@ -14,10 +14,12 @@ public class GeoIpIntegrationTest { @Test public void givenIP_whenFetchingCity_thenReturnsCityData() throws IOException, GeoIp2Exception { - File database = new File("your-path-to-db-file"); + + ClassLoader classLoader = getClass().getClassLoader(); + File database = new File(classLoader.getResource("GeoLite2-City.mmdb").getFile()); DatabaseReader dbReader = new DatabaseReader.Builder(database).build(); - InetAddress ipAddress = InetAddress.getByName("your-public-ip"); + InetAddress ipAddress = InetAddress.getByName("google.com"); CityResponse response = dbReader.city(ipAddress); String countryName = response.getCountry().getName(); diff --git a/spring-mvc-xml/src/test/resources/GeoLite2-City.mmdb b/spring-mvc-xml/src/test/resources/GeoLite2-City.mmdb new file mode 100644 index 0000000000..6de839a7ed Binary files /dev/null and b/spring-mvc-xml/src/test/resources/GeoLite2-City.mmdb differ diff --git a/spring-mybatis/pom.xml b/spring-mybatis/pom.xml index 073c332705..7b8b66fef1 100644 --- a/spring-mybatis/pom.xml +++ b/spring-mybatis/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung spring-mybatis @@ -18,52 +18,57 @@ org.mybatis mybatis - 3.1.1 + ${mybatis.version} org.mybatis mybatis-spring - 1.1.1 + ${mybatis-spring.version} org.springframework spring-context-support - 3.1.1.RELEASE + ${spring.version} org.springframework spring-test - 3.1.1.RELEASE + ${spring.version} test mysql mysql-connector-java - 5.1.40 + ${mysql-connector.version} javax.servlet jstl - 1.2 + ${jstl.version} org.springframework spring-webmvc - 3.2.4.RELEASE + ${spring-webmvc.version} javax.servlet servlet-api - 2.5 - - - junit - junit - 3.8.1 - test + ${servlet.version} + spring-mybatis + + + 3.1.1 + 1.1.1 + 3.1.1.RELEASE + 3.2.4.RELEASE + 5.1.40 + 1.2 + 2.5 + diff --git a/spring-mybatis/src/main/resources/logback.xml b/spring-mybatis/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-mybatis/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-protobuf/pom.xml b/spring-protobuf/pom.xml index 5081634d9b..1ab5048d27 100644 --- a/spring-protobuf/pom.xml +++ b/spring-protobuf/pom.xml @@ -1,5 +1,5 @@ + 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-protobuf @@ -7,17 +7,12 @@ spring-protobuf - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 - - 3.1.0 - 1.4 - - com.google.protobuf @@ -52,4 +47,10 @@ + + + 3.1.0 + 1.4 + + diff --git a/spring-protobuf/src/main/resources/logback.xml b/spring-protobuf/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-protobuf/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-quartz/pom.xml b/spring-quartz/pom.xml index 435e571180..47ffeccba9 100644 --- a/spring-quartz/pom.xml +++ b/spring-quartz/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung @@ -11,47 +11,41 @@ Demo project for Scheduling in Spring with Quartz - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 - - 2.2.3 - - - org.springframework.boot spring-boot-starter-jdbc - org.springframework spring-context-support - org.quartz-scheduler quartz ${quartz.version} - - src/main/resources true - + + 2.2.3 + + \ No newline at end of file diff --git a/spring-quartz/src/main/resources/logback.xml b/spring-quartz/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-quartz/src/main/resources/logback.xml +++ b/spring-quartz/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-reactive-kotlin/README.md b/spring-reactive-kotlin/README.md new file mode 100644 index 0000000000..cf5debc617 --- /dev/null +++ b/spring-reactive-kotlin/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Spring Webflux with Kotlin](http://www.baeldung.com/spring-webflux-kotlin) diff --git a/spring-reactive-kotlin/pom.xml b/spring-reactive-kotlin/pom.xml new file mode 100644 index 0000000000..bff39984e0 --- /dev/null +++ b/spring-reactive-kotlin/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + spring-reactive-kotlin + jar + Spring Reactive Kotlin + Demo project for Spring Boot + + + parent-kotlin + com.baeldung + 1.0.0-SNAPSHOT + ../parent-kotlin + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-webflux + + + com.fasterxml.jackson.module + jackson-module-kotlin + + + + org.springframework.boot + spring-boot-starter-test + test + + + io.projectreactor + reactor-test + test + + + + + + + kotlin-maven-plugin + org.jetbrains.kotlin + ${kotlin.version} + + + -Xjsr305=strict + + + + + + diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Application.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Application.kt new file mode 100644 index 0000000000..87ac7417b7 --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Application.kt @@ -0,0 +1,11 @@ +package com.baeldung.springreactivekotlin + +import org.springframework.boot.SpringApplication +import org.springframework.boot.autoconfigure.SpringBootApplication + +@SpringBootApplication +class Application + +fun main(args: Array) { + SpringApplication.run(Application::class.java, *args) +} diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Controller.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Controller.kt new file mode 100644 index 0000000000..76f8a62b85 --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Controller.kt @@ -0,0 +1,18 @@ +package com.baeldung.springreactivekotlin + +import org.springframework.http.MediaType +import org.springframework.stereotype.Controller +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.ResponseBody +import reactor.core.publisher.Flux + +@Controller +class Controller { + + @GetMapping(path = ["/numbers"], produces = [MediaType.APPLICATION_STREAM_JSON_VALUE]) + @ResponseBody + fun getNumbers(): Flux { + return Flux.range(1, 100) + } + +} diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Device.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Device.kt new file mode 100644 index 0000000000..9eb6eb8488 --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Device.kt @@ -0,0 +1,5 @@ +package com.baeldung.springreactivekotlin + +class Device(val name: String, val reading: Double) { + +} diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsHandler.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsHandler.kt new file mode 100644 index 0000000000..0ef9f37f1b --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsHandler.kt @@ -0,0 +1,36 @@ +package com.baeldung.springreactivekotlin + +import org.springframework.stereotype.Component +import org.springframework.web.reactive.function.BodyInserters.fromObject +import org.springframework.web.reactive.function.server.ServerRequest +import org.springframework.web.reactive.function.server.ServerResponse +import reactor.core.publisher.Mono + +@Component +class HomeSensorsHandler { + + var data = mapOf("lamp" to arrayOf(0.7, 0.65, 0.67), "fridge" to arrayOf(12.0, 11.9, 12.5)) + + fun setLight(request: ServerRequest): Mono = ServerResponse.ok().build() + + fun getLightReading(request: ServerRequest): Mono = + ServerResponse.ok().body(fromObject(data["lamp"]!!)) + + fun getDeviceReadings(request: ServerRequest): Mono { + val id = request.pathVariable("id") + return ServerResponse.ok().body(fromObject(Device(id, 1.0))) + } + + fun getAllDevices(request: ServerRequest): Mono = + ServerResponse.ok().body(fromObject(arrayOf("lamp", "tv"))) + + fun getAllDeviceApi(request: ServerRequest): Mono = + ServerResponse.ok().body(fromObject(arrayListOf("kettle", "fridge"))) + + fun setDeviceReadingApi(request: ServerRequest): Mono { + return request.bodyToMono(Device::class.java).flatMap { it -> + ServerResponse.ok().body(fromObject(Device(it.name.toUpperCase(), it.reading))) + } + } + +} \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsRouters.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsRouters.kt new file mode 100644 index 0000000000..27d87afd89 --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsRouters.kt @@ -0,0 +1,32 @@ +package com.baeldung.springreactivekotlin + +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.http.MediaType.APPLICATION_JSON +import org.springframework.http.MediaType.TEXT_HTML +import org.springframework.web.reactive.function.server.router + +@Configuration +class HomeSensorsRouters(private val handler: HomeSensorsHandler) { + + @Bean + fun roomsRouter() = router { + (accept(TEXT_HTML) and "/room").nest { + GET("/light", handler::getLightReading) + POST("/light", handler::setLight) + } + } + + @Bean + fun deviceRouter() = router { + accept(TEXT_HTML).nest { + (GET("/device/") or GET("/devices/")).invoke(handler::getAllDevices) + GET("/device/{id}", handler::getDeviceReadings) + } + (accept(APPLICATION_JSON) and "/api").nest { + (GET("/device/") or GET("/devices/")).invoke(handler::getAllDeviceApi) + POST("/device/", handler::setDeviceReadingApi) + } + } + +} diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Routes.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Routes.kt new file mode 100644 index 0000000000..9015fc5df8 --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Routes.kt @@ -0,0 +1,16 @@ +package com.baeldung.springreactivekotlin + +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.web.reactive.function.server.ServerResponse +import org.springframework.web.reactive.function.server.router + +import org.springframework.web.reactive.function.BodyInserters.fromObject + +@Configuration +class SimpleRoute { + @Bean + fun route() = router { + GET("/route") { _ -> ServerResponse.ok().body(fromObject(arrayOf(1, 2, 3))) } + } +} \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/resources/logback.xml b/spring-reactive-kotlin/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-reactive-kotlin/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-reactive-kotlin/src/test/kotlin/RoutesTest.kt b/spring-reactive-kotlin/src/test/kotlin/RoutesTest.kt new file mode 100644 index 0000000000..ba640070e3 --- /dev/null +++ b/spring-reactive-kotlin/src/test/kotlin/RoutesTest.kt @@ -0,0 +1,35 @@ +package veontomo + +import com.baeldung.springreactivekotlin.SimpleRoute +import org.junit.Before +import org.junit.Test +import org.springframework.test.web.reactive.server.WebTestClient + +class RoutesTest { + + lateinit var client: WebTestClient + + @Before + fun init() { + this.client = WebTestClient.bindToRouterFunction(SimpleRoute().route()).build() + } + + + @Test + fun whenRequestToRoute_thenStatusShouldBeOk() { + client.get() + .uri("/route") + .exchange() + .expectStatus().isOk + } + + + @Test + fun whenRequestToRoute_thenBodyShouldContainArray123() { + client.get() + .uri("/route") + .exchange() + .expectBody() + .json("[1, 2, 3]") + } +} \ No newline at end of file diff --git a/spring-reactor/pom.xml b/spring-reactor/pom.xml index 1098f8b60d..f6db404656 100644 --- a/spring-reactor/pom.xml +++ b/spring-reactor/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung spring-reactor @@ -9,10 +9,10 @@ http://maven.apache.org - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-reactor/src/main/resources/logback.xml b/spring-reactor/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-reactor/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-remoting/pom.xml b/spring-remoting/pom.xml index aac8357c10..9f05bc91d2 100644 --- a/spring-remoting/pom.xml +++ b/spring-remoting/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.baeldung spring-remoting @@ -11,10 +10,10 @@ Parent for all projects related to Spring Remoting. - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -33,7 +32,7 @@ remoting-hessian-burlap remoting-amqp remoting-jms - spring-remoting-rmi + remoting-rmi \ No newline at end of file diff --git a/spring-remoting/remoting-amqp/pom.xml b/spring-remoting/remoting-amqp/pom.xml index 3ada2337ee..f52959046a 100644 --- a/spring-remoting/remoting-amqp/pom.xml +++ b/spring-remoting/remoting-amqp/pom.xml @@ -1,17 +1,17 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + + remoting-amqp + pom + remoting-amqp + spring-remoting com.baeldung 1.0-SNAPSHOT - 4.0.0 - remoting-amqp - pom - - - remoting-amqp remoting-amqp-server remoting-amqp-client diff --git a/spring-remoting/remoting-amqp/remoting-amqp-client/pom.xml b/spring-remoting/remoting-amqp/remoting-amqp-client/pom.xml index 9a2d0bf9cc..98e0bc5df5 100644 --- a/spring-remoting/remoting-amqp/remoting-amqp-client/pom.xml +++ b/spring-remoting/remoting-amqp/remoting-amqp-client/pom.xml @@ -1,21 +1,17 @@ + 4.0.0 + + remoting-amqp-client + jar + remoting-amqp-client + http://maven.apache.org + remoting-amqp com.baeldung 1.0-SNAPSHOT - 4.0.0 - - remoting-amqp-client - jar - - remoting-amqp-client - http://maven.apache.org - - - UTF-8 - @@ -30,7 +26,8 @@ com.baeldung - api + remoting-http-api + ${project.version} diff --git a/spring-remoting/remoting-amqp/remoting-amqp-client/src/main/resources/logback.xml b/spring-remoting/remoting-amqp/remoting-amqp-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-remoting/remoting-amqp/remoting-amqp-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-remoting/remoting-amqp/remoting-amqp-server/pom.xml b/spring-remoting/remoting-amqp/remoting-amqp-server/pom.xml index b926fd3d79..7fe276f824 100644 --- a/spring-remoting/remoting-amqp/remoting-amqp-server/pom.xml +++ b/spring-remoting/remoting-amqp/remoting-amqp-server/pom.xml @@ -1,26 +1,22 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + + remoting-amqp-server + jar + remoting-amqp-server + http://maven.apache.org + remoting-amqp com.baeldung 1.0-SNAPSHOT - 4.0.0 - - remoting-amqp-server - jar - - remoting-amqp-server - http://maven.apache.org - - - UTF-8 - com.baeldung - api + remoting-http-api ${project.version} @@ -29,13 +25,13 @@ com.baeldung - api - 1.0-SNAPSHOT - - - com.baeldung - spring-remoting-http-server - 1.0-SNAPSHOT + remoting-http-server + ${remoting-http-server.version} + + + 1.0-SNAPSHOT + + diff --git a/spring-remoting/remoting-amqp/remoting-amqp-server/src/main/resources/logback.xml b/spring-remoting/remoting-amqp/remoting-amqp-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-remoting/remoting-amqp/remoting-amqp-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-remoting/remoting-hessian-burlap/client/pom.xml b/spring-remoting/remoting-hessian-burlap/client/pom.xml deleted file mode 100644 index 1ae9b10019..0000000000 --- a/spring-remoting/remoting-hessian-burlap/client/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - remoting-hessian-burlap - com.baeldung - 1.0-SNAPSHOT - - 4.0.0 - - spring-remoting-hessian-burlap-client - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - ${project.groupId} - api - - - com.caucho - hessian - 4.0.38 - - - - - ${project.groupId} - remoting-hessian-burlap-server - ${project.version} - test - - - javax.servlet - javax.servlet-api - test - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.boot - spring-boot-starter-tomcat - test - - - - \ No newline at end of file diff --git a/spring-remoting/remoting-hessian-burlap/pom.xml b/spring-remoting/remoting-hessian-burlap/pom.xml index 682e460880..6cb5a51812 100644 --- a/spring-remoting/remoting-hessian-burlap/pom.xml +++ b/spring-remoting/remoting-hessian-burlap/pom.xml @@ -2,19 +2,18 @@ - + 4.0.0 + remoting-hessian-burlap + pom + + spring-remoting com.baeldung 1.0-SNAPSHOT - pom + - server - client + remoting-hessian-burlap-server + remoting-hessian-burlap-client - 4.0.0 - - remoting-hessian-burlap - - \ No newline at end of file diff --git a/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/pom.xml b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/pom.xml new file mode 100644 index 0000000000..f337d5e51f --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/pom.xml @@ -0,0 +1,60 @@ + + + + remoting-hessian-burlap + com.baeldung + 1.0-SNAPSHOT + + 4.0.0 + + spring-remoting-hessian-burlap-client + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + ${project.groupId} + remoting-http-api + ${project.version} + + + com.caucho + hessian + 4.0.38 + + + + + ${project.groupId} + remoting-hessian-burlap-server + ${project.version} + test + + + javax.servlet + javax.servlet-api + test + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-tomcat + test + + + + \ No newline at end of file diff --git a/spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/BurlapClient.java b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/java/com/baeldung/client/BurlapClient.java similarity index 100% rename from spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/BurlapClient.java rename to spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/java/com/baeldung/client/BurlapClient.java diff --git a/spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/HessianClient.java b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/java/com/baeldung/client/HessianClient.java similarity index 100% rename from spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/HessianClient.java rename to spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/java/com/baeldung/client/HessianClient.java diff --git a/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/resources/logback.xml b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-remoting/remoting-hessian-burlap/client/src/test/java/com/baeldung/client/CabBookingServiceIntegrationTest.java b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/com/baeldung/client/CabBookingServiceIntegrationTest.java similarity index 100% rename from spring-remoting/remoting-hessian-burlap/client/src/test/java/com/baeldung/client/CabBookingServiceIntegrationTest.java rename to spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/com/baeldung/client/CabBookingServiceIntegrationTest.java diff --git a/spring-remoting/remoting-hessian-burlap/client/src/test/resources/application.properties b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/resources/application.properties similarity index 100% rename from spring-remoting/remoting-hessian-burlap/client/src/test/resources/application.properties rename to spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/resources/application.properties diff --git a/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/pom.xml b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/pom.xml new file mode 100644 index 0000000000..5b6e03348f --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/pom.xml @@ -0,0 +1,30 @@ + + + + remoting-hessian-burlap + com.baeldung + 1.0-SNAPSHOT + + 4.0.0 + + remoting-hessian-burlap-server + + + + com.baeldung + remoting-http-server + ${project.version} + + + org.springframework.boot + spring-boot-starter-web + + + com.caucho + hessian + 4.0.38 + + + \ No newline at end of file diff --git a/spring-remoting/remoting-hessian-burlap/server/src/main/java/com/baeldung/server/Server.java b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/main/java/com/baeldung/server/Server.java similarity index 100% rename from spring-remoting/remoting-hessian-burlap/server/src/main/java/com/baeldung/server/Server.java rename to spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/main/java/com/baeldung/server/Server.java diff --git a/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/main/resources/logback.xml b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-remoting/remoting-hessian-burlap/server/pom.xml b/spring-remoting/remoting-hessian-burlap/server/pom.xml deleted file mode 100644 index f1fed73ed8..0000000000 --- a/spring-remoting/remoting-hessian-burlap/server/pom.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - remoting-hessian-burlap - com.baeldung - 1.0-SNAPSHOT - - 4.0.0 - - remoting-hessian-burlap-server - - - - com.baeldung - spring-remoting-http-server - ${project.version} - - - org.springframework.boot - spring-boot-starter-web - - - com.caucho - hessian - 4.0.38 - - - \ No newline at end of file diff --git a/spring-remoting/remoting-http/api/pom.xml b/spring-remoting/remoting-http/api/pom.xml deleted file mode 100644 index 633217f7de..0000000000 --- a/spring-remoting/remoting-http/api/pom.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - spring-remoting-http - com.baeldung - 1.0-SNAPSHOT - - 4.0.0 - api - spring-remoting-http-api - API definition shared between client and server. - \ No newline at end of file diff --git a/spring-remoting/remoting-http/client/pom.xml b/spring-remoting/remoting-http/client/pom.xml deleted file mode 100644 index 94a536fc18..0000000000 --- a/spring-remoting/remoting-http/client/pom.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - 4.0.0 - - - com.baeldung - spring-remoting-http - 1.0-SNAPSHOT - - spring-remoting-http-client - Shows how to invoke a remote service using Spring Remoting HTTP. - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - ${project.groupId} - api - - - \ No newline at end of file diff --git a/spring-remoting/remoting-http/pom.xml b/spring-remoting/remoting-http/pom.xml index 439f6782ba..3262736ec8 100644 --- a/spring-remoting/remoting-http/pom.xml +++ b/spring-remoting/remoting-http/pom.xml @@ -3,17 +3,19 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + remoting-http + Parent for all modules related to HTTP Spring Remoting. + pom + com.baeldung spring-remoting 1.0-SNAPSHOT - spring-remoting-http - Parent for all modules related to HTTP Spring Remoting. - pom + - server - client - api + remoting-http-server + remoting-http-client + remoting-http-api \ No newline at end of file diff --git a/spring-remoting/remoting-http/remoting-http-api/pom.xml b/spring-remoting/remoting-http/remoting-http-api/pom.xml new file mode 100644 index 0000000000..579255060d --- /dev/null +++ b/spring-remoting/remoting-http/remoting-http-api/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + remoting-http-api + remoting-http-api + API definition shared between client and server. + + + remoting-http + com.baeldung + 1.0-SNAPSHOT + + + \ No newline at end of file diff --git a/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/Booking.java b/spring-remoting/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/Booking.java similarity index 100% rename from spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/Booking.java rename to spring-remoting/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/Booking.java diff --git a/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/BookingException.java b/spring-remoting/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/BookingException.java similarity index 100% rename from spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/BookingException.java rename to spring-remoting/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/BookingException.java diff --git a/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/CabBookingService.java b/spring-remoting/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/CabBookingService.java similarity index 100% rename from spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/CabBookingService.java rename to spring-remoting/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/CabBookingService.java diff --git a/spring-remoting/remoting-http/remoting-http-client/pom.xml b/spring-remoting/remoting-http/remoting-http-client/pom.xml new file mode 100644 index 0000000000..9a6e98ffdd --- /dev/null +++ b/spring-remoting/remoting-http/remoting-http-client/pom.xml @@ -0,0 +1,32 @@ + + + 4.0.0 + remoting-http-client + Shows how to invoke a remote service using Spring Remoting HTTP. + + + com.baeldung + remoting-http + 1.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + ${project.groupId} + remoting-http-api + ${project.version} + + + \ No newline at end of file diff --git a/spring-remoting/remoting-http/client/src/main/java/com/baeldug/client/Client.java b/spring-remoting/remoting-http/remoting-http-client/src/main/java/com/baeldug/client/Client.java similarity index 100% rename from spring-remoting/remoting-http/client/src/main/java/com/baeldug/client/Client.java rename to spring-remoting/remoting-http/remoting-http-client/src/main/java/com/baeldug/client/Client.java diff --git a/spring-remoting/remoting-http/remoting-http-client/src/main/resources/logback.xml b/spring-remoting/remoting-http/remoting-http-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-remoting/remoting-http/remoting-http-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-remoting/remoting-http/remoting-http-server/pom.xml b/spring-remoting/remoting-http/remoting-http-server/pom.xml new file mode 100644 index 0000000000..53d27a5efa --- /dev/null +++ b/spring-remoting/remoting-http/remoting-http-server/pom.xml @@ -0,0 +1,26 @@ + + + 4.0.0 + remoting-http-server + Shows how to expose a service using Spring Remoting HTTP. + + + com.baeldung + remoting-http + 1.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + ${project.groupId} + remoting-http-api + ${project.version} + + + \ No newline at end of file diff --git a/spring-remoting/remoting-http/server/readme.md b/spring-remoting/remoting-http/remoting-http-server/readme.md similarity index 100% rename from spring-remoting/remoting-http/server/readme.md rename to spring-remoting/remoting-http/remoting-http-server/readme.md diff --git a/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java b/spring-remoting/remoting-http/remoting-http-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java similarity index 100% rename from spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java rename to spring-remoting/remoting-http/remoting-http-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java diff --git a/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/Server.java b/spring-remoting/remoting-http/remoting-http-server/src/main/java/com/baeldung/server/Server.java similarity index 100% rename from spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/Server.java rename to spring-remoting/remoting-http/remoting-http-server/src/main/java/com/baeldung/server/Server.java diff --git a/spring-remoting/remoting-http/remoting-http-server/src/main/resources/logback.xml b/spring-remoting/remoting-http/remoting-http-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-remoting/remoting-http/remoting-http-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-remoting/remoting-http/server/pom.xml b/spring-remoting/remoting-http/server/pom.xml deleted file mode 100644 index 517f4451f7..0000000000 --- a/spring-remoting/remoting-http/server/pom.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - 4.0.0 - - com.baeldung - spring-remoting-http - 1.0-SNAPSHOT - - spring-remoting-http-server - Shows how to expose a service using Spring Remoting HTTP. - - - org.springframework.boot - spring-boot-starter-web - - - ${project.groupId} - api - - - \ No newline at end of file diff --git a/spring-remoting/remoting-jms/remoting-jms-client/pom.xml b/spring-remoting/remoting-jms/remoting-jms-client/pom.xml index 01b7bea657..ed27282a38 100644 --- a/spring-remoting/remoting-jms/remoting-jms-client/pom.xml +++ b/spring-remoting/remoting-jms/remoting-jms-client/pom.xml @@ -28,7 +28,8 @@
    com.baeldung - api + remoting-http-api + ${project.version} diff --git a/spring-remoting/remoting-jms/remoting-jms-client/src/main/resources/logback.xml b/spring-remoting/remoting-jms/remoting-jms-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-remoting/remoting-jms/remoting-jms-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-remoting/remoting-jms/remoting-jms-server/pom.xml b/spring-remoting/remoting-jms/remoting-jms-server/pom.xml index 8feac4df57..7657267f1d 100644 --- a/spring-remoting/remoting-jms/remoting-jms-server/pom.xml +++ b/spring-remoting/remoting-jms/remoting-jms-server/pom.xml @@ -28,11 +28,7 @@
    com.baeldung - api - - - com.baeldung - api + remoting-http-api ${project.version} diff --git a/spring-remoting/remoting-jms/remoting-jms-server/src/main/resources/logback.xml b/spring-remoting/remoting-jms/remoting-jms-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-remoting/remoting-jms/remoting-jms-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-remoting/remoting-rmi/pom.xml b/spring-remoting/remoting-rmi/pom.xml new file mode 100644 index 0000000000..cd15a6ec60 --- /dev/null +++ b/spring-remoting/remoting-rmi/pom.xml @@ -0,0 +1,19 @@ + + + 4.0.0 + pom + remoting-rmi + + + spring-remoting + com.baeldung + 1.0-SNAPSHOT + + + + remoting-rmi-server + remoting-rmi-client + + \ No newline at end of file diff --git a/spring-remoting/remoting-rmi/remoting-rmi-client/pom.xml b/spring-remoting/remoting-rmi/remoting-rmi-client/pom.xml new file mode 100644 index 0000000000..1e3cd4b977 --- /dev/null +++ b/spring-remoting/remoting-rmi/remoting-rmi-client/pom.xml @@ -0,0 +1,31 @@ + + + + remoting-rmi + com.baeldung + 1.0-SNAPSHOT + + 4.0.0 + + remoting-rmi-client + + + + org.springframework.boot + spring-boot-starter-activemq + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + com.baeldung + remoting-http-api + ${project.version} + + + \ No newline at end of file diff --git a/spring-remoting/spring-remoting-rmi/remoting-rmi-client/src/main/java/com/baeldung/client/RmiClient.java b/spring-remoting/remoting-rmi/remoting-rmi-client/src/main/java/com/baeldung/client/RmiClient.java similarity index 100% rename from spring-remoting/spring-remoting-rmi/remoting-rmi-client/src/main/java/com/baeldung/client/RmiClient.java rename to spring-remoting/remoting-rmi/remoting-rmi-client/src/main/java/com/baeldung/client/RmiClient.java diff --git a/spring-remoting/remoting-rmi/remoting-rmi-client/src/main/resources/logback.xml b/spring-remoting/remoting-rmi/remoting-rmi-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-remoting/remoting-rmi/remoting-rmi-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-remoting/remoting-rmi/remoting-rmi-server/pom.xml b/spring-remoting/remoting-rmi/remoting-rmi-server/pom.xml new file mode 100644 index 0000000000..68b01829e1 --- /dev/null +++ b/spring-remoting/remoting-rmi/remoting-rmi-server/pom.xml @@ -0,0 +1,36 @@ + + + + remoting-rmi + com.baeldung + 1.0-SNAPSHOT + + 4.0.0 + + remoting-rmi-server + + + UTF-8 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + com.baeldung + remoting-http-api + ${project.version} + + + + \ No newline at end of file diff --git a/spring-remoting/spring-remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java b/spring-remoting/remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java similarity index 100% rename from spring-remoting/spring-remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java rename to spring-remoting/remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java diff --git a/spring-remoting/spring-remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/RmiServer.java b/spring-remoting/remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/RmiServer.java similarity index 100% rename from spring-remoting/spring-remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/RmiServer.java rename to spring-remoting/remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/RmiServer.java diff --git a/spring-remoting/remoting-rmi/remoting-rmi-server/src/main/resources/logback.xml b/spring-remoting/remoting-rmi/remoting-rmi-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-remoting/remoting-rmi/remoting-rmi-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-remoting/spring-remoting-rmi/pom.xml b/spring-remoting/spring-remoting-rmi/pom.xml deleted file mode 100644 index 723158775f..0000000000 --- a/spring-remoting/spring-remoting-rmi/pom.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - spring-remoting - com.baeldung - 1.0-SNAPSHOT - - 4.0.0 - pom - - remoting-rmi-server - remoting-rmi-client - - spring-remoting-rmi - - - \ No newline at end of file diff --git a/spring-remoting/spring-remoting-rmi/remoting-rmi-client/pom.xml b/spring-remoting/spring-remoting-rmi/remoting-rmi-client/pom.xml deleted file mode 100644 index 003976dc7b..0000000000 --- a/spring-remoting/spring-remoting-rmi/remoting-rmi-client/pom.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - spring-remoting-rmi - com.baeldung - 1.0-SNAPSHOT - - 4.0.0 - - remoting-rmi-client - - - - org.springframework.boot - spring-boot-starter-activemq - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - com.baeldung - api - - - \ No newline at end of file diff --git a/spring-remoting/spring-remoting-rmi/remoting-rmi-server/pom.xml b/spring-remoting/spring-remoting-rmi/remoting-rmi-server/pom.xml deleted file mode 100644 index f1633e5dc2..0000000000 --- a/spring-remoting/spring-remoting-rmi/remoting-rmi-server/pom.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - spring-remoting-rmi - com.baeldung - 1.0-SNAPSHOT - - 4.0.0 - - remoting-rmi-server - - - UTF-8 - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - com.baeldung - api - - - com.baeldung - api - ${project.version} - - - - \ No newline at end of file diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml index 7f3c21801c..7aedfa486b 100644 --- a/spring-rest-angular/pom.xml +++ b/spring-rest-angular/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 spring-rest-angular spring-rest-angular @@ -9,10 +8,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-rest-angular/src/main/resources/logback.xml b/spring-rest-angular/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-rest-angular/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-rest-embedded-tomcat/pom.xml b/spring-rest-embedded-tomcat/pom.xml index 9ab9b4b718..9f6eb0d703 100644 --- a/spring-rest-embedded-tomcat/pom.xml +++ b/spring-rest-embedded-tomcat/pom.xml @@ -1,20 +1,19 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung.embedded - SpringRestTomcat + spring-rest-embedded-tomcat 0.0.1-SNAPSHOT - spring-rest-embedded-tomcat war - + com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 - + org.springframework @@ -25,7 +24,7 @@ javax.servlet javax.servlet-api - 4.0.0 + ${servlet.version} @@ -37,27 +36,27 @@ org.apache.tomcat.embed tomcat-embed-core - 9.0.1 + ${tomcat.version} test org.apache.tomcat tomcat-jasper - 9.0.1 + ${tomcat.version} test org.apache.httpcomponents httpclient - 4.5.3 + ${httpclient.version} org.apache.httpcomponents httpcore - 4.4.8 + ${httpcore.version} @@ -74,6 +73,7 @@ true **/*IntegrationTest.java + **/*IntTest.java **/*LongRunningUnitTest.java **/*ManualTest.java **/JdbcTest.java @@ -85,11 +85,13 @@ - 5.0.2.RELEASE - 2.19.1 2.9.2 1.8 1.8 + 4.0.0 + 9.0.1 + 4.5.3 + 4.4.8 false diff --git a/spring-rest-embedded-tomcat/src/main/resources/logback.xml b/spring-rest-embedded-tomcat/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-rest-embedded-tomcat/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-rest-full/README.md b/spring-rest-full/README.md index 23b0b0435b..b8fef9cb82 100644 --- a/spring-rest-full/README.md +++ b/spring-rest-full/README.md @@ -16,7 +16,6 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) - [Project Configuration with Spring](http://www.baeldung.com/project-configuration-with-spring) - [Metrics for your Spring REST API](http://www.baeldung.com/spring-rest-api-metrics) -- [Spring RestTemplate Tutorial](http://www.baeldung.com/rest-template) - [Bootstrap a Web Application with Spring 4](http://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) - [Build a REST API with Spring 4 and Java Config](http://www.baeldung.com/building-a-restful-web-service-with-spring-and-java-based-configuration) - [Error Handling for REST with Spring](http://www.baeldung.com/exception-handling-for-rest-with-spring) @@ -41,5 +40,5 @@ mysql -u root -p ### Use the REST Service ``` -curl http://localhost:8080/spring-rest-full/foos +curl http://localhost:8082/spring-rest-full/auth/foos ``` diff --git a/spring-rest-full/pom.xml b/spring-rest-full/pom.xml index fd2c485eaf..81c938a289 100644 --- a/spring-rest-full/pom.xml +++ b/spring-rest-full/pom.xml @@ -1,18 +1,17 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-rest-full 0.1-SNAPSHOT - spring-rest-full war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -26,12 +25,10 @@ org.springframework.boot spring-boot-starter-actuator - org.aspectj aspectjweaver - org.apache.tomcat.embed tomcat-embed-jasper @@ -74,7 +71,6 @@ org.springframework spring-expression - org.springframework spring-web @@ -83,7 +79,6 @@ org.springframework spring-webmvc - org.springframework.data spring-data-commons @@ -140,7 +135,6 @@ mysql-connector-java runtime - com.h2database h2 @@ -153,7 +147,6 @@ javax.servlet-api provided - javax.servlet jstl @@ -161,12 +154,10 @@ - com.fasterxml.jackson.core jackson-databind - com.thoughtworks.xstream xstream @@ -189,7 +180,6 @@ test - @@ -217,14 +207,28 @@ true - - org.apache.maven.plugins maven-war-plugin - + + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/*LiveTest.java + **/*TestSuite.java + + + org.codehaus.cargo cargo-maven2-plugin @@ -245,9 +249,7 @@ - - com.mysema.maven apt-maven-plugin @@ -264,9 +266,7 @@ - - @@ -286,6 +286,7 @@ **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java @@ -328,7 +329,6 @@ - 1.4.9 diff --git a/spring-rest-full/src/main/resources/logback.xml b/spring-rest-full/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-rest-full/src/main/resources/logback.xml +++ b/spring-rest-full/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-rest-full/src/test/java/org/baeldung/spring/ConfigIntegrationTest.java b/spring-rest-full/src/test/java/org/baeldung/spring/ConfigIntegrationTest.java new file mode 100644 index 0000000000..77603da0dd --- /dev/null +++ b/spring-rest-full/src/test/java/org/baeldung/spring/ConfigIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung.spring; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +@ComponentScan("org.baeldung.test") +public class ConfigIntegrationTest extends WebMvcConfigurerAdapter { + + public ConfigIntegrationTest() { + super(); + } + + // API + +} \ No newline at end of file diff --git a/spring-rest-full/src/test/java/org/baeldung/spring/ConfigTest.java b/spring-rest-full/src/test/java/org/baeldung/spring/ConfigTest.java deleted file mode 100644 index 56f3de6cb0..0000000000 --- a/spring-rest-full/src/test/java/org/baeldung/spring/ConfigTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.spring; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -@Configuration -@ComponentScan("org.baeldung.test") -public class ConfigTest extends WebMvcConfigurerAdapter { - - public ConfigTest() { - super(); - } - - // API - -} \ No newline at end of file diff --git a/spring-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java b/spring-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java index a899d387ab..912ad89ed7 100644 --- a/spring-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java +++ b/spring-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java @@ -8,9 +8,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; -import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Preconditions; diff --git a/spring-rest-full/src/test/java/org/baeldung/web/FooDiscoverabilityLiveTest.java b/spring-rest-full/src/test/java/org/baeldung/web/FooDiscoverabilityLiveTest.java index c0e1f9d04d..a6577e4de8 100644 --- a/spring-rest-full/src/test/java/org/baeldung/web/FooDiscoverabilityLiveTest.java +++ b/spring-rest-full/src/test/java/org/baeldung/web/FooDiscoverabilityLiveTest.java @@ -4,7 +4,7 @@ import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import org.baeldung.common.web.AbstractDiscoverabilityLiveTest; import org.baeldung.persistence.model.Foo; -import org.baeldung.spring.ConfigTest; +import org.baeldung.spring.ConfigIntegrationTest; import org.junit.runner.RunWith; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ConfigTest.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { ConfigIntegrationTest.class }, loader = AnnotationConfigContextLoader.class) @ActiveProfiles("test") public class FooDiscoverabilityLiveTest extends AbstractDiscoverabilityLiveTest { diff --git a/spring-rest-full/src/test/java/org/baeldung/web/FooLiveTest.java b/spring-rest-full/src/test/java/org/baeldung/web/FooLiveTest.java index 5a4f472fe3..65564a6845 100644 --- a/spring-rest-full/src/test/java/org/baeldung/web/FooLiveTest.java +++ b/spring-rest-full/src/test/java/org/baeldung/web/FooLiveTest.java @@ -4,7 +4,7 @@ import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import org.baeldung.common.web.AbstractBasicLiveTest; import org.baeldung.persistence.model.Foo; -import org.baeldung.spring.ConfigTest; +import org.baeldung.spring.ConfigIntegrationTest; import org.junit.runner.RunWith; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ConfigTest.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { ConfigIntegrationTest.class }, loader = AnnotationConfigContextLoader.class) @ActiveProfiles("test") public class FooLiveTest extends AbstractBasicLiveTest { diff --git a/spring-rest-full/src/test/java/org/baeldung/web/FooPageableLiveTest.java b/spring-rest-full/src/test/java/org/baeldung/web/FooPageableLiveTest.java index 62a8983356..3f637c5213 100644 --- a/spring-rest-full/src/test/java/org/baeldung/web/FooPageableLiveTest.java +++ b/spring-rest-full/src/test/java/org/baeldung/web/FooPageableLiveTest.java @@ -13,7 +13,7 @@ import java.util.List; import org.baeldung.common.web.AbstractBasicLiveTest; import org.baeldung.persistence.model.Foo; -import org.baeldung.spring.ConfigTest; +import org.baeldung.spring.ConfigIntegrationTest; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ActiveProfiles; @@ -22,7 +22,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ConfigTest.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { ConfigIntegrationTest.class }, loader = AnnotationConfigContextLoader.class) @ActiveProfiles("test") public class FooPageableLiveTest extends AbstractBasicLiveTest { diff --git a/spring-rest-hal-browser/README.md b/spring-rest-hal-browser/README.md new file mode 100644 index 0000000000..d9760c8295 --- /dev/null +++ b/spring-rest-hal-browser/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Spring REST and HAL Browser](http://www.baeldung.com/spring-rest-hal) diff --git a/spring-rest-hal-browser/pom.xml b/spring-rest-hal-browser/pom.xml new file mode 100644 index 0000000000..6c56faf0b2 --- /dev/null +++ b/spring-rest-hal-browser/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + + com.baeldung + spring-rest-hal-browser + 1.0-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + + + org.springframework.boot + spring-boot-starter-web + 2.0.3.RELEASE + + + + org.springframework.boot + spring-boot-starter-data-jpa + 2.0.3.RELEASE + + + + org.springframework.data + spring-data-rest-hal-browser + 3.0.8.RELEASE + + + + com.h2database + h2 + 1.4.197 + + + + + + + \ No newline at end of file diff --git a/spring-rest-hal-browser/src/main/java/com/baeldung/App.java b/spring-rest-hal-browser/src/main/java/com/baeldung/App.java new file mode 100644 index 0000000000..14b6c201d5 --- /dev/null +++ b/spring-rest-hal-browser/src/main/java/com/baeldung/App.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class App { + + public static void main(String[] args) { + SpringApplication.run(App.class); + } + +} diff --git a/spring-rest-hal-browser/src/main/java/com/baeldung/config/DBLoader.java b/spring-rest-hal-browser/src/main/java/com/baeldung/config/DBLoader.java new file mode 100644 index 0000000000..7251ef0e8c --- /dev/null +++ b/spring-rest-hal-browser/src/main/java/com/baeldung/config/DBLoader.java @@ -0,0 +1,108 @@ +package com.baeldung.config; + +import com.baeldung.data.BookRepository; +import com.baeldung.model.Book; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.Random; +import java.util.stream.IntStream; + +@Component +public class DBLoader implements ApplicationRunner { + + private final BookRepository bookRepository; + + @Autowired + DBLoader(BookRepository bookRepository){ + this.bookRepository = bookRepository; + } + + + public void run(ApplicationArguments applicationArguments) throws Exception { + + String[] templates = { + "Up and running with %s", + "%s Basics", + "%s for Beginners", + "%s for Neckbeards", + "Under the hood: %s", + "Discovering %s", + "A short guide to %s", + "%s with Baeldung" + }; + + String[] buzzWords = { + "Spring REST Data", + "Java 9", + "Scala", + "Groovy", + "Hibernate", + "Spring HATEOS", + "The HAL Browser", + "Spring webflux", + }; + + String[] authorFirstName = { + "John %s", + "Steve %s", + "Samantha %s", + "Gale %s", + "Tom %s" + }; + + String[] authorLastName = { + "Giles", + "Gill", + "Smith", + "Armstrong" + }; + + String[] blurbs = { + "It was getting dark when the %s %s" , + "Scott was nearly there when he heard that a %s %s", + "Diana was a lovable Java coder until the %s %s", + "The gripping story of a small %s and the day it %s" + }; + + String[] blublMiddles = { + "distaster", + "dog", + "cat", + "turtle", + "hurricane" + }; + + String[] end = { + "hit the school", + "memorised pi to 100 decimal places!", + "became a world champion armwrestler", + "became a Java REST master!!" + }; + + Random random = new Random(); + + IntStream.range(0, 100) + .forEach(i -> { + String template = templates[i % templates.length]; + String buzzword = buzzWords[i % buzzWords.length]; + String blurbStart = blurbs[i % blurbs.length]; + String middle = blublMiddles[i % blublMiddles.length]; + String ending = end[i % end.length]; + String blurb = String.format(blurbStart, middle, ending); + String firstName = authorFirstName[i % authorFirstName.length]; + String lastname = authorLastName[i % authorLastName.length]; + Book book = new Book(String.format(template, buzzword), String.format(firstName, lastname), blurb, random.nextInt(1000-200) + 200); + + bookRepository.save(book); + + System.out.println(book); + + }); + + + + } +} diff --git a/spring-rest-hal-browser/src/main/java/com/baeldung/config/RestConfig.java b/spring-rest-hal-browser/src/main/java/com/baeldung/config/RestConfig.java new file mode 100644 index 0000000000..858371facc --- /dev/null +++ b/spring-rest-hal-browser/src/main/java/com/baeldung/config/RestConfig.java @@ -0,0 +1,23 @@ +package com.baeldung.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Lazy; +import org.springframework.data.rest.core.event.ValidatingRepositoryEventListener; +import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter; +import org.springframework.validation.Validator; + +@Configuration +public class RestConfig extends RepositoryRestConfigurerAdapter { + + //access to global validator + @Autowired + @Lazy + private Validator validator; + + @Override + public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) { + validatingListener.addValidator("beforeCreate", validator ); + validatingListener.addValidator("beforeSave", validator); + } +} diff --git a/spring-rest-hal-browser/src/main/java/com/baeldung/data/BookRepository.java b/spring-rest-hal-browser/src/main/java/com/baeldung/data/BookRepository.java new file mode 100644 index 0000000000..d8e35974b1 --- /dev/null +++ b/spring-rest-hal-browser/src/main/java/com/baeldung/data/BookRepository.java @@ -0,0 +1,21 @@ +package com.baeldung.data; + +import com.baeldung.model.Book; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.data.rest.core.annotation.RestResource; +import org.springframework.stereotype.Repository; + +@Repository +public interface BookRepository extends PagingAndSortingRepository { + + @RestResource(rel = "title-contains", path="title-contains") + Page findByTitleContaining(@Param("query") String query, Pageable page); + + @RestResource(rel = "author-contains", path="author-contains", exported = false) + Page findByAuthorContaining(@Param("query") String query, Pageable page); + +} diff --git a/spring-rest-hal-browser/src/main/java/com/baeldung/model/Book.java b/spring-rest-hal-browser/src/main/java/com/baeldung/model/Book.java new file mode 100644 index 0000000000..b1dc1b41f3 --- /dev/null +++ b/spring-rest-hal-browser/src/main/java/com/baeldung/model/Book.java @@ -0,0 +1,86 @@ +package com.baeldung.model; + +import javax.persistence.*; +import javax.validation.constraints.NotNull; + +@Entity +public class Book { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + @NotNull + @Column(columnDefinition = "VARCHAR", length = 100) + private String title; + + @NotNull + @Column(columnDefinition = "VARCHAR", length = 100) + private String author; + + @Column(columnDefinition = "VARCHAR", length = 1000) + private String blurb; + + private int pages; + + public Book() { + } + + public Book(@NotNull String title, @NotNull String author, String blurb, int pages) { + this.title = title; + this.author = author; + this.blurb = blurb; + this.pages = pages; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getBlurb() { + return blurb; + } + + public void setBlurb(String blurb) { + this.blurb = blurb; + } + + public int getPages() { + return pages; + } + + public void setPages(int pages) { + this.pages = pages; + } + + @Override + public String toString() { + return "Book{" + + "id=" + id + + ", title='" + title + '\'' + + ", author='" + author + '\'' + + ", blurb='" + blurb + '\'' + + ", pages=" + pages + + '}'; + } +} diff --git a/spring-rest-hal-browser/src/main/resources/application.properties b/spring-rest-hal-browser/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-rest-hal-browser/src/main/resources/logback.xml b/spring-rest-hal-browser/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-rest-hal-browser/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-rest-query-language/pom.xml b/spring-rest-query-language/pom.xml index d20a97268b..8b24c7b8fb 100644 --- a/spring-rest-query-language/pom.xml +++ b/spring-rest-query-language/pom.xml @@ -1,18 +1,17 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-rest-query-language 0.1-SNAPSHOT - spring-rest-query-language war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -31,7 +30,6 @@ org.aspectj aspectjweaver - org.apache.tomcat.embed tomcat-embed-jasper @@ -74,7 +72,6 @@ org.springframework spring-expression - org.springframework spring-web @@ -83,7 +80,6 @@ org.springframework spring-webmvc - org.springframework.data spring-data-commons @@ -305,6 +301,7 @@ **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java diff --git a/spring-rest-query-language/src/main/resources/logback.xml b/spring-rest-query-language/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-rest-query-language/src/main/resources/logback.xml +++ b/spring-rest-query-language/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-rest-shell/pom.xml b/spring-rest-shell/pom.xml index fe255b397f..2f7d1c8933 100644 --- a/spring-rest-shell/pom.xml +++ b/spring-rest-shell/pom.xml @@ -1,29 +1,21 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-rest-shell 0.0.1-SNAPSHOT jar - spring-rest-shell A simple project to demonstrate Spring REST Shell features. - org.springframework.boot - spring-boot-starter-parent - 1.5.8.RELEASE - + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-1 - - UTF-8 - UTF-8 - 1.8 - - @@ -56,5 +48,10 @@ + + UTF-8 + UTF-8 + 1.8 + diff --git a/spring-rest-shell/src/main/resources/logback.xml b/spring-rest-shell/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-rest-shell/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-rest-simple/README.md b/spring-rest-simple/README.md index 982e16d5a5..57d6f50887 100644 --- a/spring-rest-simple/README.md +++ b/spring-rest-simple/README.md @@ -6,3 +6,4 @@ - [Spring RequestMapping](http://www.baeldung.com/spring-requestmapping) - [ETags for REST with Spring](http://www.baeldung.com/etags-for-rest-with-spring) - [Spring and Apache FileUpload](http://www.baeldung.com/spring-apache-file-upload) +- [Test a REST API with curl](http://www.baeldung.com/curl-rest) diff --git a/spring-rest-simple/pom.xml b/spring-rest-simple/pom.xml index 1c6c6e1044..d39e3a43c1 100644 --- a/spring-rest-simple/pom.xml +++ b/spring-rest-simple/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-rest-simple @@ -8,15 +8,15 @@ war - org.springframework.boot - spring-boot-starter-parent - 1.4.3.RELEASE + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-1 - org.springframework.boot spring-boot-starter-thymeleaf @@ -31,11 +31,11 @@ org.springframework.boot - spring-boot-test + spring-boot-starter-test + test - org.springframework spring-web @@ -54,7 +54,6 @@ org.springframework spring-oxm - commons-fileupload commons-fileupload @@ -67,7 +66,6 @@ javax.servlet-api provided - javax.servlet jstl @@ -80,12 +78,10 @@ com.fasterxml.jackson.core jackson-databind - com.fasterxml.jackson.dataformat jackson-dataformat-xml - com.thoughtworks.xstream xstream @@ -99,7 +95,6 @@ guava ${guava.version} - org.apache.commons commons-lang3 @@ -138,7 +133,6 @@ junit test - org.hamcrest hamcrest-core @@ -149,25 +143,20 @@ hamcrest-library test - org.mockito mockito-core test - org.springframework spring-test - com.jayway.restassured rest-assured - ${rest-assured.version} + ${jayway-rest-assured.version} - - com.google.protobuf protobuf-java @@ -178,18 +167,15 @@ protobuf-java-format ${protobuf-java-format.version} - com.esotericsoftware kryo ${kryo.version} - com.jayway.jsonpath json-path - @@ -200,47 +186,13 @@ true - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.7.0 - - 1.8 - 1.8 - - - - - org.apache.maven.plugins - maven-war-plugin - - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - - **/*IntegrationTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/JdbcTest.java - **/*LiveTest.java - - - - - org.codehaus.cargo cargo-maven2-plugin ${cargo-maven2-plugin.version} - true + tomcat8x embedded @@ -255,17 +207,34 @@ - - - integration + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + org.apache.maven.plugins maven-surefire-plugin @@ -281,16 +250,16 @@ **/*IntegrationTest.java + **/*IntTest.java - - + live @@ -343,7 +312,6 @@ - @@ -356,7 +324,7 @@ 20.0 - 2.9.0 + 2.9.0 1.6.0 diff --git a/spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java index ec92ad8349..309a36609a 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java @@ -1,8 +1,5 @@ package org.baeldung.config; -import java.text.SimpleDateFormat; -import java.util.List; - import org.baeldung.config.converter.KryoHttpMessageConverter; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @@ -19,6 +16,9 @@ import org.springframework.web.servlet.config.annotation.ContentNegotiationConfi import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import java.text.SimpleDateFormat; +import java.util.List; + /* * Please note that main web configuration is in src/main/webapp/WEB-INF/api-servlet.xml */ diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java index 3c7e5ed13c..bf26eb3292 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java @@ -45,4 +45,19 @@ public class FooController { .setName("Foo Name") .build(); } + + @RequestMapping(method = RequestMethod.POST, value = "/foos/new") + @ResponseStatus(HttpStatus.OK) + @ResponseBody + public Foo createFoo(@RequestBody final Foo foo) { + return foo; + } + + @RequestMapping(method = RequestMethod.DELETE, value = "/foos/{id}") + @ResponseStatus(HttpStatus.OK) + @ResponseBody + public long deleteFoo(@PathVariable final long id) { + return id; + } + } diff --git a/spring-rest-simple/src/main/resources/logback.xml b/spring-rest-simple/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-rest-simple/src/main/resources/logback.xml +++ b/spring-rest-simple/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-rest-simple/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java b/spring-rest-simple/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java deleted file mode 100644 index 40e93f2d89..0000000000 --- a/spring-rest-simple/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.baeldung.client; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; - -import java.io.IOException; - -import org.baeldung.web.dto.Foo; -import org.junit.Before; -import org.junit.Test; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.client.RestTemplate; - -public class RestTemplateBasicLiveTest { - - private RestTemplate restTemplate; - - private static final String fooResourceUrl = String.format("http://localhost:%d/spring-rest/foos", 8082); - - @Before - public void beforeTest() { - restTemplate = new RestTemplate(); - } - - // GET - - @Test - public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException { - final ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); - - assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); - } - - @Test - public void givenResourceUrl_whenRetrievingResource_thenCorrect() throws IOException { - final Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class); - - assertThat(foo.getName(), notNullValue()); - assertThat(foo.getId(), is(1L)); - } - - // PUT - - @Test - public void givenFooService_whenPutObject_thenUpdatedObjectIsReturned() { - final HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); - final Foo foo = new Foo(1, "newName"); - final String resourceUrl = fooResourceUrl + "/1"; - final HttpEntity requestUpdate = new HttpEntity<>(foo, headers); - final ResponseEntity response = restTemplate.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Foo.class); - - assertThat(foo.getName(), is(response.getBody() - .getName())); - } - -} diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java b/spring-rest-simple/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java index e29bef501e..7f78146b84 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java +++ b/spring-rest-simple/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java @@ -8,6 +8,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.client.AutoConfigureWebClient; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @@ -18,6 +19,7 @@ import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = WebConfig.class) @WebAppConfiguration +@AutoConfigureWebClient public class ExampleControllerIntegrationTest { private MockMvc mockMvc; diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java b/spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java index 266ee1938b..dfb3ff7a38 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java +++ b/spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java @@ -15,6 +15,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.client.AutoConfigureWebClient; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @@ -26,6 +27,7 @@ import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = WebConfig.class) @WebAppConfiguration +@AutoConfigureWebClient public class BazzNewMappingsExampleIntegrationTest { private MockMvc mockMvc; diff --git a/spring-rest-template/.gitignore b/spring-rest-template/.gitignore new file mode 100644 index 0000000000..afdfaa6ded --- /dev/null +++ b/spring-rest-template/.gitignore @@ -0,0 +1,14 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +*/.idea/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/spring-rest-template/README.md b/spring-rest-template/README.md new file mode 100644 index 0000000000..d69d5c01c7 --- /dev/null +++ b/spring-rest-template/README.md @@ -0,0 +1,7 @@ +## Spring REST Template Example Project + +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: +- [Uploading MultipartFile with Spring RestTemplate](http://www.baeldung.com/spring-rest-template-multipart-upload) diff --git a/spring-rest-template/checkstyle.xml b/spring-rest-template/checkstyle.xml new file mode 100644 index 0000000000..85063a7570 --- /dev/null +++ b/spring-rest-template/checkstyle.xml @@ -0,0 +1,11 @@ + + + + + + + + + \ No newline at end of file diff --git a/spring-rest-template/pom.xml b/spring-rest-template/pom.xml new file mode 100644 index 0000000000..fa93308cf5 --- /dev/null +++ b/spring-rest-template/pom.xml @@ -0,0 +1,83 @@ + + 4.0.0 + com.baeldung + spring-rest-template + 0.1-SNAPSHOT + spring-rest-template + jar + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + + + org.springframework + spring-web + + + commons-logging + commons-logging + + + + + + + spring-rest-template + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${checkstyle-maven-plugin.version} + + checkstyle.xml + + + + + check + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/*LiveTest.java + + + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${checkstyle-maven-plugin.version} + + checkstyle.xml + + + + + + + + 3.0.0 + + diff --git a/spring-rest-template/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java b/spring-rest-template/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java new file mode 100644 index 0000000000..804013d4dc --- /dev/null +++ b/spring-rest-template/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java @@ -0,0 +1,62 @@ +package com.baeldung.web.upload.client; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +public class MultipartFileUploadClient { + + public static void main(String[] args) throws IOException { + uploadSingleFile(); + uploadMultipleFile(); + } + + private static void uploadSingleFile() throws IOException { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.MULTIPART_FORM_DATA); + + MultiValueMap body = new LinkedMultiValueMap<>(); + body.add("file", getTestFile()); + + + HttpEntity> requestEntity = new HttpEntity<>(body, headers); + String serverUrl = "http://localhost:8082/spring-rest/fileserver/singlefileupload/"; + RestTemplate restTemplate = new RestTemplate(); + ResponseEntity response = restTemplate.postForEntity(serverUrl, requestEntity, String.class); + System.out.println("Response code: " + response.getStatusCode()); + } + + private static void uploadMultipleFile() throws IOException { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.MULTIPART_FORM_DATA); + + MultiValueMap body = new LinkedMultiValueMap<>(); + body.add("files", getTestFile()); + body.add("files", getTestFile()); + body.add("files", getTestFile()); + + HttpEntity> requestEntity = new HttpEntity<>(body, headers); + String serverUrl = "http://localhost:8082/spring-rest/fileserver/multiplefileupload/"; + RestTemplate restTemplate = new RestTemplate(); + ResponseEntity response = restTemplate.postForEntity(serverUrl, requestEntity, String.class); + System.out.println("Response code: " + response.getStatusCode()); + } + + public static Resource getTestFile() throws IOException { + Path testFile = Files.createTempFile("test-file", ".txt"); + System.out.println("Creating and Uploading Test File: " + testFile); + Files.write(testFile, "Hello World !!, This is a test file.".getBytes()); + return new FileSystemResource(testFile.toFile()); + } + +} diff --git a/spring-rest-template/src/main/resources/logback.xml b/spring-rest-template/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-rest-template/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-rest/README.md b/spring-rest/README.md index 83cb450564..d449a4d92a 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -1,6 +1,6 @@ ## Spring REST Example Project -###The Course +### The Course The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: @@ -14,7 +14,12 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Introduction to FindBugs](http://www.baeldung.com/intro-to-findbugs) - [A Custom Media Type for a Spring REST API](http://www.baeldung.com/spring-rest-custom-media-type) - [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) - [Introduction to CheckStyle](http://www.baeldung.com/checkstyle-java) +- [How to Change the Default Port in Spring Boot](http://www.baeldung.com/spring-boot-change-port) +- [Guide to DeferredResult in Spring](http://www.baeldung.com/spring-deferred-result) +- [Spring Custom Property Editor](http://www.baeldung.com/spring-mvc-custom-property-editor) +- [Using the Spring RestTemplate Interceptor](http://www.baeldung.com/spring-rest-template-interceptor) +- [Get and Post Lists of Objects with RestTemplate](http://www.baeldung.com/spring-rest-template-list) +- [How to Set a Header on a Response with Spring 5](http://www.baeldung.com/spring-response-header) diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index d56eb9949b..ba74d26c35 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -1,7 +1,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-rest 0.1-SNAPSHOT spring-rest @@ -17,8 +16,7 @@ - - + org.springframework.boot spring-boot-starter-web @@ -40,7 +38,6 @@ - org.springframework spring-web @@ -59,14 +56,13 @@ org.springframework spring-oxm - commons-fileupload commons-fileupload ${commons-fileupload.version} - + javax.servlet javax.servlet-api @@ -80,7 +76,6 @@ - com.fasterxml.jackson.core jackson-databind @@ -98,21 +93,17 @@ - com.google.guava guava ${guava.version} - org.apache.commons commons-lang3 - ${commons-lang3.version} - com.squareup.okhttp3 okhttp @@ -120,7 +111,6 @@ - org.hamcrest hamcrest-core @@ -131,13 +121,11 @@ hamcrest-library test - org.mockito mockito-core test - org.springframework spring-test @@ -154,36 +142,30 @@ protobuf-java-format ${protobuf-java-format.version} - com.esotericsoftware kryo ${kryo.version} - com.jayway.jsonpath json-path - commons-io commons-io 2.4 - au.com.dius pact-jvm-provider-junit_2.11 ${pact.version} - io.rest-assured rest-assured - ${rest-assured.version} @@ -209,27 +191,6 @@ org.apache.maven.plugins maven-war-plugin - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - - tomcat8x - embedded - - - - - - - 8082 - - - - - org.apache.maven.plugins maven-checkstyle-plugin @@ -245,22 +206,7 @@ - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - - **/*IntegrationTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/*LiveTest.java - - - - @@ -352,7 +298,6 @@ 3.4.1 2.2.0 - 3.5.11 3.1.0 diff --git a/spring-rest/src/main/java/com/baeldung/responseheaders/ResponseHeadersApplication.java b/spring-rest/src/main/java/com/baeldung/responseheaders/ResponseHeadersApplication.java new file mode 100644 index 0000000000..ebc18a130b --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/responseheaders/ResponseHeadersApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.responseheaders; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.ServletComponentScan; + +@ServletComponentScan +@SpringBootApplication +public class ResponseHeadersApplication { + + public static void main(String[] args) { + SpringApplication.run(ResponseHeadersApplication.class, args); + } +} diff --git a/spring-rest/src/main/java/com/baeldung/responseheaders/controllers/FilterResponseHeaderController.java b/spring-rest/src/main/java/com/baeldung/responseheaders/controllers/FilterResponseHeaderController.java new file mode 100644 index 0000000000..c92d4afafd --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/responseheaders/controllers/FilterResponseHeaderController.java @@ -0,0 +1,24 @@ +package com.baeldung.responseheaders.controllers; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/filter-response-header") +public class FilterResponseHeaderController { + + @GetMapping("/no-extra-header") + public String FilterHeaderResponseWithNoExtraHeader() { + return "Response body with Filter header and no extra header"; + } + + @GetMapping("/extra-header") + public String FilterHeaderResponseWithExtraHeader(HttpServletResponse response) { + response.addHeader("Baeldung-Example-Header", "Value-ExtraHeader"); + return "Response body with Filter header and one extra header"; + } + +} diff --git a/spring-rest/src/main/java/com/baeldung/responseheaders/controllers/ResponseHeaderController.java b/spring-rest/src/main/java/com/baeldung/responseheaders/controllers/ResponseHeaderController.java new file mode 100644 index 0000000000..d93964b815 --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/responseheaders/controllers/ResponseHeaderController.java @@ -0,0 +1,70 @@ +package com.baeldung.responseheaders.controllers; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/single-response-header") +public class ResponseHeaderController { + + @GetMapping("/http-servlet-response") + public String usingHttpServletResponse(HttpServletResponse response) { + response.addHeader("Baeldung-Example-Header", "Value-HttpServletResponse"); + return "Response with header using HttpServletResponse"; + } + + @GetMapping("/response-entity-constructor") + public ResponseEntity usingResponseEntityConstructor() { + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.set("Baeldung-Example-Header", "Value-ResponseEntityContructor"); + String responseBody = "Response with header using ResponseEntity (constructor)"; + HttpStatus responseStatus = HttpStatus.OK; + + return new ResponseEntity(responseBody, responseHeaders, responseStatus); + } + + @GetMapping("/response-entity-contructor-multiple-headers") + public ResponseEntity usingResponseEntityConstructorAndMultipleHeaders() { + List acceptableMediaTypes = new ArrayList<>(Arrays.asList(MediaType.APPLICATION_JSON)); + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.set("Baeldung-Example-Header", "Value-ResponseEntityConstructorAndHeaders"); + responseHeaders.setAccept(acceptableMediaTypes); + String responseBody = "Response with header using ResponseEntity (constructor)"; + HttpStatus responseStatus = HttpStatus.OK; + + return new ResponseEntity(responseBody, responseHeaders, responseStatus); + } + + @GetMapping("/response-entity-builder") + public ResponseEntity usingResponseEntityBuilder() { + String responseHeaderKey = "Baeldung-Example-Header"; + String responseHeaderValue = "Value-ResponseEntityBuilder"; + String responseBody = "Response with header using ResponseEntity (builder)"; + + return ResponseEntity.ok() + .header(responseHeaderKey, responseHeaderValue) + .body(responseBody); + } + + @GetMapping("/response-entity-builder-with-http-headers") + public ResponseEntity usingResponseEntityBuilderAndHttpHeaders() { + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.set("Baeldung-Example-Header", "Value-ResponseEntityBuilderWithHttpHeaders"); + String responseBody = "Response with header using ResponseEntity (builder)"; + + return ResponseEntity.ok() + .headers(responseHeaders) + .body(responseBody); + } +} diff --git a/spring-rest/src/main/java/com/baeldung/responseheaders/filter/AddResponseHeaderFilter.java b/spring-rest/src/main/java/com/baeldung/responseheaders/filter/AddResponseHeaderFilter.java new file mode 100644 index 0000000000..7d4ffb1391 --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/responseheaders/filter/AddResponseHeaderFilter.java @@ -0,0 +1,41 @@ +package com.baeldung.responseheaders.filter; + +import java.io.IOException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.annotation.WebFilter; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@WebFilter("/filter-response-header/*") +public class AddResponseHeaderFilter implements Filter { + + private static final Logger LOGGER = LoggerFactory.getLogger(AddResponseHeaderFilter.class); + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + // add special initialization requirements here + LOGGER.trace("Initializing filter..."); + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletResponse httpServletResponse = (HttpServletResponse) response; + httpServletResponse.setHeader("Baeldung-Example-Filter-Header", "Value-Filter"); + chain.doFilter(request, response); + } + + @Override + public void destroy() { + // clean up any resource being held by the filter here + LOGGER.trace("Destroying filter..."); + } + +} diff --git a/spring-rest/src/main/java/com/baeldung/web/upload/app/Application.java b/spring-rest/src/main/java/com/baeldung/web/upload/app/Application.java new file mode 100644 index 0000000000..d6821196eb --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/upload/app/Application.java @@ -0,0 +1,17 @@ +package com.baeldung.web.upload.app; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.ComponentScan; + +@EnableAutoConfiguration +@ComponentScan("com.baeldung.web.upload") +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + public static void main(final String[] args) { + SpringApplication.run(Application.class, args); + } +} \ No newline at end of file diff --git a/spring-rest/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java b/spring-rest/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java new file mode 100644 index 0000000000..547aec17a0 --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java @@ -0,0 +1,61 @@ +package com.baeldung.web.upload.client; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +public class MultipartFileUploadClient { + + public static void main(String[] args) throws IOException { + uploadSingleFile(); + uploadMultipleFile(); + } + + private static void uploadSingleFile() throws IOException { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.MULTIPART_FORM_DATA); + + MultiValueMap body = new LinkedMultiValueMap<>(); + body.add("file", getTestFile()); + + + HttpEntity> requestEntity = new HttpEntity<>(body, headers); + String serverUrl = "http://localhost:8082/spring-rest/fileserver/singlefileupload/"; + RestTemplate restTemplate = new RestTemplate(); + ResponseEntity response = restTemplate.postForEntity(serverUrl, requestEntity, String.class); + System.out.println("Response code: " + response.getStatusCode()); + } + + private static void uploadMultipleFile() throws IOException { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.MULTIPART_FORM_DATA); + + MultiValueMap body = new LinkedMultiValueMap<>(); + body.add("files", getTestFile()); + body.add("files", getTestFile()); + body.add("files", getTestFile()); + + HttpEntity> requestEntity = new HttpEntity<>(body, headers); + String serverUrl = "http://localhost:8082/spring-rest/fileserver/multiplefileupload/"; + RestTemplate restTemplate = new RestTemplate(); + ResponseEntity response = restTemplate.postForEntity(serverUrl, requestEntity, String.class); + System.out.println("Response code: " + response.getStatusCode()); + } + + public static Resource getTestFile() throws IOException { + Path testFile = Files.createTempFile("test-file", ".txt"); + System.out.println("Creating and Uploading Test File: " + testFile); + Files.write(testFile, "Hello World !!, This is a test file.".getBytes()); + return new FileSystemResource(testFile.toFile()); + } +} diff --git a/spring-rest/src/main/java/com/baeldung/web/upload/controller/FileServerResource.java b/spring-rest/src/main/java/com/baeldung/web/upload/controller/FileServerResource.java new file mode 100644 index 0000000000..3863a8f20d --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/upload/controller/FileServerResource.java @@ -0,0 +1,43 @@ +package com.baeldung.web.upload.controller; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.util.List; + +@RestController +@RequestMapping("/fileserver") +public class FileServerResource { + + @RequestMapping(path = "/singlefileupload/", method = RequestMethod.POST) + public ResponseEntity processFile(@RequestParam("file") MultipartFile file) throws IOException { + + byte[] bytes = file.getBytes(); + + System.out.println("File Name: " + file.getOriginalFilename()); + System.out.println("File Content Type: " + file.getContentType()); + System.out.println("File Content:\n" + new String(bytes)); + + return (new ResponseEntity<>("Successful", null, HttpStatus.OK)); + } + + @RequestMapping(path = "/multiplefileupload/", method = RequestMethod.POST) + public ResponseEntity processFile(@RequestParam("files") List files) throws IOException { + + for (MultipartFile file : files) { + byte[] bytes = file.getBytes(); + + System.out.println("File Name: " + file.getOriginalFilename()); + System.out.println("File Content Type: " + file.getContentType()); + System.out.println("File Content:\n" + new String(bytes)); + } + + return (new ResponseEntity<>("Successful", null, HttpStatus.OK)); + } +} \ No newline at end of file diff --git a/spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java b/spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java index 3619f43f8a..8743af20fe 100644 --- a/spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java +++ b/spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java @@ -3,12 +3,10 @@ package org.baeldung.config; import java.util.ArrayList; import java.util.List; -import org.baeldung.interceptors.RestTemplateLoggingInterceptor; +import org.baeldung.interceptors.RestTemplateHeaderModifierInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.http.client.BufferingClientHttpRequestFactory; import org.springframework.http.client.ClientHttpRequestInterceptor; -import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.util.CollectionUtils; import org.springframework.web.client.RestTemplate; @@ -17,13 +15,13 @@ public class RestClientConfig { @Bean public RestTemplate restTemplate() { - RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())); + RestTemplate restTemplate = new RestTemplate(); List interceptors = restTemplate.getInterceptors(); if (CollectionUtils.isEmpty(interceptors)) { interceptors = new ArrayList(); } - interceptors.add(new RestTemplateLoggingInterceptor()); + interceptors.add(new RestTemplateHeaderModifierInterceptor()); restTemplate.setInterceptors(interceptors); return restTemplate; } diff --git a/spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateHeaderModifierInterceptor.java b/spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateHeaderModifierInterceptor.java new file mode 100644 index 0000000000..fabb904634 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateHeaderModifierInterceptor.java @@ -0,0 +1,18 @@ +package org.baeldung.interceptors; + +import java.io.IOException; + +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; + +public class RestTemplateHeaderModifierInterceptor implements ClientHttpRequestInterceptor { + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + ClientHttpResponse response = execution.execute(request, body); + response.getHeaders().add("Foo", "bar"); + return response; + } +} diff --git a/spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateLoggingInterceptor.java b/spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateLoggingInterceptor.java deleted file mode 100644 index 03a9cdc806..0000000000 --- a/spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateLoggingInterceptor.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.baeldung.interceptors; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.http.HttpRequest; -import org.springframework.http.client.ClientHttpRequestExecution; -import org.springframework.http.client.ClientHttpRequestInterceptor; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.util.StreamUtils; - -public class RestTemplateLoggingInterceptor implements ClientHttpRequestInterceptor { - - @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { - logRequest(body); - ClientHttpResponse response = execution.execute(request, body); - logResponse(response); - response.getHeaders().add("Foo", "bar"); - return response; - } - - private void logRequest(byte[] body) { - if (body.length > 0) { - String payLoad = new String(body, StandardCharsets.UTF_8); - System.out.println(payLoad); - } - } - - private void logResponse(ClientHttpResponse response) throws IOException { - long contentLength = response.getHeaders() - .getContentLength(); - if (contentLength != 0) { - String payLoad = StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8); - System.out.println(payLoad); - } - } -} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/EmployeeApplication.java b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/EmployeeApplication.java new file mode 100644 index 0000000000..baaa4c4d80 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/EmployeeApplication.java @@ -0,0 +1,16 @@ +package org.baeldung.resttemplate.lists; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * Sample application used to demonstrate working with Lists and RestTemplate. + */ +@SpringBootApplication +public class EmployeeApplication +{ + public static void main(String[] args) + { + SpringApplication.run(EmployeeApplication.class, args); + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/client/EmployeeClient.java b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/client/EmployeeClient.java new file mode 100644 index 0000000000..729fa3ca3e --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/client/EmployeeClient.java @@ -0,0 +1,100 @@ +package org.baeldung.resttemplate.lists.client; + +import org.baeldung.resttemplate.lists.dto.Employee; +import org.baeldung.resttemplate.lists.dto.EmployeeList; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.*; +import org.springframework.web.client.RestTemplate; + +import java.util.ArrayList; +import java.util.List; + +/** + * Application that shows how to use Lists with RestTemplate. + */ +public class EmployeeClient +{ + public static void main(String[] args) + { + EmployeeClient employeeClient = new EmployeeClient(); + + System.out.println("Calling GET using ParameterizedTypeReference"); + employeeClient.getAllEmployeesUsingParameterizedTypeReference(); + + System.out.println("Calling GET using wrapper class"); + employeeClient.getAllEmployeesUsingWrapperClass(); + + System.out.println("Calling POST using normal lists"); + employeeClient.createEmployeesUsingLists(); + + System.out.println("Calling POST using wrapper class"); + employeeClient.createEmployeesUsingWrapperClass(); + } + + public EmployeeClient() + { + + } + + public List getAllEmployeesUsingParameterizedTypeReference() + { + RestTemplate restTemplate = new RestTemplate(); + + ResponseEntity> response = + restTemplate.exchange( + "http://localhost:8080/spring-rest/employees/", + HttpMethod.GET, + null, + new ParameterizedTypeReference>(){}); + + List employees = response.getBody(); + + employees.forEach(e -> System.out.println(e)); + + return employees; + } + + public List getAllEmployeesUsingWrapperClass() + { + RestTemplate restTemplate = new RestTemplate(); + + EmployeeList response = + restTemplate.getForObject( + "http://localhost:8080/spring-rest/employees/v2", + EmployeeList.class); + + List employees = response.getEmployees(); + + employees.forEach(e -> System.out.println(e)); + + return employees; + } + + public void createEmployeesUsingLists() + { + RestTemplate restTemplate = new RestTemplate(); + + List newEmployees = new ArrayList<>(); + newEmployees.add(new Employee(3, "Intern")); + newEmployees.add(new Employee(4, "CEO")); + + restTemplate.postForObject( + "http://localhost:8080/spring-rest/employees/", + newEmployees, + ResponseEntity.class); + } + + public void createEmployeesUsingWrapperClass() + { + RestTemplate restTemplate = new RestTemplate(); + + List newEmployees = new ArrayList<>(); + newEmployees.add(new Employee(3, "Intern")); + newEmployees.add(new Employee(4, "CEO")); + + restTemplate.postForObject( + "http://localhost:8080/spring-rest/employees/v2/", + new EmployeeList(newEmployees), + ResponseEntity.class); + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/controller/EmployeeResource.java b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/controller/EmployeeResource.java new file mode 100644 index 0000000000..f051c6a78b --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/controller/EmployeeResource.java @@ -0,0 +1,45 @@ +package org.baeldung.resttemplate.lists.controller; + +import org.baeldung.resttemplate.lists.dto.Employee; +import org.baeldung.resttemplate.lists.dto.EmployeeList; +import org.baeldung.resttemplate.lists.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/employees") +public class EmployeeResource +{ + @Autowired + private EmployeeService employeeService; + + @RequestMapping(method = RequestMethod.GET, path = "/") + public List getEmployees() + { + return employeeService.getAllEmployees(); + } + + @RequestMapping(method = RequestMethod.GET, path = "/v2") + public EmployeeList getEmployeesUsingWrapperClass() + { + List employees = employeeService.getAllEmployees(); + return new EmployeeList(employees); + } + + @RequestMapping(method = RequestMethod.POST, path = "/") + public void addEmployees(@RequestBody List employees) + { + employeeService.addEmployees(employees); + } + + @RequestMapping(method = RequestMethod.POST, path = "/v2") + public void addEmployeesUsingWrapperClass(@RequestBody EmployeeList employeeWrapper) + { + employeeService.addEmployees(employeeWrapper.getEmployees()); + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/Employee.java b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/Employee.java new file mode 100644 index 0000000000..bd8ebbf969 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/Employee.java @@ -0,0 +1,40 @@ +package org.baeldung.resttemplate.lists.dto; + +public class Employee { + + public long id; + public String title; + + public Employee() + { + + } + + public Employee(long id, String title) + { + this.id = id; + this.title = title; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + @Override + public String toString() + { + return "Employee #" + id + "[" + title + "]"; + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/EmployeeList.java b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/EmployeeList.java new file mode 100644 index 0000000000..2bb86ac5b4 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/EmployeeList.java @@ -0,0 +1,29 @@ +package org.baeldung.resttemplate.lists.dto; + +import java.util.ArrayList; +import java.util.List; + +public class EmployeeList +{ + public List employees; + + public EmployeeList() + { + employees = new ArrayList<>(); + } + + public EmployeeList(List employees) + { + this.employees = employees; + } + + public void setEmployees(List employees) + { + this.employees = employees; + } + + public List getEmployees() + { + return employees; + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/service/EmployeeService.java b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/service/EmployeeService.java new file mode 100644 index 0000000000..08196dda77 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/service/EmployeeService.java @@ -0,0 +1,24 @@ +package org.baeldung.resttemplate.lists.service; + +import org.baeldung.resttemplate.lists.dto.Employee; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class EmployeeService +{ + public List getAllEmployees() + { + List employees = new ArrayList<>(); + employees.add(new Employee(1, "Manager")); + employees.add(new Employee(2, "Java Developer")); + return employees; + } + + public void addEmployees(List employees) + { + employees.forEach(e -> System.out.println("Adding new employee " + e)); + } +} diff --git a/spring-rest/src/main/resources/application.properties b/spring-rest/src/main/resources/application.properties index 5ea345c395..dd7e4e2f2d 100644 --- a/spring-rest/src/main/resources/application.properties +++ b/spring-rest/src/main/resources/application.properties @@ -1,3 +1,2 @@ server.port= 8082 -server.servlet.context-path=/spring-rest -spring.mvc.favicon.enabled=false \ No newline at end of file +server.servlet.context-path=/spring-rest \ No newline at end of file diff --git a/spring-rest/src/main/resources/logback.xml b/spring-rest/src/main/resources/logback.xml index 3496a4a03c..9f48d36486 100644 --- a/spring-rest/src/main/resources/logback.xml +++ b/spring-rest/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorTest.java b/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorTest.java deleted file mode 100644 index e87adbc712..0000000000 --- a/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.propertyeditor.creditcard; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; - -import com.baeldung.propertyeditor.creditcard.CreditCard; -import com.baeldung.propertyeditor.creditcard.CreditCardEditor; - -@RunWith(MockitoJUnitRunner.class) -public class CreditCardEditorTest { - - private CreditCardEditor creditCardEditor; - - @Before - public void setup() { - creditCardEditor = new CreditCardEditor(); - } - - @Test(expected=IllegalArgumentException.class) - public void whenInvalidCardNoWithLessDigits_thenThrowsException() { - creditCardEditor.setAsText("123-123-123-123"); - } - - @Test(expected=IllegalArgumentException.class) - public void whenInvalidCardNoWithNonDigits_thenThrowsException() { - creditCardEditor.setAsText("1234-1234-xxxx-yyyy"); - } - - @Test - public void whenCardNoWithNonDigits_parseCreditCard() { - creditCardEditor.setAsText("1234-5678-9123-4560"); - - CreditCard creditCard = (CreditCard) creditCardEditor.getValue(); - Assert.assertNotNull(creditCard); - - Assert.assertEquals(123456, creditCard.getBankIdNo().intValue()); - Assert.assertEquals(789123456, creditCard.getAccountNo().intValue()); - Assert.assertEquals(0, creditCard.getCheckCode().intValue()); - } - -} diff --git a/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java b/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java new file mode 100644 index 0000000000..a84f866dfe --- /dev/null +++ b/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.propertyeditor.creditcard; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.runners.MockitoJUnitRunner; + +import com.baeldung.propertyeditor.creditcard.CreditCard; +import com.baeldung.propertyeditor.creditcard.CreditCardEditor; + +@RunWith(MockitoJUnitRunner.class) +public class CreditCardEditorUnitTest { + + private CreditCardEditor creditCardEditor; + + @Before + public void setup() { + creditCardEditor = new CreditCardEditor(); + } + + @Test(expected=IllegalArgumentException.class) + public void whenInvalidCardNoWithLessDigits_thenThrowsException() { + creditCardEditor.setAsText("123-123-123-123"); + } + + @Test(expected=IllegalArgumentException.class) + public void whenInvalidCardNoWithNonDigits_thenThrowsException() { + creditCardEditor.setAsText("1234-1234-xxxx-yyyy"); + } + + @Test + public void whenCardNoWithNonDigits_parseCreditCard() { + creditCardEditor.setAsText("1234-5678-9123-4560"); + + CreditCard creditCard = (CreditCard) creditCardEditor.getValue(); + Assert.assertNotNull(creditCard); + + Assert.assertEquals(123456, creditCard.getBankIdNo().intValue()); + Assert.assertEquals(789123456, creditCard.getAccountNo().intValue()); + Assert.assertEquals(0, creditCard.getCheckCode().intValue()); + } + +} diff --git a/spring-rest/src/test/java/com/baeldung/responseheaders/ResponseHeaderLiveTest.java b/spring-rest/src/test/java/com/baeldung/responseheaders/ResponseHeaderLiveTest.java new file mode 100644 index 0000000000..bed0de55bd --- /dev/null +++ b/spring-rest/src/test/java/com/baeldung/responseheaders/ResponseHeaderLiveTest.java @@ -0,0 +1,103 @@ +package com.baeldung.responseheaders; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class ResponseHeaderLiveTest { + + private static final String BASE_URL = "http://localhost:8082/spring-rest"; + private static final String SINGLE_BASE_URL = BASE_URL + "/single-response-header"; + private static final String FILTER_BASE_URL = BASE_URL + "/filter-response-header"; + private static final String SERVICE_SINGLE_RESPONSE_HEADER = "Baeldung-Example-Header"; + private static final String SERVICE_FILTER_RESPONSE_HEADER = "Baeldung-Example-Filter-Header"; + + @Autowired + private TestRestTemplate template; + + @Test + public void whenHttpServletResponseRequest_thenObtainResponseWithCorrectHeader() { + final String requestUrl = "/http-servlet-response"; + ResponseEntity response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class); + HttpHeaders responseHeaders = response.getHeaders(); + + assertThat(responseHeaders).isNotEmpty(); + assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-HttpServletResponse")); + } + + @Test + public void whenResponseEntityConstructorRequest_thenObtainResponseWithCorrectHeader() { + final String requestUrl = "/response-entity-constructor"; + ResponseEntity response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class); + HttpHeaders responseHeaders = response.getHeaders(); + + assertThat(responseHeaders).isNotEmpty(); + assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityContructor")); + } + + @Test + public void whenResponseEntityConstructorAndMultipleHeadersRequest_thenObtainResponseWithCorrectHeaders() { + final String requestUrl = "/response-entity-contructor-multiple-headers"; + ResponseEntity response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class); + HttpHeaders responseHeaders = response.getHeaders(); + + assertThat(responseHeaders).isNotEmpty(); + assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityConstructorAndHeaders")); + assertThat(responseHeaders).containsEntry("Accept", Arrays.asList(MediaType.APPLICATION_JSON.toString())); + } + + @Test + public void whenResponseEntityBuilderRequest_thenObtainResponseWithCorrectHeader() { + final String requestUrl = "/response-entity-builder"; + ResponseEntity response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class); + HttpHeaders responseHeaders = response.getHeaders(); + + assertThat(responseHeaders).isNotEmpty(); + assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityBuilder")); + } + + @Test + public void whenResponseEntityBuilderAndHttpHeadersRequest_thenObtainResponseWithCorrectHeader() { + final String requestUrl = "/response-entity-builder-with-http-headers"; + ResponseEntity response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class); + HttpHeaders responseHeaders = response.getHeaders(); + + assertThat(responseHeaders).isNotEmpty(); + assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityBuilderWithHttpHeaders")); + } + + @Test + public void whenFilterWithNoExtraHeaderRequest_thenObtainResponseWithCorrectHeader() { + final String requestUrl = "/no-extra-header"; + ResponseEntity response = template.getForEntity(FILTER_BASE_URL + requestUrl, String.class); + HttpHeaders responseHeaders = response.getHeaders(); + + assertThat(responseHeaders).isNotEmpty(); + assertThat(responseHeaders).containsEntry(SERVICE_FILTER_RESPONSE_HEADER, Arrays.asList("Value-Filter")); + } + + @Test + public void whenFilterWithExtraHeaderRequest_thenObtainResponseWithCorrectHeaders() { + final String requestUrl = "/extra-header"; + ResponseEntity response = template.getForEntity(FILTER_BASE_URL + requestUrl, String.class); + HttpHeaders responseHeaders = response.getHeaders(); + + assertThat(responseHeaders).isNotEmpty(); + assertThat(responseHeaders).containsEntry(SERVICE_FILTER_RESPONSE_HEADER, Arrays.asList("Value-Filter")); + assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ExtraHeader")); + } + +} diff --git a/spring-rest/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java b/spring-rest/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java deleted file mode 100644 index a8a71c7d73..0000000000 --- a/spring-rest/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java +++ /dev/null @@ -1,117 +0,0 @@ -package org.baeldung.client; - -import okhttp3.Request; -import okhttp3.RequestBody; -import org.junit.Before; -import org.junit.Test; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.client.RestTemplateBuilder; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.client.RestTemplate; - -import static org.baeldung.client.Consts.APPLICATION_PORT; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; - -public class TestRestTemplateBasicLiveTest { - - private RestTemplateBuilder restTemplate; - private static final String FOO_RESOURCE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest/foos"; - private static final String URL_SECURED_BY_AUTHENTICATION = "http://httpbin.org/basic-auth/user/passwd"; - private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; - - @Before - public void beforeTest() { - restTemplate = new RestTemplateBuilder(); - } - - // GET - @Test - public void givenTestRestTemplate_whenSendGetForEntity_thenStatusOk() { - TestRestTemplate testRestTemplate = new TestRestTemplate(); - ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class); - assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); - } - - @Test - public void givenRestTemplateWrapper_whenSendGetForEntity_thenStatusOk() { - TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplate); - ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class); - assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); - } - - @Test - public void givenRestTemplateBuilderWrapper_whenSendGetForEntity_thenStatusOk() { - RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); - restTemplateBuilder.build(); - TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder); - ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class); - assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); - } - - @Test - public void givenRestTemplateWrapperWithCredentials_whenSendGetForEntity_thenStatusOk() { - TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplate, "user", "passwd"); - ResponseEntity response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION, - String.class); - assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); - } - - @Test - public void givenTestRestTemplateWithCredentials_whenSendGetForEntity_thenStatusOk() { - TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd"); - ResponseEntity response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION, - String.class); - assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); - } - - @Test - public void givenTestRestTemplateWithBasicAuth_whenSendGetForEntity_thenStatusOk() { - TestRestTemplate testRestTemplate = new TestRestTemplate(); - ResponseEntity response = testRestTemplate.withBasicAuth("user", "passwd"). - getForEntity(URL_SECURED_BY_AUTHENTICATION, String.class); - assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); - } - - @Test - public void givenTestRestTemplateWithCredentialsAndEnabledCookies_whenSendGetForEntity_thenStatusOk() { - TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd", TestRestTemplate. - HttpClientOption.ENABLE_COOKIES); - ResponseEntity response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION, - String.class); - assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); - } - - // HEAD - @Test - public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeaders() { - TestRestTemplate testRestTemplate = new TestRestTemplate(); - final HttpHeaders httpHeaders = testRestTemplate.headForHeaders(FOO_RESOURCE_URL); - assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON)); - } - - // POST - @Test - public void givenService_whenPostForObject_thenCreatedObjectIsReturned() { - TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd"); - final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/html; charset=utf-8"), - "{\"id\":1,\"name\":\"Jim\"}"); - final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build(); - testRestTemplate.postForObject(URL_SECURED_BY_AUTHENTICATION, request, String.class); - } - - // PUT - @Test - public void givenService_whenPutForObject_thenCreatedObjectIsReturned() { - TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd"); - final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/html; charset=utf-8"), - "{\"id\":1,\"name\":\"Jim\"}"); - final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build(); - testRestTemplate.put(URL_SECURED_BY_AUTHENTICATION, request, String.class); - } - -} diff --git a/spring-rest/src/test/java/org/baeldung/resttemplate/RestTemplateIntegrationTest.java b/spring-rest/src/test/java/org/baeldung/resttemplate/RestTemplateIntegrationTest.java deleted file mode 100644 index e0c24c32b1..0000000000 --- a/spring-rest/src/test/java/org/baeldung/resttemplate/RestTemplateIntegrationTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.baeldung.resttemplate; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import org.baeldung.config.RestClientConfig; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.client.RestTemplate; - -import com.baeldung.transfer.LoginForm; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = RestClientConfig.class) -public class RestTemplateIntegrationTest { - - @Autowired - RestTemplate restTemplate; - - @Test - public void givenRestTemplate_whenRequested_thenLogAndModifyResponse() { - LoginForm loginForm = new LoginForm("userName", "password"); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); - HttpEntity requestEntity = new HttpEntity(loginForm, headers); - - ResponseEntity responseEntity = restTemplate.postForEntity("http://httpbin.org/post", requestEntity, String.class); - - assertThat(responseEntity.getStatusCode(), is(equalTo(HttpStatus.OK))); - assertThat(responseEntity.getHeaders() - .get("Foo") - .get(0), is(equalTo("bar"))); - } -} diff --git a/spring-rest/src/test/java/org/baeldung/resttemplate/RestTemplateLiveTest.java b/spring-rest/src/test/java/org/baeldung/resttemplate/RestTemplateLiveTest.java new file mode 100644 index 0000000000..4f00bebdf4 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/resttemplate/RestTemplateLiveTest.java @@ -0,0 +1,43 @@ +package org.baeldung.resttemplate; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.baeldung.config.RestClientConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.client.RestTemplate; + +import com.baeldung.transfer.LoginForm; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = RestClientConfig.class) +public class RestTemplateLiveTest { + + @Autowired + RestTemplate restTemplate; + + @Test + public void givenRestTemplate_whenRequested_thenLogAndModifyResponse() { + LoginForm loginForm = new LoginForm("userName", "password"); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity requestEntity = new HttpEntity(loginForm, headers); + + ResponseEntity responseEntity = restTemplate.postForEntity("http://httpbin.org/post", requestEntity, String.class); + + assertThat(responseEntity.getStatusCode(), is(equalTo(HttpStatus.OK))); + assertThat(responseEntity.getHeaders() + .get("Foo") + .get(0), is(equalTo("bar"))); + } +} diff --git a/spring-resttemplate/.gitignore b/spring-resttemplate/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-resttemplate/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/spring-resttemplate/README.md b/spring-resttemplate/README.md new file mode 100644 index 0000000000..bf8c56e6ec --- /dev/null +++ b/spring-resttemplate/README.md @@ -0,0 +1,10 @@ +## Spring REST Example Project + +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: +- [Spring RestTemplate Tutorial](http://www.baeldung.com/rest-template) +- [Exploring the Spring Boot TestRestTemplate](http://www.baeldung.com/spring-boot-testresttemplate) +- [Spring RestTemplate Error Handling](http://www.baeldung.com/spring-rest-template-error-handling) +- [Configure a RestTemplate with RestTemplateBuilder](http://www.baeldung.com/spring-rest-template-builder) \ No newline at end of file diff --git a/spring-resttemplate/pom.xml b/spring-resttemplate/pom.xml new file mode 100644 index 0000000000..481104372a --- /dev/null +++ b/spring-resttemplate/pom.xml @@ -0,0 +1,297 @@ + + 4.0.0 + com.baeldung + spring-resttemplate + 0.1-SNAPSHOT + spring-resttemplate + war + + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-1 + + + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-devtools + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.springframework + spring-web + + + commons-logging + commons-logging + + + + + org.springframework + spring-webmvc + + + org.springframework + spring-oxm + + + + + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + com.thoughtworks.xstream + xstream + ${xstream.version} + + + + + + com.google.guava + guava + ${guava.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + + org.slf4j + jcl-over-slf4j + + + + + + + com.squareup.okhttp3 + okhttp + ${com.squareup.okhttp3.version} + + + + + + junit + junit + test + + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + + + org.mockito + mockito-core + test + + + org.springframework + spring-test + + + + + spring-resttemplate + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-war-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + + + tomcat8x + embedded + + + + + + + 8082 + + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + + + + + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + + + 3.5 + 1.4.9 + + + 20.0 + + + 1.6.0 + 3.0.4 + + + 3.4.1 + + + diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java new file mode 100644 index 0000000000..a39994ae67 --- /dev/null +++ b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java @@ -0,0 +1,32 @@ +package org.baeldung.resttemplate.configuration; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; + +import java.io.IOException; + +/** + * interceptor to log incoming requests + */ +public class CustomClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { + + private static final Logger LOGGER = LoggerFactory.getLogger(CustomClientHttpRequestInterceptor.class); + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + + logRequestDetails(request); + + return execution.execute(request, body); + } + + private void logRequestDetails(HttpRequest request) { + LOGGER.info("Request Headers: {}", request.getHeaders()); + LOGGER.info("Request Method: {}", request.getMethod()); + LOGGER.info("Request URI: {}", request.getURI()); + } +} diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java new file mode 100644 index 0000000000..5e8220d064 --- /dev/null +++ b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java @@ -0,0 +1,14 @@ +package org.baeldung.resttemplate.configuration; + +import org.springframework.boot.web.client.RestTemplateCustomizer; +import org.springframework.web.client.RestTemplate; + +/** + * customize rest template with an interceptor + */ +public class CustomRestTemplateCustomizer implements RestTemplateCustomizer { + @Override + public void customize(RestTemplate restTemplate) { + restTemplate.getInterceptors().add(new CustomClientHttpRequestInterceptor()); + } +} diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java new file mode 100644 index 0000000000..ee404db4f8 --- /dev/null +++ b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java @@ -0,0 +1,37 @@ +package org.baeldung.resttemplate.configuration; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.RestTemplate; + +/** + * Controller to test RestTemplate configuration + */ +@RestController +public class HelloController { + + private static final String RESOURCE_URL = "http://localhost:8082/spring-rest/baz"; + private RestTemplate restTemplate; + + @Autowired + public HelloController(RestTemplateBuilder builder) { + this.restTemplate = builder.build(); + } + + @RequestMapping("/foo") + public String foo() { + + ResponseEntity response = restTemplate.getForEntity(RESOURCE_URL, String.class); + + return response.getBody(); + } + + @RequestMapping("/baz") + public String baz() { + return "Foo"; + } + +} diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/RestTemplateConfigurationApplication.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/RestTemplateConfigurationApplication.java new file mode 100644 index 0000000000..76fc346aca --- /dev/null +++ b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/RestTemplateConfigurationApplication.java @@ -0,0 +1,14 @@ +package org.baeldung.resttemplate.configuration; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@EnableAutoConfiguration +public class RestTemplateConfigurationApplication { + + public static void main(String[] args) { + SpringApplication.run(RestTemplateConfigurationApplication.class, args); + } +} diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java new file mode 100644 index 0000000000..4e121185b1 --- /dev/null +++ b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java @@ -0,0 +1,28 @@ +package org.baeldung.resttemplate.configuration; + +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.DependsOn; + +@Configuration +@EnableAutoConfiguration +@ComponentScan("org.baeldung.resttemplate.configuration") +public class SpringConfig { + + @Bean + @Qualifier("customRestTemplateCustomizer") + public CustomRestTemplateCustomizer customRestTemplateCustomizer() { + return new CustomRestTemplateCustomizer(); + } + + @Bean + @DependsOn(value = {"customRestTemplateCustomizer"}) + public RestTemplateBuilder restTemplateBuilder() { + return new RestTemplateBuilder(customRestTemplateCustomizer()); + } + +} diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/dto/Foo.java b/spring-resttemplate/src/main/java/org/baeldung/web/dto/Foo.java new file mode 100644 index 0000000000..240b368b50 --- /dev/null +++ b/spring-resttemplate/src/main/java/org/baeldung/web/dto/Foo.java @@ -0,0 +1,45 @@ +package org.baeldung.web.dto; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +@XStreamAlias("Foo") +public class Foo { + private long id; + private String name; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + this.name = name; + } + + public Foo(final long id, final String name) { + super(); + + this.id = id; + this.name = name; + } + + // API + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + +} \ No newline at end of file diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/exception/NotFoundException.java b/spring-resttemplate/src/main/java/org/baeldung/web/exception/NotFoundException.java new file mode 100644 index 0000000000..5b4d80a659 --- /dev/null +++ b/spring-resttemplate/src/main/java/org/baeldung/web/exception/NotFoundException.java @@ -0,0 +1,4 @@ +package org.baeldung.web.exception; + +public class NotFoundException extends RuntimeException { +} diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/handler/RestTemplateResponseErrorHandler.java b/spring-resttemplate/src/main/java/org/baeldung/web/handler/RestTemplateResponseErrorHandler.java new file mode 100644 index 0000000000..b1b87e89a5 --- /dev/null +++ b/spring-resttemplate/src/main/java/org/baeldung/web/handler/RestTemplateResponseErrorHandler.java @@ -0,0 +1,43 @@ +package org.baeldung.web.handler; + +import org.baeldung.web.exception.NotFoundException; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.stereotype.Component; +import org.springframework.web.client.ResponseErrorHandler; + +import java.io.IOException; + +@Component +public class RestTemplateResponseErrorHandler + implements ResponseErrorHandler { + + @Override + public boolean hasError(ClientHttpResponse httpResponse) + throws IOException { + + return (httpResponse + .getStatusCode() + .series() == HttpStatus.Series.CLIENT_ERROR || httpResponse + .getStatusCode() + .series() == HttpStatus.Series.SERVER_ERROR); + } + + @Override + public void handleError(ClientHttpResponse httpResponse) + throws IOException { + + if (httpResponse + .getStatusCode() + .series() == HttpStatus.Series.SERVER_ERROR) { + //Handle SERVER_ERROR + } else if (httpResponse + .getStatusCode() + .series() == HttpStatus.Series.CLIENT_ERROR) { + //Handle CLIENT_ERROR + if (httpResponse.getStatusCode() == HttpStatus.NOT_FOUND) { + throw new NotFoundException(); + } + } + } +} diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/model/Bar.java b/spring-resttemplate/src/main/java/org/baeldung/web/model/Bar.java new file mode 100644 index 0000000000..474e2070a5 --- /dev/null +++ b/spring-resttemplate/src/main/java/org/baeldung/web/model/Bar.java @@ -0,0 +1,22 @@ +package org.baeldung.web.model; + +public class Bar { + private String id; + private String name; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/service/BarConsumerService.java b/spring-resttemplate/src/main/java/org/baeldung/web/service/BarConsumerService.java new file mode 100644 index 0000000000..4188677b4f --- /dev/null +++ b/spring-resttemplate/src/main/java/org/baeldung/web/service/BarConsumerService.java @@ -0,0 +1,26 @@ +package org.baeldung.web.service; + +import org.baeldung.web.handler.RestTemplateResponseErrorHandler; +import org.baeldung.web.model.Bar; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +@Service +public class BarConsumerService { + + private RestTemplate restTemplate; + + @Autowired + public BarConsumerService(RestTemplateBuilder restTemplateBuilder) { + RestTemplate restTemplate = restTemplateBuilder + .errorHandler(new RestTemplateResponseErrorHandler()) + .build(); + } + + public Bar fetchBarById(String barId) { + return restTemplate.getForObject("/bars/4242", Bar.class); + } + +} diff --git a/spring-resttemplate/src/main/resources/application.properties b/spring-resttemplate/src/main/resources/application.properties new file mode 100644 index 0000000000..1a26e3ad99 --- /dev/null +++ b/spring-resttemplate/src/main/resources/application.properties @@ -0,0 +1,2 @@ +server.port=8082 +server.servlet.context-path=/spring-rest \ No newline at end of file diff --git a/spring-resttemplate/src/main/resources/logback.xml b/spring-resttemplate/src/main/resources/logback.xml new file mode 100644 index 0000000000..9f48d36486 --- /dev/null +++ b/spring-resttemplate/src/main/resources/logback.xml @@ -0,0 +1,23 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-resttemplate/src/test/java/org/baeldung/client/Consts.java b/spring-resttemplate/src/test/java/org/baeldung/client/Consts.java new file mode 100644 index 0000000000..b40561d9c3 --- /dev/null +++ b/spring-resttemplate/src/test/java/org/baeldung/client/Consts.java @@ -0,0 +1,5 @@ +package org.baeldung.client; + +public interface Consts { + int APPLICATION_PORT = 8082; +} diff --git a/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java b/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java similarity index 100% rename from spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java rename to spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java diff --git a/spring-rest-simple/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java b/spring-resttemplate/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java similarity index 100% rename from spring-rest-simple/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java rename to spring-resttemplate/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java b/spring-resttemplate/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java new file mode 100644 index 0000000000..2dfa81f441 --- /dev/null +++ b/spring-resttemplate/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java @@ -0,0 +1,48 @@ +package org.baeldung.web.handler; + +import org.baeldung.web.exception.NotFoundException; +import org.baeldung.web.model.Bar; +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.autoconfigure.web.client.RestClientTest; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.client.ExpectedCount; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.web.client.RestTemplate; + +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = { NotFoundException.class, Bar.class }) +@RestClientTest +public class RestTemplateResponseErrorHandlerIntegrationTest { + + @Autowired private MockRestServiceServer server; + @Autowired private RestTemplateBuilder builder; + + @Test(expected = NotFoundException.class) + public void givenRemoteApiCall_when404Error_thenThrowNotFound() { + Assert.assertNotNull(this.builder); + Assert.assertNotNull(this.server); + + RestTemplate restTemplate = this.builder + .errorHandler(new RestTemplateResponseErrorHandler()) + .build(); + + this.server + .expect(ExpectedCount.once(), requestTo("/bars/4242")) + .andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); + + Bar response = restTemplate.getForObject("/bars/4242", Bar.class); + this.server.verify(); + } +} \ No newline at end of file diff --git a/spring-resttemplate/src/test/resources/.gitignore b/spring-resttemplate/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-resttemplate/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/spring-roo/pom.xml b/spring-roo/pom.xml index 5827aba7af..c205c98dc0 100644 --- a/spring-roo/pom.xml +++ b/spring-roo/pom.xml @@ -1,266 +1,20 @@ - - + + + 4.0.0 + com.baeldung + spring-roo + 1.0.0.BUILD-SNAPSHOT + Spring Roo + jar + io.spring.platform platform-bom Athens-RELEASE - + - 4.0.0 - com.baeldung - roo - 1.0.0.BUILD-SNAPSHOT - roo - - jar - - - 2.0.0.RC1 - 8 - UTF-8 - 1.8 - 1.5.4 - 1.4.1.RELEASE - 1.8 - 1.2.0.RC1 - 1.1.2 - 3.0.0.RELEASE - 2.0.0 - 2.0.1 - 5.0.11 - 1.0 - 3.3.6 - 1.10.12 - 1.10.11 - 1.1.2 - 1.1.2 - 2.0.2 - 2.0.2 - 1.1.2 - 1.1.2 - 1.1.2 - 2.0.0 - 2.5.4 - 4.6.2 - 1.12.3 - 3.3.1 - 1.15.0 - 2.13.0 - 4.0.3 - 0.1.0-beta.7 - 1.4.2 - 3.7.3 - 1.0.3 - - - - - - maven-snapshot-repository - Maven Snapshot Repository - https://oss.sonatype.org/content/repositories/snapshots - - false - - - true - - - - - spring-roo-repository - Spring Roo Repository - http://repo.spring.io/spring-roo - - - - - - - - - org.springframework.roo - org.springframework.roo.annotations - ${roo.version} - pom - provided - - - - io.springlets - springlets-data-jpa - ${springlets.version} - - - io.springlets - springlets-data-commons - ${springlets.version} - - - io.springlets - springlets-context - ${springlets.version} - - - org.springframework.roo - org.springframework.roo.querydsl.processor - 2.0.0.RELEASE - - - io.tracee.binding - tracee-springmvc - ${tracee.version} - - - io.springlets - springlets-boot-starter-web - ${springlets.version} - - - com.github.mxab.thymeleaf.extras - thymeleaf-extras-data-attribute - ${thymeleaf-data-dialect.version} - - - ar.com.fdvs - DynamicJasper - ${dynamicjasper.version} - - - ar.com.fdvs - DynamicJasper-core-fonts - ${dynamicjasper-fonts.version} - - - org.webjars.bower - bootstrap - ${bootstrap.version} - - - org.webjars.bower - datatables - ${datatables.version} - - - org.webjars.bower - datatables.net-bs - ${datatables-bs.version} - - - org.webjars.bower - datatables.net-buttons - ${datatables-buttons.version} - - - org.webjars.bower - datatables.net-buttons-bs - ${datatables-buttons-bs.version} - - - org.webjars.bower - datatables.net-responsive - ${datatables-responsive.version} - - - org.webjars.bower - datatables.net-responsive-bs - ${datatables-responsive-bs.version} - - - org.webjars.bower - datatables.net-select - ${datatables-select.version} - - - org.webjars.bower - datatables.net-select-bs - ${datatables-select-bs.version} - - - org.webjars.npm - jquery-datatables-checkboxes - ${datatables-checkboxes.version} - - - org.webjars.npm - jquery - - - org.webjars.npm - datatables.net - - - - - org.webjars.bower - github-com-julmot-datatables-mark-js - ${datatables-mark.version} - - - org.webjars.bower - datetimepicker - ${datetimepicker.version} - - - org.webjars.bower - font-awesome - ${fontawesome.version} - - - org.webjars.bower - jquery - ${jquery.version} - - - org.webjars - jquery.inputmask - ${jquery-inputmask.version} - - - org.webjars - jquery - - - - - org.webjars.bower - jquery-validation - ${jquery-validation.version} - - - org.webjars.bower - momentjs - ${momentjs.version} - - - org.webjars.bower - select2 - ${select2.version} - - - org.webjars.bower - select2-bootstrap-theme - ${select2-bootstrap-theme.version} - - - org.webjars - respond - ${respond.version} - - - org.webjars - html5shiv - ${html5shiv.version} - - - org.webjars.bower - ie10-viewport-bug-workaround - ${bootstrap.ie10-viewport-bug-workaround.version} - - - @@ -558,7 +312,8 @@ "projectName=${project.name}" --attribute "projectVersion=${project.version}" - --attribute "doctype=book" + --attribute + "doctype=book" ${project.groupId}:* @@ -642,4 +397,250 @@ + + + + maven-snapshot-repository + Maven Snapshot Repository + https://oss.sonatype.org/content/repositories/snapshots + + false + + + true + + + + + spring-roo-repository + Spring Roo Repository + http://repo.spring.io/spring-roo + + + + + + + + org.springframework.roo + org.springframework.roo.annotations + ${roo.version} + pom + provided + + + + io.springlets + springlets-data-jpa + ${springlets.version} + + + io.springlets + springlets-data-commons + ${springlets.version} + + + io.springlets + springlets-context + ${springlets.version} + + + org.springframework.roo + org.springframework.roo.querydsl.processor + ${querydsl-processor.version} + + + io.tracee.binding + tracee-springmvc + ${tracee.version} + + + io.springlets + springlets-boot-starter-web + ${springlets.version} + + + com.github.mxab.thymeleaf.extras + thymeleaf-extras-data-attribute + ${thymeleaf-data-dialect.version} + + + ar.com.fdvs + DynamicJasper + ${dynamicjasper.version} + + + ar.com.fdvs + DynamicJasper-core-fonts + ${dynamicjasper-fonts.version} + + + org.webjars.bower + bootstrap + ${bootstrap.version} + + + org.webjars.bower + datatables + ${datatables.version} + + + org.webjars.bower + datatables.net-bs + ${datatables-bs.version} + + + org.webjars.bower + datatables.net-buttons + ${datatables-buttons.version} + + + org.webjars.bower + datatables.net-buttons-bs + ${datatables-buttons-bs.version} + + + org.webjars.bower + datatables.net-responsive + ${datatables-responsive.version} + + + org.webjars.bower + datatables.net-responsive-bs + ${datatables-responsive-bs.version} + + + org.webjars.bower + datatables.net-select + ${datatables-select.version} + + + org.webjars.bower + datatables.net-select-bs + ${datatables-select-bs.version} + + + org.webjars.npm + jquery-datatables-checkboxes + ${datatables-checkboxes.version} + + + org.webjars.npm + jquery + + + org.webjars.npm + datatables.net + + + + + org.webjars.bower + github-com-julmot-datatables-mark-js + ${datatables-mark.version} + + + org.webjars.bower + datetimepicker + ${datetimepicker.version} + + + org.webjars.bower + font-awesome + ${fontawesome.version} + + + org.webjars.bower + jquery + ${jquery.version} + + + org.webjars + jquery.inputmask + ${jquery-inputmask.version} + + + org.webjars + jquery + + + + + org.webjars.bower + jquery-validation + ${jquery-validation.version} + + + org.webjars.bower + momentjs + ${momentjs.version} + + + org.webjars.bower + select2 + ${select2.version} + + + org.webjars.bower + select2-bootstrap-theme + ${select2-bootstrap-theme.version} + + + org.webjars + respond + ${respond.version} + + + org.webjars + html5shiv + ${html5shiv.version} + + + org.webjars.bower + ie10-viewport-bug-workaround + ${bootstrap.ie10-viewport-bug-workaround.version} + + + + + + 2.0.0.RC1 + 8 + UTF-8 + 1.8 + 1.5.4 + 1.4.1.RELEASE + 1.8 + 1.2.0.RC1 + 1.1.2 + 3.0.0.RELEASE + 2.0.0 + 2.0.1 + 5.0.11 + 1.0 + 3.3.6 + 1.10.12 + 1.10.11 + 1.1.2 + 1.1.2 + 2.0.2 + 2.0.2 + 1.1.2 + 1.1.2 + 1.1.2 + 2.0.0 + 2.5.4 + 4.6.2 + 1.12.3 + 3.3.1 + 1.15.0 + 2.13.0 + 4.0.3 + 0.1.0-beta.7 + 1.4.2 + 3.7.3 + 1.0.3 + 2.0.0.RELEASE + + diff --git a/spring-roo/src/main/resources/logback.xml b/spring-roo/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-roo/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-acl/pom.xml b/spring-security-acl/pom.xml index 7ddbf66365..c87c237233 100644 --- a/spring-security-acl/pom.xml +++ b/spring-security-acl/pom.xml @@ -1,46 +1,40 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-security-acl 0.0.1-SNAPSHOT war - spring-security-acl Spring Security ACL - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 - org.springframework.boot spring-boot-starter-data-jpa - com.h2database h2 - org.springframework spring-test test - org.springframework.security spring-security-test test - org.springframework.security spring-security-acl @@ -56,10 +50,13 @@ net.sf.ehcache ehcache-core - 2.6.11 + ${ehcache-core.version} jar - + + 2.6.11 + + diff --git a/spring-security-acl/src/main/resources/logback.xml b/spring-security-acl/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-acl/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-angular/README.md b/spring-security-angular/README.md new file mode 100644 index 0000000000..80312c4bab --- /dev/null +++ b/spring-security-angular/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Spring Security Login Page with Angular](https://www.baeldung.com/spring-security-login-angular) diff --git a/spring-security-angular/client/anguarjs/app.js b/spring-security-angular/client/anguarjs/app.js new file mode 100644 index 0000000000..4b7268da3f --- /dev/null +++ b/spring-security-angular/client/anguarjs/app.js @@ -0,0 +1,40 @@ +(function () { + 'use strict'; + + angular + .module('app', ['ngRoute']) + .config(config) + .run(run); + + config.$inject = ['$routeProvider', '$locationProvider']; + function config($routeProvider, $locationProvider) { + $routeProvider + .when('/', { + controller: 'HomeController', + templateUrl: 'home/home.view.html', + controllerAs: 'vm' + }) + .when('/login', { + controller: 'LoginController', + templateUrl: 'login/login.view.html', + controllerAs: 'vm' + }) + .otherwise({ redirectTo: '/login' }); + } + + run.$inject = ['$rootScope', '$location', '$http', '$window']; + function run($rootScope, $location, $http, $window) { + var userData = $window.sessionStorage.getItem('userData'); + if (userData) { + $http.defaults.headers.common['Authorization'] = 'Basic ' + JSON.parse(userData).authData; + } + + $rootScope.$on('$locationChangeStart', function (event, next, current) { + var restrictedPage = $.inArray($location.path(), ['/login']) === -1; + var loggedIn = $window.sessionStorage.getItem('userData');; + if (restrictedPage && !loggedIn) { + $location.path('/login'); + } + }); + } +})(); \ No newline at end of file diff --git a/spring-security-angular/client/anguarjs/home/home.controller.js b/spring-security-angular/client/anguarjs/home/home.controller.js new file mode 100644 index 0000000000..6449029ec2 --- /dev/null +++ b/spring-security-angular/client/anguarjs/home/home.controller.js @@ -0,0 +1,34 @@ +(function () { + 'use strict'; + + angular + .module('app') + .controller('HomeController', HomeController); + + HomeController.$inject = ['$window', '$http', '$scope']; + function HomeController($window, $http, $scope) { + var vm = this; + + vm.user = null; + + initController(); + + function initController() { + + $http({ + url: 'http://localhost:8082/user', + method: "GET" + }).then(function (response) { + vm.user = response.data.name; + },function(error){ + console.log(error); + }); + }; + + $scope.logout = function(){ + $window.sessionStorage.setItem('userData', ''); + $http.defaults.headers.common['Authorization'] = 'Basic'; + } + } + +})(); \ No newline at end of file diff --git a/spring-security-angular/client/anguarjs/home/home.view.html b/spring-security-angular/client/anguarjs/home/home.view.html new file mode 100644 index 0000000000..bb5c2d3dbf --- /dev/null +++ b/spring-security-angular/client/anguarjs/home/home.view.html @@ -0,0 +1,3 @@ +

    Hi {{vm.user}}!

    +

    You're logged in!!

    +

    Logout

    \ No newline at end of file diff --git a/spring-security-angular/client/anguarjs/index.html b/spring-security-angular/client/anguarjs/index.html new file mode 100644 index 0000000000..a5584d53be --- /dev/null +++ b/spring-security-angular/client/anguarjs/index.html @@ -0,0 +1,17 @@ + + + + + + +
    + + + + + + + + + + \ No newline at end of file diff --git a/spring-security-angular/client/anguarjs/login/login.controller.js b/spring-security-angular/client/anguarjs/login/login.controller.js new file mode 100644 index 0000000000..2da509ec83 --- /dev/null +++ b/spring-security-angular/client/anguarjs/login/login.controller.js @@ -0,0 +1,38 @@ +(function () { + 'use strict'; + + angular + .module('app') + .controller('LoginController', LoginController); + + LoginController.$inject = ['$location', '$window', '$http']; + function LoginController($location, $window, $http) { + var vm = this; + vm.login = login; + + (function initController() { + $window.localStorage.setItem('token', ''); + })(); + + function login() { + $http({ + url: 'http://localhost:8082/login', + method: "POST", + data: { 'userName': vm.username, 'password': vm.password } + }).then(function (response) { + if (response.data) { + var token = $window.btoa(vm.username + ':' + vm.password); + var userData = { + userName: vm.username, + authData: token + } + $window.sessionStorage.setItem('userData', JSON.stringify(userData)); + $http.defaults.headers.common['Authorization'] = 'Basic ' + token; + $location.path('/'); + } else { + alert("Authentication failed.") + } + }); + }; + } +})(); diff --git a/spring-security-angular/client/anguarjs/login/login.view.html b/spring-security-angular/client/anguarjs/login/login.view.html new file mode 100644 index 0000000000..0d42f29b54 --- /dev/null +++ b/spring-security-angular/client/anguarjs/login/login.view.html @@ -0,0 +1,18 @@ +
    +

    Login

    +
    +
    + + + Username is required +
    +
    + + + Password is required +
    +
    + +
    +
    +
    \ No newline at end of file diff --git a/spring-security-angular/client/angular2/app.css b/spring-security-angular/client/angular2/app.css new file mode 100644 index 0000000000..cdd2d591d8 --- /dev/null +++ b/spring-security-angular/client/angular2/app.css @@ -0,0 +1,7 @@ +a { + cursor: pointer; +} + +.help-block { + font-size: 12px; +} \ No newline at end of file diff --git a/spring-security-angular/client/angular2/app/app.component.html b/spring-security-angular/client/angular2/app/app.component.html new file mode 100644 index 0000000000..7f77adea7b --- /dev/null +++ b/spring-security-angular/client/angular2/app/app.component.html @@ -0,0 +1,7 @@ +
    +
    +
    + +
    +
    +
    diff --git a/spring-security-angular/client/angular2/app/app.component.ts b/spring-security-angular/client/angular2/app/app.component.ts new file mode 100644 index 0000000000..0aae2b6992 --- /dev/null +++ b/spring-security-angular/client/angular2/app/app.component.ts @@ -0,0 +1,8 @@ +import { Component } from '@angular/core'; + +@Component({ + selector: 'app', + templateUrl: './app/app.component.html' +}) + +export class AppComponent { } \ No newline at end of file diff --git a/spring-security-angular/client/angular2/app/app.module.ts b/spring-security-angular/client/angular2/app/app.module.ts new file mode 100644 index 0000000000..4d484b49f8 --- /dev/null +++ b/spring-security-angular/client/angular2/app/app.module.ts @@ -0,0 +1,27 @@ +import { NgModule } from '@angular/core'; +import { BrowserModule } from '@angular/platform-browser'; +import { FormsModule } from '@angular/forms'; +import { HttpModule } from '@angular/http'; + +import { AppComponent } from './app.component'; +import { routing } from './app.routing'; + +import { HomeComponent } from './home/home.component'; +import { LoginComponent } from './login/login.component'; + +@NgModule({ + imports: [ + BrowserModule, + FormsModule, + HttpModule, + routing + ], + declarations: [ + AppComponent, + HomeComponent, + LoginComponent + ], + bootstrap: [AppComponent] +}) + +export class AppModule { } \ No newline at end of file diff --git a/spring-security-angular/client/angular2/app/app.routing.ts b/spring-security-angular/client/angular2/app/app.routing.ts new file mode 100644 index 0000000000..c794fc5c50 --- /dev/null +++ b/spring-security-angular/client/angular2/app/app.routing.ts @@ -0,0 +1,12 @@ +import { Routes, RouterModule } from '@angular/router'; + +import { HomeComponent } from './home/home.component'; +import { LoginComponent } from './login/login.component'; + +const appRoutes: Routes = [ + { path: '', component: HomeComponent}, + { path: 'login', component: LoginComponent }, + { path: '**', redirectTo: '' } +]; + +export const routing = RouterModule.forRoot(appRoutes); \ No newline at end of file diff --git a/spring-security-angular/client/angular2/app/home/home.component.html b/spring-security-angular/client/angular2/app/home/home.component.html new file mode 100644 index 0000000000..5f3b24be3a --- /dev/null +++ b/spring-security-angular/client/angular2/app/home/home.component.html @@ -0,0 +1,4 @@ +
    +

    Hi {{userName}}!

    +

    Logout

    +
    \ No newline at end of file diff --git a/spring-security-angular/client/angular2/app/home/home.component.ts b/spring-security-angular/client/angular2/app/home/home.component.ts new file mode 100644 index 0000000000..1b168bfb30 --- /dev/null +++ b/spring-security-angular/client/angular2/app/home/home.component.ts @@ -0,0 +1,36 @@ +import { Component, OnInit } from '@angular/core'; +import { Http, RequestOptions, Headers } from '@angular/http'; +import 'rxjs/add/operator/map' + +@Component({ + selector:'home', + templateUrl: './app/home/home.component.html' +}) + +export class HomeComponent implements OnInit { + + userName: string; + + constructor(private http: Http) { } + + ngOnInit() { + let url = 'http://localhost:8082/user'; + let headers = new Headers({ + 'Authorization': 'Basic ' + sessionStorage.getItem('token') + }); + let options = new RequestOptions({ headers: headers }); + this.http.post(url,{}, options). + map(res => res.json()). + subscribe( + principal => this.userName = principal.name, + error => { + if(error.status == 401) + alert('Unauthorized'); + } + ); + } + + logout() { + sessionStorage.setItem('token', ''); + } +} \ No newline at end of file diff --git a/spring-security-angular/client/angular2/app/login/login.component.html b/spring-security-angular/client/angular2/app/login/login.component.html new file mode 100644 index 0000000000..d87b91a7bb --- /dev/null +++ b/spring-security-angular/client/angular2/app/login/login.component.html @@ -0,0 +1,18 @@ +
    +

    Login

    +
    +
    + + +
    Username is required
    +
    +
    + + +
    Password is required
    +
    +
    + +
    +
    +
    diff --git a/spring-security-angular/client/angular2/app/login/login.component.ts b/spring-security-angular/client/angular2/app/login/login.component.ts new file mode 100644 index 0000000000..81d6c1d7ae --- /dev/null +++ b/spring-security-angular/client/angular2/app/login/login.component.ts @@ -0,0 +1,36 @@ +import { Component, OnInit } from '@angular/core'; +import { Router, ActivatedRoute } from '@angular/router'; +import { Http } from '@angular/http'; + +@Component({ + selector: 'login', + templateUrl: './app/login/login.component.html' +}) + +export class LoginComponent implements OnInit { + model: any = {}; + + constructor( + private route: ActivatedRoute, + private router: Router, + private http: Http) { } + + ngOnInit() { + sessionStorage.setItem('token', ''); + } + + login() { + let url = 'http://localhost:8082/login'; + let result = this.http.post(url, { + userName: this.model.username, + password: this.model.password + }).map(res => res.json()).subscribe(isValid => { + if (isValid) { + sessionStorage.setItem('token', btoa(this.model.username + ':' + this.model.password)); + this.router.navigate(['']); + } else { + alert("Authentication failed."); + } + }); + } +} diff --git a/spring-security-angular/client/angular2/app/main.ts b/spring-security-angular/client/angular2/app/main.ts new file mode 100644 index 0000000000..3a6c754786 --- /dev/null +++ b/spring-security-angular/client/angular2/app/main.ts @@ -0,0 +1,5 @@ +import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; + +import { AppModule } from './app.module'; + +platformBrowserDynamic().bootstrapModule(AppModule); \ No newline at end of file diff --git a/spring-security-angular/client/angular2/index.html b/spring-security-angular/client/angular2/index.html new file mode 100644 index 0000000000..c9730a8568 --- /dev/null +++ b/spring-security-angular/client/angular2/index.html @@ -0,0 +1,17 @@ + + + + + + + + + + + + + Loading... + + diff --git a/spring-security-angular/client/angular2/package.json b/spring-security-angular/client/angular2/package.json new file mode 100644 index 0000000000..9b36652fac --- /dev/null +++ b/spring-security-angular/client/angular2/package.json @@ -0,0 +1,37 @@ +{ + "name": "angular2-quickstart", + "version": "1.0.0", + "description": "Sample of how easy and fast to start hacking with Angular2 and ng2-bootstrap", + "scripts": { + "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ", + "lite": "lite-server", + "tsc": "tsc", + "tsc:w": "tsc -w" + }, + "license": "ISC", + "dependencies": { + "@angular/common": "2.4.4", + "@angular/compiler": "2.4.4", + "@angular/core": "2.4.4", + "@angular/forms": "2.4.4", + "@angular/http": "2.4.4", + "@angular/platform-browser": "2.4.4", + "@angular/platform-browser-dynamic": "2.4.4", + "@angular/router": "3.4.4", + "@angular/upgrade": "2.4.4", + "angular2-in-memory-web-api": "0.0.21", + "bootstrap": "^3.3.7", + "core-js": "^2.4.1", + "ng2-bootstrap": "1.3.0", + "reflect-metadata": "^0.1.8", + "rxjs": "5.0.3", + "systemjs": "0.20.0", + "zone.js": "0.7.6" + }, + "devDependencies": { + "concurrently": "3.1.0", + "lite-server": "^2.2.0", + "typescript": "2.1.5" + }, + "repository": {} +} diff --git a/spring-security-angular/client/angular2/systemjs.config.js b/spring-security-angular/client/angular2/systemjs.config.js new file mode 100644 index 0000000000..ea4c543fdd --- /dev/null +++ b/spring-security-angular/client/angular2/systemjs.config.js @@ -0,0 +1,41 @@ +/** + * System configuration for Angular 2 samples + * Adjust as necessary for your application needs. + */ +(function (global) { + System.config({ + paths: { + // paths serve as alias + 'npm:': 'node_modules/' + }, + // map tells the System loader where to look for things + map: { + // our app is within the app folder + app: 'app', + + // angular bundles + '@angular/core': 'npm:@angular/core/bundles/core.umd.js', + '@angular/common': 'npm:@angular/common/bundles/common.umd.js', + '@angular/http': 'npm:@angular/http/bundles/http.umd.js', + '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', + '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js', + '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js', + '@angular/router': 'npm:@angular/router/bundles/router.umd.js', + '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js', + + // other libraries + 'rxjs': 'npm:rxjs', + 'tslib': 'npm:tslib/tslib.js' + }, + // packages tells the System loader how to load when no filename and/or no extension + packages: { + app: { + main: './main.js', + defaultExtension: 'js' + }, + rxjs: { + defaultExtension: 'js' + } + } + }); +})(this); diff --git a/spring-security-angular/client/angular2/tsconfig.json b/spring-security-angular/client/angular2/tsconfig.json new file mode 100644 index 0000000000..55f9ad70c3 --- /dev/null +++ b/spring-security-angular/client/angular2/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "lib": [ "es2015", "dom" ], + "module": "commonjs", + "moduleResolution": "node", + "noImplicitAny": true, + "sourceMap": true, + "suppressImplicitAnyIndexErrors": true, + "target": "es5" + }, + "exclude": [ + "node_modules/*" + ] +} \ No newline at end of file diff --git a/spring-security-angular/client/angular4/.angular-cli.json b/spring-security-angular/client/angular4/.angular-cli.json new file mode 100644 index 0000000000..967934b2f7 --- /dev/null +++ b/spring-security-angular/client/angular4/.angular-cli.json @@ -0,0 +1,65 @@ +{ + "$schema": "./node_modules/@angular/cli/lib/config/schema.json", + "project": { + "name": "angular-crud" + }, + "apps": [ + { + "root": "src", + "outDir": "dist", + "assets": [ + "assets", + "favicon.ico" + ], + "index": "index.html", + "main": "main.ts", + "polyfills": "polyfills.ts", + "test": "test.ts", + "tsconfig": "tsconfig.app.json", + "testTsconfig": "tsconfig.spec.json", + "prefix": "app", + "styles": [ + "../node_modules/bootstrap/dist/css/bootstrap.min.css", + "styles.css", + "../node_modules/font-awesome/css/font-awesome.min.css" + ], + "scripts": [ + "../node_modules/jquery/dist/jquery.js", + "../node_modules/bootstrap/dist/js/bootstrap.js" + ], + "environmentSource": "environments/environment.ts", + "environments": { + "dev": "environments/environment.ts", + "prod": "environments/environment.prod.ts" + } + } + ], + "e2e": { + "protractor": { + "config": "./protractor.conf.js" + } + }, + "lint": [ + { + "project": "src/tsconfig.app.json", + "exclude": "**/node_modules/**" + }, + { + "project": "src/tsconfig.spec.json", + "exclude": "**/node_modules/**" + }, + { + "project": "e2e/tsconfig.e2e.json", + "exclude": "**/node_modules/**" + } + ], + "test": { + "karma": { + "config": "./karma.conf.js" + } + }, + "defaults": { + "styleExt": "css", + "component": {} + } +} \ No newline at end of file diff --git a/spring-security-angular/client/angular4/package.json b/spring-security-angular/client/angular4/package.json new file mode 100644 index 0000000000..8c6ddcaf1f --- /dev/null +++ b/spring-security-angular/client/angular4/package.json @@ -0,0 +1,54 @@ +{ + "name": "angular-crud", + "version": "0.0.0", + "license": "MIT", + "scripts": { + "ng": "ng", + "start": "ng serve", + "build": "ng build", + "test": "ng test", + "lint": "ng lint", + "e2e": "ng e2e" + }, + "private": true, + "dependencies": { + "@angular/animations": "^4.0.0", + "@angular/common": "^4.0.0", + "@angular/compiler": "^4.0.0", + "@angular/core": "^4.0.0", + "@angular/forms": "^4.0.0", + "@angular/http": "^4.0.0", + "@angular/platform-browser": "^4.0.0", + "@angular/platform-browser-dynamic": "^4.0.0", + "@angular/router": "^4.0.0", + "bootstrap": "^3.3.7", + "core-js": "^2.4.1", + "font-awesome": "^4.7.0", + "jquery": "^3.2.1", + "lodash": "^4.17.4", + "rxjs": "^5.4.1", + "zone.js": "^0.8.14" + }, + "devDependencies": { + "@angular/cli": "1.2.3", + "@angular/compiler-cli": "^4.0.0", + "@angular/language-service": "^4.0.0", + "@types/jasmine": "~2.5.53", + "@types/jasminewd2": "~2.0.2", + "@types/lodash": "^4.14.66", + "@types/node": "~6.0.60", + "codelyzer": "~3.0.1", + "jasmine-core": "~2.6.2", + "jasmine-spec-reporter": "~4.1.0", + "karma": "~1.7.0", + "karma-chrome-launcher": "~2.1.1", + "karma-cli": "~1.0.1", + "karma-coverage-istanbul-reporter": "^1.2.1", + "karma-jasmine": "~1.1.0", + "karma-jasmine-html-reporter": "^0.2.2", + "protractor": "~5.1.2", + "ts-node": "~3.0.4", + "tslint": "~5.3.2", + "typescript": "~2.3.3" + } +} diff --git a/spring-security-angular/client/angular4/src/app/app.component.html b/spring-security-angular/client/angular4/src/app/app.component.html new file mode 100644 index 0000000000..7f77adea7b --- /dev/null +++ b/spring-security-angular/client/angular4/src/app/app.component.html @@ -0,0 +1,7 @@ +
    +
    +
    + +
    +
    +
    diff --git a/spring-security-angular/client/angular4/src/app/app.component.ts b/spring-security-angular/client/angular4/src/app/app.component.ts new file mode 100644 index 0000000000..36f986c63f --- /dev/null +++ b/spring-security-angular/client/angular4/src/app/app.component.ts @@ -0,0 +1,8 @@ +import { Component } from '@angular/core'; + +@Component({ + selector: 'app-root', + templateUrl: './app.component.html' +}) + +export class AppComponent { } \ No newline at end of file diff --git a/spring-security-angular/client/angular4/src/app/app.module.ts b/spring-security-angular/client/angular4/src/app/app.module.ts new file mode 100644 index 0000000000..9e840e6f13 --- /dev/null +++ b/spring-security-angular/client/angular4/src/app/app.module.ts @@ -0,0 +1,29 @@ +import { NgModule } from '@angular/core'; +import { BrowserModule } from '@angular/platform-browser'; +import { FormsModule } from '@angular/forms'; +import { HttpModule } from '@angular/http'; + +// used to create fake backend + +import { AppComponent } from './app.component'; +import { routing } from './app.routing'; + +import { HomeComponent } from './home/home.component'; +import { LoginComponent } from './login/login.component'; + +@NgModule({ + imports: [ + BrowserModule, + FormsModule, + HttpModule, + routing + ], + declarations: [ + AppComponent, + HomeComponent, + LoginComponent + ], + bootstrap: [AppComponent] +}) + +export class AppModule { } \ No newline at end of file diff --git a/spring-security-angular/client/angular4/src/app/app.routing.ts b/spring-security-angular/client/angular4/src/app/app.routing.ts new file mode 100644 index 0000000000..c794fc5c50 --- /dev/null +++ b/spring-security-angular/client/angular4/src/app/app.routing.ts @@ -0,0 +1,12 @@ +import { Routes, RouterModule } from '@angular/router'; + +import { HomeComponent } from './home/home.component'; +import { LoginComponent } from './login/login.component'; + +const appRoutes: Routes = [ + { path: '', component: HomeComponent}, + { path: 'login', component: LoginComponent }, + { path: '**', redirectTo: '' } +]; + +export const routing = RouterModule.forRoot(appRoutes); \ No newline at end of file diff --git a/spring-security-angular/client/angular4/src/app/home/home.component.html b/spring-security-angular/client/angular4/src/app/home/home.component.html new file mode 100644 index 0000000000..7ccd2c2a3a --- /dev/null +++ b/spring-security-angular/client/angular4/src/app/home/home.component.html @@ -0,0 +1,4 @@ +
    +

    Hi {{userName}}!

    +

    Logout

    +
    \ No newline at end of file diff --git a/spring-security-angular/client/angular4/src/app/home/home.component.ts b/spring-security-angular/client/angular4/src/app/home/home.component.ts new file mode 100644 index 0000000000..0f66f42ce2 --- /dev/null +++ b/spring-security-angular/client/angular4/src/app/home/home.component.ts @@ -0,0 +1,37 @@ +import { Component, OnInit } from '@angular/core'; +import { Http, RequestOptions, Headers } from '@angular/http'; +import 'rxjs/add/operator/map' + +@Component({ + selector:'home', + templateUrl: './home.component.html' +}) + +export class HomeComponent implements OnInit { + + userName: string; + + constructor(private http: Http) { } + + ngOnInit() { + let url = 'http://localhost:8082/user'; + let headers = new Headers({ + 'Authorization': 'Basic ' + sessionStorage.getItem('token') + }); + let options = new RequestOptions({ headers: headers }); + this.http.post(url,{}, options). + map( + res => res.json(), + error => { + if(error.status == 401) + alert('Unauthorized'); + } + ).subscribe(principal => { + this.userName = principal.name; + }); + } + + logout() { + sessionStorage.setItem('token', ''); + } +} \ No newline at end of file diff --git a/spring-security-angular/client/angular4/src/app/login/login.component.html b/spring-security-angular/client/angular4/src/app/login/login.component.html new file mode 100644 index 0000000000..d87b91a7bb --- /dev/null +++ b/spring-security-angular/client/angular4/src/app/login/login.component.html @@ -0,0 +1,18 @@ +
    +

    Login

    +
    +
    + + +
    Username is required
    +
    +
    + + +
    Password is required
    +
    +
    + +
    +
    +
    diff --git a/spring-security-angular/client/angular4/src/app/login/login.component.ts b/spring-security-angular/client/angular4/src/app/login/login.component.ts new file mode 100644 index 0000000000..2a2dc102af --- /dev/null +++ b/spring-security-angular/client/angular4/src/app/login/login.component.ts @@ -0,0 +1,39 @@ +import { Component, OnInit } from '@angular/core'; +import { Router, ActivatedRoute } from '@angular/router'; +import { Http } from '@angular/http'; + +@Component({ + selector: 'login', + templateUrl: './login.component.html' +}) + +export class LoginComponent implements OnInit { + model: any = {}; + + constructor( + private route: ActivatedRoute, + private router: Router, + private http: Http) { } + + ngOnInit() { + sessionStorage.setItem('token', ''); + } + + + login() { + let url = 'http://localhost:8082/login'; + let result = this.http.post(url, { + userName: this.model.username, + password: this.model.password + }). + map(res => res.json()). + subscribe(isValid => { + if (isValid) { + sessionStorage.setItem('token', btoa(this.model.username + ':' + this.model.password)); + this.router.navigate(['']); + } else { + alert("Authentication failed.") + } + }); + } +} diff --git a/spring-security-angular/client/angular4/src/index.html b/spring-security-angular/client/angular4/src/index.html new file mode 100644 index 0000000000..c716820396 --- /dev/null +++ b/spring-security-angular/client/angular4/src/index.html @@ -0,0 +1,14 @@ + + + + + AngularCRUD + + + + + + + + + \ No newline at end of file diff --git a/spring-security-angular/client/angular4/src/main.ts b/spring-security-angular/client/angular4/src/main.ts new file mode 100644 index 0000000000..49db98ae89 --- /dev/null +++ b/spring-security-angular/client/angular4/src/main.ts @@ -0,0 +1,5 @@ +import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; + +import { AppModule } from './app/app.module'; + +platformBrowserDynamic().bootstrapModule(AppModule); \ No newline at end of file diff --git a/spring-security-angular/client/angular4/src/polyfills.ts b/spring-security-angular/client/angular4/src/polyfills.ts new file mode 100644 index 0000000000..a4984ced57 --- /dev/null +++ b/spring-security-angular/client/angular4/src/polyfills.ts @@ -0,0 +1,68 @@ +/** + * This file includes polyfills needed by Angular and is loaded before the app. + * You can add your own extra polyfills to this file. + * + * This file is divided into 2 sections: + * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. + * 2. Application imports. Files imported after ZoneJS that should be loaded before your main + * file. + * + * The current setup is for so-called "evergreen" browsers; the last versions of browsers that + * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), + * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. + * + * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html + */ + +/*************************************************************************************************** + * BROWSER POLYFILLS + */ + +/** IE9, IE10 and IE11 requires all of the following polyfills. **/ +// import 'core-js/es6/symbol'; +// import 'core-js/es6/object'; +// import 'core-js/es6/function'; +// import 'core-js/es6/parse-int'; +// import 'core-js/es6/parse-float'; +// import 'core-js/es6/number'; +// import 'core-js/es6/math'; +// import 'core-js/es6/string'; +// import 'core-js/es6/date'; +// import 'core-js/es6/array'; +// import 'core-js/es6/regexp'; +// import 'core-js/es6/map'; +// import 'core-js/es6/weak-map'; +// import 'core-js/es6/set'; +/** IE10 and IE11 requires the following for NgClass support on SVG elements */ +// import 'classlist.js'; // Run `npm install --save classlist.js`. +/** Evergreen browsers require these. **/ +import 'core-js/es6/reflect'; +import 'core-js/es7/reflect'; + + +/** + * Required to support Web Animations `@angular/animation`. + * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation + **/ +// import 'web-animations-js'; // Run `npm install --save web-animations-js`. + + +/*************************************************************************************************** + * Zone JS is required by Angular itself. + */ +import 'zone.js/dist/zone'; // Included with Angular CLI. + + +/*************************************************************************************************** + * APPLICATION IMPORTS + */ + +/** + * Date, currency, decimal and percent pipes. + * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 + */ +// import 'intl'; // Run `npm install --save intl`. +/** + * Need to import at least one locale-data with intl. + */ +// import 'intl/locale-data/jsonp/en'; \ No newline at end of file diff --git a/spring-security-angular/client/angular4/src/styles.css b/spring-security-angular/client/angular4/src/styles.css new file mode 100644 index 0000000000..cdd2d591d8 --- /dev/null +++ b/spring-security-angular/client/angular4/src/styles.css @@ -0,0 +1,7 @@ +a { + cursor: pointer; +} + +.help-block { + font-size: 12px; +} \ No newline at end of file diff --git a/spring-security-angular/client/angular4/src/tsconfig.app.json b/spring-security-angular/client/angular4/src/tsconfig.app.json new file mode 100644 index 0000000000..213ce42a1b --- /dev/null +++ b/spring-security-angular/client/angular4/src/tsconfig.app.json @@ -0,0 +1,13 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "outDir": "../out-tsc/app", + "baseUrl": "./", + "module": "es2015", + "types": [] + }, + "exclude": [ + "test.ts", + "**/*.spec.ts" + ] +} \ No newline at end of file diff --git a/spring-security-angular/client/angular4/tsconfig.json b/spring-security-angular/client/angular4/tsconfig.json new file mode 100644 index 0000000000..ef44e2862b --- /dev/null +++ b/spring-security-angular/client/angular4/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compileOnSave": false, + "compilerOptions": { + "baseUrl": "./", + "outDir": "./dist/out-tsc", + "sourceMap": true, + "declaration": false, + "moduleResolution": "node", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "target": "es5", + "typeRoots": [ + "node_modules/@types" + ], + "lib": [ + "es2017", + "dom" + ] + } +} diff --git a/spring-security-angular/client/angular4/tslint.json b/spring-security-angular/client/angular4/tslint.json new file mode 100644 index 0000000000..3ea984c776 --- /dev/null +++ b/spring-security-angular/client/angular4/tslint.json @@ -0,0 +1,130 @@ +{ + "rulesDirectory": [ + "node_modules/codelyzer" + ], + "rules": { + "arrow-return-shorthand": true, + "callable-types": true, + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "curly": true, + "deprecation": { + "severity": "warn" + }, + "eofline": true, + "forin": true, + "import-blacklist": [ + true, + "rxjs/Rx" + ], + "import-spacing": true, + "indent": [ + true, + "spaces" + ], + "interface-over-type-literal": true, + "label-position": true, + "max-line-length": [ + true, + 140 + ], + "member-access": false, + "member-ordering": [ + true, + { + "order": [ + "static-field", + "instance-field", + "static-method", + "instance-method" + ] + } + ], + "no-arg": true, + "no-bitwise": true, + "no-console": [ + true, + "debug", + "info", + "time", + "timeEnd", + "trace" + ], + "no-construct": true, + "no-debugger": true, + "no-duplicate-super": true, + "no-empty": false, + "no-empty-interface": true, + "no-eval": true, + "no-inferrable-types": [ + true, + "ignore-params" + ], + "no-misused-new": true, + "no-non-null-assertion": true, + "no-shadowed-variable": true, + "no-string-literal": false, + "no-string-throw": true, + "no-switch-case-fall-through": true, + "no-trailing-whitespace": true, + "no-unnecessary-initializer": true, + "no-unused-expression": true, + "no-use-before-declare": true, + "no-var-keyword": true, + "object-literal-sort-keys": false, + "one-line": [ + true, + "check-open-brace", + "check-catch", + "check-else", + "check-whitespace" + ], + "prefer-const": true, + "quotemark": [ + true, + "single" + ], + "radix": true, + "semicolon": [ + true, + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "typedef-whitespace": [ + true, + { + "call-signature": "nospace", + "index-signature": "nospace", + "parameter": "nospace", + "property-declaration": "nospace", + "variable-declaration": "nospace" + } + ], + "unified-signatures": true, + "variable-name": false, + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ], + "no-output-on-prefix": true, + "use-input-property-decorator": true, + "use-output-property-decorator": true, + "use-host-property-decorator": true, + "no-input-rename": true, + "no-output-rename": true, + "use-life-cycle-interface": true, + "use-pipe-transform-interface": true, + "component-class-suffix": true, + "directive-class-suffix": true + } +} diff --git a/spring-security-angular/client/angular5/.angular-cli.json b/spring-security-angular/client/angular5/.angular-cli.json new file mode 100644 index 0000000000..d390652214 --- /dev/null +++ b/spring-security-angular/client/angular5/.angular-cli.json @@ -0,0 +1,61 @@ +{ + "$schema": "./node_modules/@angular/cli/lib/config/schema.json", + "project": { + "name": "angular5" + }, + "apps": [ + { + "root": "src", + "outDir": "dist", + "assets": [ + "assets", + "favicon.ico" + ], + "index": "index.html", + "main": "main.ts", + "polyfills": "polyfills.ts", + "test": "test.ts", + "tsconfig": "tsconfig.app.json", + "testTsconfig": "tsconfig.spec.json", + "prefix": "app", + "styles": [ + "styles.css", + "../node_modules/ngx-toastr/toastr.css" + ], + "scripts": [], + "environmentSource": "environments/environment.ts", + "environments": { + "dev": "environments/environment.ts", + "prod": "environments/environment.prod.ts" + } + } + ], + "e2e": { + "protractor": { + "config": "./protractor.conf.js" + } + }, + "lint": [ + { + "project": "src/tsconfig.app.json", + "exclude": "**/node_modules/**" + }, + { + "project": "src/tsconfig.spec.json", + "exclude": "**/node_modules/**" + }, + { + "project": "e2e/tsconfig.e2e.json", + "exclude": "**/node_modules/**" + } + ], + "test": { + "karma": { + "config": "./karma.conf.js" + } + }, + "defaults": { + "styleExt": "css", + "component": {} + } +} \ No newline at end of file diff --git a/spring-security-angular/client/angular5/package.json b/spring-security-angular/client/angular5/package.json new file mode 100644 index 0000000000..45f455d191 --- /dev/null +++ b/spring-security-angular/client/angular5/package.json @@ -0,0 +1,50 @@ +{ + "name": "angular5", + "version": "0.0.0", + "license": "MIT", + "scripts": { + "ng": "ng", + "start": "ng serve", + "build": "ng build --prod", + "test": "ng test", + "lint": "ng lint", + "e2e": "ng e2e" + }, + "private": true, + "dependencies": { + "@angular/animations": "^5.0.0", + "@angular/common": "^5.0.0", + "@angular/compiler": "^5.0.0", + "@angular/core": "^5.0.0", + "@angular/forms": "^5.0.0", + "@angular/http": "^5.0.0", + "@angular/platform-browser": "^5.0.0", + "@angular/platform-browser-dynamic": "^5.0.0", + "@angular/router": "^5.0.0", + "core-js": "^2.4.1", + "ngx-toastr": "^8.1.1", + "rxjs": "^5.5.2", + "zone.js": "^0.8.14" + }, + "devDependencies": { + "@angular/cli": "^1.6.6", + "@angular/compiler-cli": "^5.0.0", + "@angular/language-service": "^5.0.0", + "@types/jasmine": "~2.5.53", + "@types/jasminewd2": "~2.0.2", + "@types/node": "~6.0.60", + "codelyzer": "^4.0.1", + "jasmine-core": "~2.6.2", + "jasmine-spec-reporter": "~4.1.0", + "karma": "~1.7.0", + "karma-chrome-launcher": "~2.1.1", + "karma-cli": "~1.0.1", + "karma-coverage-istanbul-reporter": "^1.2.1", + "karma-jasmine": "~1.1.0", + "karma-jasmine-html-reporter": "^0.2.2", + "protractor": "~5.1.2", + "ts-node": "~3.2.0", + "tslint": "~5.7.0", + "typescript": "~2.4.2" + } +} diff --git a/spring-security-angular/client/angular5/src/app/app.component.html b/spring-security-angular/client/angular5/src/app/app.component.html new file mode 100644 index 0000000000..7f77adea7b --- /dev/null +++ b/spring-security-angular/client/angular5/src/app/app.component.html @@ -0,0 +1,7 @@ +
    +
    +
    + +
    +
    +
    diff --git a/spring-security-angular/client/angular5/src/app/app.component.ts b/spring-security-angular/client/angular5/src/app/app.component.ts new file mode 100644 index 0000000000..36f986c63f --- /dev/null +++ b/spring-security-angular/client/angular5/src/app/app.component.ts @@ -0,0 +1,8 @@ +import { Component } from '@angular/core'; + +@Component({ + selector: 'app-root', + templateUrl: './app.component.html' +}) + +export class AppComponent { } \ No newline at end of file diff --git a/spring-security-angular/client/angular5/src/app/app.module.ts b/spring-security-angular/client/angular5/src/app/app.module.ts new file mode 100644 index 0000000000..9e840e6f13 --- /dev/null +++ b/spring-security-angular/client/angular5/src/app/app.module.ts @@ -0,0 +1,29 @@ +import { NgModule } from '@angular/core'; +import { BrowserModule } from '@angular/platform-browser'; +import { FormsModule } from '@angular/forms'; +import { HttpModule } from '@angular/http'; + +// used to create fake backend + +import { AppComponent } from './app.component'; +import { routing } from './app.routing'; + +import { HomeComponent } from './home/home.component'; +import { LoginComponent } from './login/login.component'; + +@NgModule({ + imports: [ + BrowserModule, + FormsModule, + HttpModule, + routing + ], + declarations: [ + AppComponent, + HomeComponent, + LoginComponent + ], + bootstrap: [AppComponent] +}) + +export class AppModule { } \ No newline at end of file diff --git a/spring-security-angular/client/angular5/src/app/app.routing.ts b/spring-security-angular/client/angular5/src/app/app.routing.ts new file mode 100644 index 0000000000..c794fc5c50 --- /dev/null +++ b/spring-security-angular/client/angular5/src/app/app.routing.ts @@ -0,0 +1,12 @@ +import { Routes, RouterModule } from '@angular/router'; + +import { HomeComponent } from './home/home.component'; +import { LoginComponent } from './login/login.component'; + +const appRoutes: Routes = [ + { path: '', component: HomeComponent}, + { path: 'login', component: LoginComponent }, + { path: '**', redirectTo: '' } +]; + +export const routing = RouterModule.forRoot(appRoutes); \ No newline at end of file diff --git a/spring-security-angular/client/angular5/src/app/home/home.component.html b/spring-security-angular/client/angular5/src/app/home/home.component.html new file mode 100644 index 0000000000..7ccd2c2a3a --- /dev/null +++ b/spring-security-angular/client/angular5/src/app/home/home.component.html @@ -0,0 +1,4 @@ +
    +

    Hi {{userName}}!

    +

    Logout

    +
    \ No newline at end of file diff --git a/spring-security-angular/client/angular5/src/app/home/home.component.ts b/spring-security-angular/client/angular5/src/app/home/home.component.ts new file mode 100644 index 0000000000..7fe1ac4eff --- /dev/null +++ b/spring-security-angular/client/angular5/src/app/home/home.component.ts @@ -0,0 +1,37 @@ +import { Component, OnInit } from '@angular/core'; +import { Http, Headers, RequestOptions } from '@angular/http'; +import 'rxjs/add/operator/map' + +@Component({ + selector:'home', + templateUrl: './home.component.html' +}) + +export class HomeComponent implements OnInit { + + userName: string; + + constructor(private http: Http) { } + + ngOnInit() { + let url = 'http://localhost:8082/user'; + + let headers:Headers = new Headers({ + 'Authorization': 'Basic ' + sessionStorage.getItem('token') + }) + let options = new RequestOptions({headers: headers}); + this.http.post(url,{}, options).map( + res => res.json(), + error => { + if(error.status == 401) + alert('Unauthorized'); + } + ).subscribe(principal => { + this.userName = principal.name; + }); + } + + logout() { + sessionStorage.setItem('token', ''); + } +} \ No newline at end of file diff --git a/spring-security-angular/client/angular5/src/app/login/login.component.html b/spring-security-angular/client/angular5/src/app/login/login.component.html new file mode 100644 index 0000000000..d87b91a7bb --- /dev/null +++ b/spring-security-angular/client/angular5/src/app/login/login.component.html @@ -0,0 +1,18 @@ +
    +

    Login

    +
    +
    + + +
    Username is required
    +
    +
    + + +
    Password is required
    +
    +
    + +
    +
    +
    diff --git a/spring-security-angular/client/angular5/src/app/login/login.component.ts b/spring-security-angular/client/angular5/src/app/login/login.component.ts new file mode 100644 index 0000000000..2db8f32871 --- /dev/null +++ b/spring-security-angular/client/angular5/src/app/login/login.component.ts @@ -0,0 +1,37 @@ +import { Component, OnInit } from '@angular/core'; +import { Router, ActivatedRoute } from '@angular/router'; +import { Http } from '@angular/http'; + +@Component({ + selector: 'login', + templateUrl: './login.component.html' +}) + +export class LoginComponent implements OnInit { + model: any = {}; + + constructor( + private route: ActivatedRoute, + private router: Router, + private http: Http) { } + + ngOnInit() { + sessionStorage.setItem('token', ''); + } + + + login() { + let url = 'http://localhost:8082/login'; + let result = this.http.post(url, { + userName: this.model.username, + password: this.model.password + }).map(res => res.json()).subscribe(isValid => { + if (isValid) { + sessionStorage.setItem('token', btoa(this.model.username + ':' + this.model.password)); + this.router.navigate(['']); + } else { + alert("Authentication failed.") + } + }); + } +} diff --git a/spring-security-angular/client/angular5/src/index.html b/spring-security-angular/client/angular5/src/index.html new file mode 100644 index 0000000000..c716820396 --- /dev/null +++ b/spring-security-angular/client/angular5/src/index.html @@ -0,0 +1,14 @@ + + + + + AngularCRUD + + + + + + + + + \ No newline at end of file diff --git a/spring-security-angular/client/angular5/src/main.ts b/spring-security-angular/client/angular5/src/main.ts new file mode 100644 index 0000000000..49db98ae89 --- /dev/null +++ b/spring-security-angular/client/angular5/src/main.ts @@ -0,0 +1,5 @@ +import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; + +import { AppModule } from './app/app.module'; + +platformBrowserDynamic().bootstrapModule(AppModule); \ No newline at end of file diff --git a/spring-security-angular/client/angular5/src/polyfills.ts b/spring-security-angular/client/angular5/src/polyfills.ts new file mode 100644 index 0000000000..a4984ced57 --- /dev/null +++ b/spring-security-angular/client/angular5/src/polyfills.ts @@ -0,0 +1,68 @@ +/** + * This file includes polyfills needed by Angular and is loaded before the app. + * You can add your own extra polyfills to this file. + * + * This file is divided into 2 sections: + * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. + * 2. Application imports. Files imported after ZoneJS that should be loaded before your main + * file. + * + * The current setup is for so-called "evergreen" browsers; the last versions of browsers that + * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), + * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. + * + * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html + */ + +/*************************************************************************************************** + * BROWSER POLYFILLS + */ + +/** IE9, IE10 and IE11 requires all of the following polyfills. **/ +// import 'core-js/es6/symbol'; +// import 'core-js/es6/object'; +// import 'core-js/es6/function'; +// import 'core-js/es6/parse-int'; +// import 'core-js/es6/parse-float'; +// import 'core-js/es6/number'; +// import 'core-js/es6/math'; +// import 'core-js/es6/string'; +// import 'core-js/es6/date'; +// import 'core-js/es6/array'; +// import 'core-js/es6/regexp'; +// import 'core-js/es6/map'; +// import 'core-js/es6/weak-map'; +// import 'core-js/es6/set'; +/** IE10 and IE11 requires the following for NgClass support on SVG elements */ +// import 'classlist.js'; // Run `npm install --save classlist.js`. +/** Evergreen browsers require these. **/ +import 'core-js/es6/reflect'; +import 'core-js/es7/reflect'; + + +/** + * Required to support Web Animations `@angular/animation`. + * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation + **/ +// import 'web-animations-js'; // Run `npm install --save web-animations-js`. + + +/*************************************************************************************************** + * Zone JS is required by Angular itself. + */ +import 'zone.js/dist/zone'; // Included with Angular CLI. + + +/*************************************************************************************************** + * APPLICATION IMPORTS + */ + +/** + * Date, currency, decimal and percent pipes. + * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 + */ +// import 'intl'; // Run `npm install --save intl`. +/** + * Need to import at least one locale-data with intl. + */ +// import 'intl/locale-data/jsonp/en'; \ No newline at end of file diff --git a/spring-security-angular/client/angular5/src/styles.css b/spring-security-angular/client/angular5/src/styles.css new file mode 100644 index 0000000000..cdd2d591d8 --- /dev/null +++ b/spring-security-angular/client/angular5/src/styles.css @@ -0,0 +1,7 @@ +a { + cursor: pointer; +} + +.help-block { + font-size: 12px; +} \ No newline at end of file diff --git a/spring-security-angular/client/angular5/src/tsconfig.app.json b/spring-security-angular/client/angular5/src/tsconfig.app.json new file mode 100644 index 0000000000..213ce42a1b --- /dev/null +++ b/spring-security-angular/client/angular5/src/tsconfig.app.json @@ -0,0 +1,13 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "outDir": "../out-tsc/app", + "baseUrl": "./", + "module": "es2015", + "types": [] + }, + "exclude": [ + "test.ts", + "**/*.spec.ts" + ] +} \ No newline at end of file diff --git a/spring-security-angular/client/angular5/tsconfig.json b/spring-security-angular/client/angular5/tsconfig.json new file mode 100644 index 0000000000..0fdb5c817d --- /dev/null +++ b/spring-security-angular/client/angular5/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compileOnSave": false, + "compilerOptions": { + "outDir": "./dist/out-tsc", + "sourceMap": true, + "declaration": false, + "moduleResolution": "node", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "target": "es5", + "typeRoots": [ + "node_modules/@types" + ], + "lib": [ + "es2017", + "dom" + ] + } +} \ No newline at end of file diff --git a/spring-security-angular/client/angular5/tslint.json b/spring-security-angular/client/angular5/tslint.json new file mode 100644 index 0000000000..1c1d53b0d9 --- /dev/null +++ b/spring-security-angular/client/angular5/tslint.json @@ -0,0 +1,144 @@ +{ + "rulesDirectory": [ + "node_modules/codelyzer" + ], + "rules": { + "arrow-return-shorthand": true, + "callable-types": true, + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "curly": true, + "deprecation": { + "severity": "warn" + }, + "eofline": true, + "forin": true, + "import-blacklist": [ + true, + "rxjs", + "rxjs/Rx" + ], + "import-spacing": true, + "indent": [ + true, + "spaces" + ], + "interface-over-type-literal": true, + "label-position": true, + "max-line-length": [ + true, + 140 + ], + "member-access": false, + "member-ordering": [ + true, + { + "order": [ + "static-field", + "instance-field", + "static-method", + "instance-method" + ] + } + ], + "no-arg": true, + "no-bitwise": true, + "no-console": [ + true, + "debug", + "info", + "time", + "timeEnd", + "trace" + ], + "no-construct": true, + "no-debugger": true, + "no-duplicate-super": true, + "no-empty": false, + "no-empty-interface": true, + "no-eval": true, + "no-inferrable-types": [ + true, + "ignore-params" + ], + "no-misused-new": true, + "no-non-null-assertion": true, + "no-shadowed-variable": true, + "no-string-literal": false, + "no-string-throw": true, + "no-switch-case-fall-through": true, + "no-trailing-whitespace": true, + "no-unnecessary-initializer": true, + "no-unused-expression": true, + "no-use-before-declare": true, + "no-var-keyword": true, + "object-literal-sort-keys": false, + "one-line": [ + true, + "check-open-brace", + "check-catch", + "check-else", + "check-whitespace" + ], + "prefer-const": true, + "quotemark": [ + true, + "single" + ], + "radix": true, + "semicolon": [ + true, + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "typedef-whitespace": [ + true, + { + "call-signature": "nospace", + "index-signature": "nospace", + "parameter": "nospace", + "property-declaration": "nospace", + "variable-declaration": "nospace" + } + ], + "typeof-compare": true, + "unified-signatures": true, + "variable-name": false, + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ], + "directive-selector": [ + true, + "attribute", + "app", + "camelCase" + ], + "component-selector": [ + true, + "element", + "app", + "kebab-case" + ], + "no-output-on-prefix": true, + "use-input-property-decorator": true, + "use-output-property-decorator": true, + "use-host-property-decorator": true, + "no-input-rename": true, + "no-output-rename": true, + "use-life-cycle-interface": true, + "use-pipe-transform-interface": true, + "component-class-suffix": true, + "directive-class-suffix": true + } +} \ No newline at end of file diff --git a/spring-security-angular/client/angular6/angular.json b/spring-security-angular/client/angular6/angular.json new file mode 100644 index 0000000000..0168c58817 --- /dev/null +++ b/spring-security-angular/client/angular6/angular.json @@ -0,0 +1,127 @@ +{ + "$schema": "./node_modules/@angular/cli/lib/config/schema.json", + "version": 1, + "newProjectRoot": "projects", + "projects": { + "angular6-login": { + "root": "", + "sourceRoot": "src", + "projectType": "application", + "prefix": "app", + "schematics": {}, + "architect": { + "build": { + "builder": "@angular-devkit/build-angular:browser", + "options": { + "outputPath": "dist/angular6-login", + "index": "src/index.html", + "main": "src/main.ts", + "polyfills": "src/polyfills.ts", + "tsConfig": "src/tsconfig.app.json", + "assets": [ + "src/favicon.ico", + "src/assets" + ], + "styles": [ + "src/styles.css" + ], + "scripts": [] + }, + "configurations": { + "production": { + "fileReplacements": [ + { + "replace": "src/environments/environment.ts", + "with": "src/environments/environment.prod.ts" + } + ], + "optimization": true, + "outputHashing": "all", + "sourceMap": false, + "extractCss": true, + "namedChunks": false, + "aot": true, + "extractLicenses": true, + "vendorChunk": false, + "buildOptimizer": true + } + } + }, + "serve": { + "builder": "@angular-devkit/build-angular:dev-server", + "options": { + "browserTarget": "angular6-login:build" + }, + "configurations": { + "production": { + "browserTarget": "angular6-login:build:production" + } + } + }, + "extract-i18n": { + "builder": "@angular-devkit/build-angular:extract-i18n", + "options": { + "browserTarget": "angular6-login:build" + } + }, + "test": { + "builder": "@angular-devkit/build-angular:karma", + "options": { + "main": "src/test.ts", + "polyfills": "src/polyfills.ts", + "tsConfig": "src/tsconfig.spec.json", + "karmaConfig": "src/karma.conf.js", + "styles": [ + "src/styles.css" + ], + "scripts": [], + "assets": [ + "src/favicon.ico", + "src/assets" + ] + } + }, + "lint": { + "builder": "@angular-devkit/build-angular:tslint", + "options": { + "tsConfig": [ + "src/tsconfig.app.json", + "src/tsconfig.spec.json" + ], + "exclude": [ + "**/node_modules/**" + ] + } + } + } + }, + "angular6-login-e2e": { + "root": "e2e/", + "projectType": "application", + "architect": { + "e2e": { + "builder": "@angular-devkit/build-angular:protractor", + "options": { + "protractorConfig": "e2e/protractor.conf.js", + "devServerTarget": "angular6-login:serve" + }, + "configurations": { + "production": { + "devServerTarget": "angular6-login:serve:production" + } + } + }, + "lint": { + "builder": "@angular-devkit/build-angular:tslint", + "options": { + "tsConfig": "e2e/tsconfig.e2e.json", + "exclude": [ + "**/node_modules/**" + ] + } + } + } + } + }, + "defaultProject": "angular6-login" +} \ No newline at end of file diff --git a/spring-security-angular/client/angular6/package.json b/spring-security-angular/client/angular6/package.json new file mode 100644 index 0000000000..a0adcd03f3 --- /dev/null +++ b/spring-security-angular/client/angular6/package.json @@ -0,0 +1,48 @@ +{ + "name": "angular6-login", + "version": "0.0.0", + "scripts": { + "ng": "ng", + "start": "ng serve", + "build": "ng build", + "test": "ng test", + "lint": "ng lint", + "e2e": "ng e2e" + }, + "private": true, + "dependencies": { + "@angular/animations": "^6.0.3", + "@angular/common": "^6.0.3", + "@angular/compiler": "^6.0.3", + "@angular/core": "^6.0.3", + "@angular/forms": "^6.0.3", + "@angular/http": "^6.0.3", + "@angular/platform-browser": "^6.0.3", + "@angular/platform-browser-dynamic": "^6.0.3", + "@angular/router": "^6.0.3", + "core-js": "^2.5.4", + "rxjs": "^6.0.0", + "zone.js": "^0.8.26" + }, + "devDependencies": { + "@angular/compiler-cli": "^6.0.3", + "@angular-devkit/build-angular": "~0.6.8", + "typescript": "~2.7.2", + "@angular/cli": "~6.0.8", + "@angular/language-service": "^6.0.3", + "@types/jasmine": "~2.8.6", + "@types/jasminewd2": "~2.0.3", + "@types/node": "~8.9.4", + "codelyzer": "~4.2.1", + "jasmine-core": "~2.99.1", + "jasmine-spec-reporter": "~4.2.1", + "karma": "~1.7.1", + "karma-chrome-launcher": "~2.2.0", + "karma-coverage-istanbul-reporter": "~2.0.0", + "karma-jasmine": "~1.1.1", + "karma-jasmine-html-reporter": "^0.2.2", + "protractor": "~5.3.0", + "ts-node": "~5.0.1", + "tslint": "~5.9.1" + } +} diff --git a/spring-security-angular/client/angular6/src/app/app.component.html b/spring-security-angular/client/angular6/src/app/app.component.html new file mode 100644 index 0000000000..6bf00f3018 --- /dev/null +++ b/spring-security-angular/client/angular6/src/app/app.component.html @@ -0,0 +1,2 @@ + + diff --git a/spring-security-angular/client/angular6/src/app/app.component.ts b/spring-security-angular/client/angular6/src/app/app.component.ts new file mode 100644 index 0000000000..36f986c63f --- /dev/null +++ b/spring-security-angular/client/angular6/src/app/app.component.ts @@ -0,0 +1,8 @@ +import { Component } from '@angular/core'; + +@Component({ + selector: 'app-root', + templateUrl: './app.component.html' +}) + +export class AppComponent { } \ No newline at end of file diff --git a/spring-security-angular/client/angular6/src/app/app.module.ts b/spring-security-angular/client/angular6/src/app/app.module.ts new file mode 100644 index 0000000000..4f9a792e19 --- /dev/null +++ b/spring-security-angular/client/angular6/src/app/app.module.ts @@ -0,0 +1,27 @@ +import { NgModule } from '@angular/core'; +import { BrowserModule } from '@angular/platform-browser'; +import { FormsModule } from '@angular/forms'; +import { HttpClientModule } from '@angular/common/http'; + +import { AppComponent } from './app.component'; +import { routing } from './app.routing'; + +import { HomeComponent } from './home/home.component'; +import { LoginComponent } from './login/login.component'; + +@NgModule({ + imports: [ + BrowserModule, + FormsModule, + HttpClientModule, + routing + ], + declarations: [ + AppComponent, + HomeComponent, + LoginComponent + ], + bootstrap: [AppComponent] +}) + +export class AppModule { } \ No newline at end of file diff --git a/spring-security-angular/client/angular6/src/app/app.routing.ts b/spring-security-angular/client/angular6/src/app/app.routing.ts new file mode 100644 index 0000000000..e5f5e04aa8 --- /dev/null +++ b/spring-security-angular/client/angular6/src/app/app.routing.ts @@ -0,0 +1,11 @@ +import { Routes, RouterModule } from '@angular/router'; +import { HomeComponent } from './home/home.component'; +import { LoginComponent } from './login/login.component'; + +const appRoutes: Routes = [ + { path: '', component: HomeComponent }, + { path: 'login', component: LoginComponent }, + { path: '**', redirectTo: '' } +]; + +export const routing = RouterModule.forRoot(appRoutes); \ No newline at end of file diff --git a/spring-security-angular/client/angular6/src/app/home/home.component.html b/spring-security-angular/client/angular6/src/app/home/home.component.html new file mode 100644 index 0000000000..7ccd2c2a3a --- /dev/null +++ b/spring-security-angular/client/angular6/src/app/home/home.component.html @@ -0,0 +1,4 @@ +
    +

    Hi {{userName}}!

    +

    Logout

    +
    \ No newline at end of file diff --git a/spring-security-angular/client/angular6/src/app/home/home.component.ts b/spring-security-angular/client/angular6/src/app/home/home.component.ts new file mode 100644 index 0000000000..6c9fcfd97f --- /dev/null +++ b/spring-security-angular/client/angular6/src/app/home/home.component.ts @@ -0,0 +1,49 @@ +import { Component, OnInit } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'; +import { Observable, throwError } from 'rxjs'; +import { catchError, map, tap} from 'rxjs/operators'; +@Component({ + selector: 'home', + templateUrl: './home.component.html' +}) + +export class HomeComponent implements OnInit { + + userName: string; + + constructor(private http: HttpClient) { } + + ngOnInit() { + let url = 'http://localhost:8082/user'; + + let headers: HttpHeaders = new HttpHeaders({ + 'Authorization': 'Basic ' + sessionStorage.getItem('token') + }); + + let options = { headers: headers }; + this.http.post>(url, {}, options). + subscribe(principal => { + this.userName = principal['name']; + }, + error => { + if(error.status == 401) + alert('Unauthorized'); + } + ); + } + + logout() { + sessionStorage.setItem('token', ''); + } + private handleError(error: HttpErrorResponse) { + if (error.error instanceof ErrorEvent) { + console.error('An error occurred:', error.error.message); + } else { + console.error( + `Backend returned code ${error.status}, ` + + `body was: ${error.error}`); + } + return throwError( + 'Something bad happened; please try again later.'); + }; +} \ No newline at end of file diff --git a/spring-security-angular/client/angular6/src/app/login/login.component.html b/spring-security-angular/client/angular6/src/app/login/login.component.html new file mode 100644 index 0000000000..4291206469 --- /dev/null +++ b/spring-security-angular/client/angular6/src/app/login/login.component.html @@ -0,0 +1,15 @@ +
    +
    + + +
    Username is required
    +
    +
    + + +
    Password is required
    +
    +
    + +
    +
    \ No newline at end of file diff --git a/spring-security-angular/client/angular6/src/app/login/login.component.ts b/spring-security-angular/client/angular6/src/app/login/login.component.ts new file mode 100644 index 0000000000..27af9ebba5 --- /dev/null +++ b/spring-security-angular/client/angular6/src/app/login/login.component.ts @@ -0,0 +1,39 @@ +import { Component, OnInit } from '@angular/core'; +import { Router, ActivatedRoute } from '@angular/router'; +import { HttpClient } from '@angular/common/http'; +import { Observable } from 'rxjs'; + +@Component({ + selector: 'login', + templateUrl: './login.component.html' +}) + +export class LoginComponent implements OnInit { + + model: any = {}; + + constructor( + private route: ActivatedRoute, + private router: Router, + private http: HttpClient + ) { } + + ngOnInit() { + sessionStorage.setItem('token', ''); + } + + login() { + let url = 'http://localhost:8082/login'; + this.http.post>(url, { + userName: this.model.username, + password: this.model.password + }).subscribe(isValid => { + if (isValid) { + sessionStorage.setItem('token', btoa(this.model.username + ':' + this.model.password)); + this.router.navigate(['']); + } else { + alert("Authentication failed.") + } + }); + } +} diff --git a/spring-security-angular/client/angular6/src/index.html b/spring-security-angular/client/angular6/src/index.html new file mode 100644 index 0000000000..c716820396 --- /dev/null +++ b/spring-security-angular/client/angular6/src/index.html @@ -0,0 +1,14 @@ + + + + + AngularCRUD + + + + + + + + + \ No newline at end of file diff --git a/spring-security-angular/client/angular6/src/main.ts b/spring-security-angular/client/angular6/src/main.ts new file mode 100644 index 0000000000..49db98ae89 --- /dev/null +++ b/spring-security-angular/client/angular6/src/main.ts @@ -0,0 +1,5 @@ +import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; + +import { AppModule } from './app/app.module'; + +platformBrowserDynamic().bootstrapModule(AppModule); \ No newline at end of file diff --git a/spring-security-angular/client/angular6/src/polyfills.ts b/spring-security-angular/client/angular6/src/polyfills.ts new file mode 100644 index 0000000000..a4984ced57 --- /dev/null +++ b/spring-security-angular/client/angular6/src/polyfills.ts @@ -0,0 +1,68 @@ +/** + * This file includes polyfills needed by Angular and is loaded before the app. + * You can add your own extra polyfills to this file. + * + * This file is divided into 2 sections: + * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. + * 2. Application imports. Files imported after ZoneJS that should be loaded before your main + * file. + * + * The current setup is for so-called "evergreen" browsers; the last versions of browsers that + * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), + * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. + * + * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html + */ + +/*************************************************************************************************** + * BROWSER POLYFILLS + */ + +/** IE9, IE10 and IE11 requires all of the following polyfills. **/ +// import 'core-js/es6/symbol'; +// import 'core-js/es6/object'; +// import 'core-js/es6/function'; +// import 'core-js/es6/parse-int'; +// import 'core-js/es6/parse-float'; +// import 'core-js/es6/number'; +// import 'core-js/es6/math'; +// import 'core-js/es6/string'; +// import 'core-js/es6/date'; +// import 'core-js/es6/array'; +// import 'core-js/es6/regexp'; +// import 'core-js/es6/map'; +// import 'core-js/es6/weak-map'; +// import 'core-js/es6/set'; +/** IE10 and IE11 requires the following for NgClass support on SVG elements */ +// import 'classlist.js'; // Run `npm install --save classlist.js`. +/** Evergreen browsers require these. **/ +import 'core-js/es6/reflect'; +import 'core-js/es7/reflect'; + + +/** + * Required to support Web Animations `@angular/animation`. + * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation + **/ +// import 'web-animations-js'; // Run `npm install --save web-animations-js`. + + +/*************************************************************************************************** + * Zone JS is required by Angular itself. + */ +import 'zone.js/dist/zone'; // Included with Angular CLI. + + +/*************************************************************************************************** + * APPLICATION IMPORTS + */ + +/** + * Date, currency, decimal and percent pipes. + * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 + */ +// import 'intl'; // Run `npm install --save intl`. +/** + * Need to import at least one locale-data with intl. + */ +// import 'intl/locale-data/jsonp/en'; \ No newline at end of file diff --git a/spring-security-angular/client/angular6/src/styles.css b/spring-security-angular/client/angular6/src/styles.css new file mode 100644 index 0000000000..cdd2d591d8 --- /dev/null +++ b/spring-security-angular/client/angular6/src/styles.css @@ -0,0 +1,7 @@ +a { + cursor: pointer; +} + +.help-block { + font-size: 12px; +} \ No newline at end of file diff --git a/spring-security-angular/client/angular6/src/tsconfig.app.json b/spring-security-angular/client/angular6/src/tsconfig.app.json new file mode 100644 index 0000000000..213ce42a1b --- /dev/null +++ b/spring-security-angular/client/angular6/src/tsconfig.app.json @@ -0,0 +1,13 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "outDir": "../out-tsc/app", + "baseUrl": "./", + "module": "es2015", + "types": [] + }, + "exclude": [ + "test.ts", + "**/*.spec.ts" + ] +} \ No newline at end of file diff --git a/spring-security-angular/client/angular6/tsconfig.json b/spring-security-angular/client/angular6/tsconfig.json new file mode 100644 index 0000000000..ef44e2862b --- /dev/null +++ b/spring-security-angular/client/angular6/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compileOnSave": false, + "compilerOptions": { + "baseUrl": "./", + "outDir": "./dist/out-tsc", + "sourceMap": true, + "declaration": false, + "moduleResolution": "node", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "target": "es5", + "typeRoots": [ + "node_modules/@types" + ], + "lib": [ + "es2017", + "dom" + ] + } +} diff --git a/spring-security-angular/client/angular6/tslint.json b/spring-security-angular/client/angular6/tslint.json new file mode 100644 index 0000000000..3ea984c776 --- /dev/null +++ b/spring-security-angular/client/angular6/tslint.json @@ -0,0 +1,130 @@ +{ + "rulesDirectory": [ + "node_modules/codelyzer" + ], + "rules": { + "arrow-return-shorthand": true, + "callable-types": true, + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "curly": true, + "deprecation": { + "severity": "warn" + }, + "eofline": true, + "forin": true, + "import-blacklist": [ + true, + "rxjs/Rx" + ], + "import-spacing": true, + "indent": [ + true, + "spaces" + ], + "interface-over-type-literal": true, + "label-position": true, + "max-line-length": [ + true, + 140 + ], + "member-access": false, + "member-ordering": [ + true, + { + "order": [ + "static-field", + "instance-field", + "static-method", + "instance-method" + ] + } + ], + "no-arg": true, + "no-bitwise": true, + "no-console": [ + true, + "debug", + "info", + "time", + "timeEnd", + "trace" + ], + "no-construct": true, + "no-debugger": true, + "no-duplicate-super": true, + "no-empty": false, + "no-empty-interface": true, + "no-eval": true, + "no-inferrable-types": [ + true, + "ignore-params" + ], + "no-misused-new": true, + "no-non-null-assertion": true, + "no-shadowed-variable": true, + "no-string-literal": false, + "no-string-throw": true, + "no-switch-case-fall-through": true, + "no-trailing-whitespace": true, + "no-unnecessary-initializer": true, + "no-unused-expression": true, + "no-use-before-declare": true, + "no-var-keyword": true, + "object-literal-sort-keys": false, + "one-line": [ + true, + "check-open-brace", + "check-catch", + "check-else", + "check-whitespace" + ], + "prefer-const": true, + "quotemark": [ + true, + "single" + ], + "radix": true, + "semicolon": [ + true, + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "typedef-whitespace": [ + true, + { + "call-signature": "nospace", + "index-signature": "nospace", + "parameter": "nospace", + "property-declaration": "nospace", + "variable-declaration": "nospace" + } + ], + "unified-signatures": true, + "variable-name": false, + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ], + "no-output-on-prefix": true, + "use-input-property-decorator": true, + "use-output-property-decorator": true, + "use-host-property-decorator": true, + "no-input-rename": true, + "no-output-rename": true, + "use-life-cycle-interface": true, + "use-pipe-transform-interface": true, + "component-class-suffix": true, + "directive-class-suffix": true + } +} diff --git a/spring-security-angular/server/pom.xml b/spring-security-angular/server/pom.xml new file mode 100644 index 0000000000..c1faecca55 --- /dev/null +++ b/spring-security-angular/server/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + com.baeldung + spring-security-angular + 0.0.1-SNAPSHOT + jar + spring-security-angular + Spring Security Angular + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + + + org.springframework.boot + spring-boot-dependencies + 1.5.9.RELEASE + pom + import + + + + + + + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + UTF-8 + + + diff --git a/spring-security-angular/server/src/main/java/com/baeldung/springbootsecurityrest/basicauth/SpringBootSecurityApplication.java b/spring-security-angular/server/src/main/java/com/baeldung/springbootsecurityrest/basicauth/SpringBootSecurityApplication.java new file mode 100644 index 0000000000..681c7590a8 --- /dev/null +++ b/spring-security-angular/server/src/main/java/com/baeldung/springbootsecurityrest/basicauth/SpringBootSecurityApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.springbootsecurityrest.basicauth; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication(scanBasePackages = "com.baeldung.springbootsecurityrest") +@EnableAutoConfiguration +public class SpringBootSecurityApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootSecurityApplication.class, args); + } +} diff --git a/spring-security-angular/server/src/main/java/com/baeldung/springbootsecurityrest/basicauth/config/BasicAuthConfiguration.java b/spring-security-angular/server/src/main/java/com/baeldung/springbootsecurityrest/basicauth/config/BasicAuthConfiguration.java new file mode 100644 index 0000000000..3ed301439c --- /dev/null +++ b/spring-security-angular/server/src/main/java/com/baeldung/springbootsecurityrest/basicauth/config/BasicAuthConfiguration.java @@ -0,0 +1,34 @@ +package com.baeldung.springbootsecurityrest.basicauth.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class BasicAuthConfiguration extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth + .inMemoryAuthentication() + .withUser("user") + .password("password") + .roles("USER"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable() + .authorizeRequests() + .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() + .antMatchers("/login").permitAll() + .anyRequest() + .authenticated() + .and() + .httpBasic(); + } +} diff --git a/spring-security-angular/server/src/main/java/com/baeldung/springbootsecurityrest/controller/UserController.java b/spring-security-angular/server/src/main/java/com/baeldung/springbootsecurityrest/controller/UserController.java new file mode 100644 index 0000000000..ab66065b61 --- /dev/null +++ b/spring-security-angular/server/src/main/java/com/baeldung/springbootsecurityrest/controller/UserController.java @@ -0,0 +1,29 @@ +package com.baeldung.springbootsecurityrest.controller; + +import java.security.Principal; +import java.util.Base64; + +import javax.servlet.http.HttpServletRequest; + +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.springbootsecurityrest.vo.User; + +@RestController +@CrossOrigin +public class UserController { + + @RequestMapping("/login") + public boolean login(@RequestBody User user) { + return user.getUserName().equals("user") && user.getPassword().equals("password"); + } + + @RequestMapping("/user") + public Principal user(HttpServletRequest request) { + String authToken = request.getHeader("Authorization").substring("Basic".length()).trim(); + return () -> new String(Base64.getDecoder().decode(authToken)).split(":")[0]; + } +} diff --git a/spring-security-angular/server/src/main/java/com/baeldung/springbootsecurityrest/vo/User.java b/spring-security-angular/server/src/main/java/com/baeldung/springbootsecurityrest/vo/User.java new file mode 100644 index 0000000000..0eda5ce9ec --- /dev/null +++ b/spring-security-angular/server/src/main/java/com/baeldung/springbootsecurityrest/vo/User.java @@ -0,0 +1,21 @@ +package com.baeldung.springbootsecurityrest.vo; + + +public class User { + + 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; + } +} diff --git a/spring-security-angular/server/src/main/resources/application.properties b/spring-security-angular/server/src/main/resources/application.properties new file mode 100644 index 0000000000..565d97a7b0 --- /dev/null +++ b/spring-security-angular/server/src/main/resources/application.properties @@ -0,0 +1,5 @@ +#spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration +#security.user.password=password +#security.oauth2.client.client-id=client +#security.oauth2.client.client-secret=secret +server.port=8082 diff --git a/spring-security-angular/server/src/main/resources/logback.xml b/spring-security-angular/server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-angular/server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-angular/server/src/test/java/com/baeldung/springbootsecurityrest/BasicAuthConfigurationIntegrationTest.java b/spring-security-angular/server/src/test/java/com/baeldung/springbootsecurityrest/BasicAuthConfigurationIntegrationTest.java new file mode 100644 index 0000000000..952a0806a1 --- /dev/null +++ b/spring-security-angular/server/src/test/java/com/baeldung/springbootsecurityrest/BasicAuthConfigurationIntegrationTest.java @@ -0,0 +1,87 @@ +package com.baeldung.springbootsecurityrest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; + +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.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootsecurityrest.basicauth.SpringBootSecurityApplication; +import com.baeldung.springbootsecurityrest.vo.User; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = RANDOM_PORT, classes = SpringBootSecurityApplication.class) +public class BasicAuthConfigurationIntegrationTest { + + TestRestTemplate restTemplate; + URL base; + + @LocalServerPort int port; + + @Before + public void setUp() throws MalformedURLException { + restTemplate = new TestRestTemplate("user", "password"); + base = new URL("http://localhost:" + port); + } + + @Test + public void givenCorrectCredentials_whenLogin_ThenSuccess() throws IllegalStateException, IOException { + restTemplate = new TestRestTemplate(); + User user = new User(); + user.setUserName("user"); + user.setPassword("password"); + ResponseEntity response = restTemplate.postForEntity(base.toString()+"/login",user, String.class); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertTrue(response + .getBody() + .contains("true")); + } + + @Test + public void givenWrongCredentials_whenLogin_ThenReturnFalse() throws IllegalStateException, IOException { + restTemplate = new TestRestTemplate(); + User user = new User(); + user.setUserName("user"); + user.setPassword("wrongpassword"); + ResponseEntity response = restTemplate.postForEntity(base.toString()+"/login",user, String.class); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertTrue(response + .getBody() + .contains("false")); + } + + @Test + public void givenLoggedInUser_whenRequestsHomePage_ThenSuccess() throws IllegalStateException, IOException { + ResponseEntity response = restTemplate.getForEntity(base.toString()+"/user", String.class); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertTrue(response + .getBody() + .contains("user")); + } + + @Test + public void givenWrongCredentials_whenRequestsHomePage_ThenUnauthorized() throws IllegalStateException, IOException { + restTemplate = new TestRestTemplate("user", "wrongpassword"); + ResponseEntity response = restTemplate.getForEntity(base.toString()+"/user", String.class); + + assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); + assertTrue(response + .getBody() + .contains("Unauthorized")); + } +} diff --git a/spring-security-cache-control/pom.xml b/spring-security-cache-control/pom.xml index 890ff5bd3f..b7dfc9db3a 100644 --- a/spring-security-cache-control/pom.xml +++ b/spring-security-cache-control/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung @@ -8,10 +8,10 @@ 1.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-security-cache-control/src/main/resources/logback.xml b/spring-security-cache-control/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-cache-control/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authentication/pom.xml b/spring-security-client/spring-security-jsp-authentication/pom.xml index 9b1ebc6fdc..0e564b47b8 100644 --- a/spring-security-client/spring-security-jsp-authentication/pom.xml +++ b/spring-security-client/spring-security-jsp-authentication/pom.xml @@ -1,21 +1,19 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-security-jsp-authentication 0.0.1-SNAPSHOT war - spring-security-jsp-authenticate Spring Security JSP Authentication tag sample - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 @@ -27,28 +25,23 @@ org.springframework.boot spring-boot-starter-web - org.springframework.boot spring-boot-starter-tomcat - org.apache.tomcat.embed tomcat-embed-jasper provided - javax.servlet jstl - org.springframework.security spring-security-taglibs - diff --git a/spring-security-client/spring-security-jsp-authentication/src/main/resources/logback.xml b/spring-security-client/spring-security-jsp-authentication/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authentication/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authorize/pom.xml b/spring-security-client/spring-security-jsp-authorize/pom.xml index ee8c9bacbd..427ba7754a 100644 --- a/spring-security-client/spring-security-jsp-authorize/pom.xml +++ b/spring-security-client/spring-security-jsp-authorize/pom.xml @@ -1,21 +1,20 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-security-jsp-authorize 0.0.1-SNAPSHOT war - spring-security-jsp-authorize Spring Security JSP Authorize tag sample - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 @@ -27,28 +26,23 @@ org.springframework.boot spring-boot-starter-web - org.springframework.boot spring-boot-starter-tomcat - org.apache.tomcat.embed tomcat-embed-jasper provided - javax.servlet jstl - org.springframework.security spring-security-taglibs - diff --git a/spring-security-client/spring-security-jsp-authorize/src/main/resources/logback.xml b/spring-security-client/spring-security-jsp-authorize/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-config/pom.xml b/spring-security-client/spring-security-jsp-config/pom.xml index 0ec72c3527..c0318a2c5c 100644 --- a/spring-security-client/spring-security-jsp-config/pom.xml +++ b/spring-security-client/spring-security-jsp-config/pom.xml @@ -1,21 +1,19 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-security-jsp-config 0.0.1-SNAPSHOT war - spring-security-jsp-config Spring Security JSP configuration - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 @@ -27,28 +25,23 @@ org.springframework.boot spring-boot-starter-web - org.springframework.boot spring-boot-starter-tomcat - org.apache.tomcat.embed tomcat-embed-jasper provided - javax.servlet jstl - org.springframework.security spring-security-taglibs - diff --git a/spring-security-client/spring-security-jsp-config/src/main/resources/logback.xml b/spring-security-client/spring-security-jsp-config/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-client/spring-security-mvc/pom.xml b/spring-security-client/spring-security-mvc/pom.xml index a6c3065cc8..6ddc6fbe65 100644 --- a/spring-security-client/spring-security-mvc/pom.xml +++ b/spring-security-client/spring-security-mvc/pom.xml @@ -1,21 +1,19 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-security-mvc 0.0.1-SNAPSHOT war - spring-security-mvc Spring Security MVC - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 @@ -27,7 +25,6 @@ org.springframework.boot spring-boot-starter-web - diff --git a/spring-security-client/spring-security-mvc/src/main/resources/logback.xml b/spring-security-client/spring-security-mvc/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-client/spring-security-mvc/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml index 345daa9570..8e6a352af1 100644 --- a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml +++ b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml @@ -1,21 +1,20 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-security-thymeleaf-authentication 0.0.1-SNAPSHOT war - spring-security-thymeleaf-authentication Spring Security thymeleaf authentication tag sample - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 @@ -27,22 +26,18 @@ org.springframework.boot spring-boot-starter-web - org.springframework.boot spring-boot-starter-tomcat - org.springframework.boot spring-boot-starter-thymeleaf - org.thymeleaf.extras thymeleaf-extras-springsecurity4 - diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/logback.xml b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authorize/pom.xml b/spring-security-client/spring-security-thymeleaf-authorize/pom.xml index 3e66e9f613..52972c0241 100644 --- a/spring-security-client/spring-security-thymeleaf-authorize/pom.xml +++ b/spring-security-client/spring-security-thymeleaf-authorize/pom.xml @@ -1,21 +1,20 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-security-thymeleaf-authorize 0.0.1-SNAPSHOT war - spring-security-thymeleaf-authorize Spring Security thymeleaf authorize tag sample - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 @@ -27,22 +26,18 @@ org.springframework.boot spring-boot-starter-web - org.springframework.boot spring-boot-starter-tomcat - org.springframework.boot spring-boot-starter-thymeleaf - org.thymeleaf.extras thymeleaf-extras-springsecurity4 - diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/logback.xml b/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-config/pom.xml b/spring-security-client/spring-security-thymeleaf-config/pom.xml index f5d4306754..668f20c001 100644 --- a/spring-security-client/spring-security-thymeleaf-config/pom.xml +++ b/spring-security-client/spring-security-thymeleaf-config/pom.xml @@ -1,21 +1,20 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-security-thymeleaf-config 0.0.1-SNAPSHOT war - spring-security-thymeleaf-config Spring Security thymeleaf configuration sample project - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 @@ -27,22 +26,18 @@ org.springframework.boot spring-boot-starter-web - org.springframework.boot spring-boot-starter-tomcat - org.springframework.boot spring-boot-starter-thymeleaf - org.thymeleaf.extras thymeleaf-extras-springsecurity4 - diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/resources/logback.xml b/spring-security-client/spring-security-thymeleaf-config/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-core/pom.xml b/spring-security-core/pom.xml index 27c6741790..41dea087d3 100644 --- a/spring-security-core/pom.xml +++ b/spring-security-core/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-security-core @@ -9,10 +9,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -56,16 +56,12 @@ true - - org.apache.maven.plugins maven-war-plugin - - @@ -73,7 +69,6 @@ live - org.apache.maven.plugins maven-surefire-plugin @@ -97,7 +92,6 @@ - diff --git a/spring-security-core/src/main/resources/logback.xml b/spring-security-core/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-core/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-mvc-boot/README.MD b/spring-security-mvc-boot/README.MD index 32976b0896..eec61f087f 100644 --- a/spring-security-mvc-boot/README.MD +++ b/spring-security-mvc-boot/README.MD @@ -1,7 +1,7 @@ -###The Course +### The Course The "REST With Spring" Classes: http://github.learnspringsecurity.com -###Relevant Articles: +### Relevant Articles: - [A Custom Security Expression with Spring Security](http://www.baeldung.com/spring-security-create-new-custom-security-expression) - [Custom AccessDecisionVoters in Spring Security](http://www.baeldung.com/spring-security-custom-voter) - [Spring Security: Authentication with a Database-backed UserDetailsService](http://www.baeldung.com/spring-security-authentication-with-a-database) @@ -9,3 +9,4 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com - [Multiple Entry Points in Spring Security](http://www.baeldung.com/spring-security-multiple-entry-points) - [Multiple Authentication Providers in Spring Security](http://www.baeldung.com/spring-security-multiple-auth-providers) - [Granted Authority Versus Role in Spring Security](http://www.baeldung.com/spring-security-granted-authority-vs-role) +- [Spring Data with Spring Security](https://www.baeldung.com/spring-data-security) diff --git a/spring-security-mvc-boot/pom.xml b/spring-security-mvc-boot/pom.xml index fe95461eab..4090beab99 100644 --- a/spring-security-mvc-boot/pom.xml +++ b/spring-security-mvc-boot/pom.xml @@ -7,7 +7,6 @@ spring-security-mvc-boot 0.0.1-SNAPSHOT war - spring-security-mvc-boot Spring Security MVC Boot @@ -19,7 +18,6 @@ - org.springframework.boot spring-boot-starter-security @@ -32,53 +30,46 @@ org.springframework.boot spring-boot-starter-tomcat - org.springframework.boot spring-boot-starter-thymeleaf - org.thymeleaf.extras thymeleaf-extras-springsecurity4 - - - org.springframework.boot spring-boot-starter-data-jpa - + + org.springframework.security + spring-security-data + com.h2database h2 - org.hamcrest hamcrest-core test - org.hamcrest hamcrest-library test - org.springframework spring-test test - org.springframework.security spring-security-test test - taglibs standard @@ -88,18 +79,15 @@ org.springframework.security spring-security-taglibs - org.springframework.security spring-security-core - javax.servlet.jsp.jstl jstl-api ${jstl.version} - org.springframework.security spring-security-config @@ -111,7 +99,7 @@ net.sf.ehcache ehcache-core - 2.6.11 + ${ehcache-core.version} jar @@ -211,6 +199,7 @@ **/*LiveTest.java **/*IntegrationTest.java + **/*IntTest.java **/*EntryPointsTest.java @@ -245,6 +234,7 @@ 1.1.2 1.2 1.6.1 + 2.6.11 diff --git a/spring-data-spring-security/src/main/java/com/baeldung/AppConfig.java b/spring-security-mvc-boot/src/main/java/com/baeldung/AppConfig.java similarity index 100% rename from spring-data-spring-security/src/main/java/com/baeldung/AppConfig.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/AppConfig.java diff --git a/spring-data-spring-security/src/main/java/com/baeldung/SpringSecurityConfig.java b/spring-security-mvc-boot/src/main/java/com/baeldung/SpringSecurityConfig.java similarity index 100% rename from spring-data-spring-security/src/main/java/com/baeldung/SpringSecurityConfig.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/SpringSecurityConfig.java diff --git a/spring-data-spring-security/src/main/java/com/baeldung/data/repositories/TweetRepository.java b/spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/TweetRepository.java similarity index 100% rename from spring-data-spring-security/src/main/java/com/baeldung/data/repositories/TweetRepository.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/TweetRepository.java diff --git a/spring-data-spring-security/src/main/java/com/baeldung/data/repositories/UserRepository.java b/spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/UserRepository.java similarity index 100% rename from spring-data-spring-security/src/main/java/com/baeldung/data/repositories/UserRepository.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/UserRepository.java diff --git a/spring-data-spring-security/src/main/java/com/baeldung/models/AppUser.java b/spring-security-mvc-boot/src/main/java/com/baeldung/models/AppUser.java similarity index 100% rename from spring-data-spring-security/src/main/java/com/baeldung/models/AppUser.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/models/AppUser.java diff --git a/spring-data-spring-security/src/main/java/com/baeldung/models/Tweet.java b/spring-security-mvc-boot/src/main/java/com/baeldung/models/Tweet.java similarity index 100% rename from spring-data-spring-security/src/main/java/com/baeldung/models/Tweet.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/models/Tweet.java diff --git a/spring-data-spring-security/src/main/java/com/baeldung/security/AppUserPrincipal.java b/spring-security-mvc-boot/src/main/java/com/baeldung/security/AppUserPrincipal.java similarity index 100% rename from spring-data-spring-security/src/main/java/com/baeldung/security/AppUserPrincipal.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/security/AppUserPrincipal.java diff --git a/spring-data-spring-security/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java b/spring-security-mvc-boot/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java similarity index 100% rename from spring-data-spring-security/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java diff --git a/spring-data-spring-security/src/main/java/com/baeldung/security/CustomUserDetailsService.java b/spring-security-mvc-boot/src/main/java/com/baeldung/security/CustomUserDetailsService.java similarity index 100% rename from spring-data-spring-security/src/main/java/com/baeldung/security/CustomUserDetailsService.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/security/CustomUserDetailsService.java diff --git a/spring-data-spring-security/src/main/java/com/baeldung/util/DummyContentUtil.java b/spring-security-mvc-boot/src/main/java/com/baeldung/util/DummyContentUtil.java similarity index 100% rename from spring-data-spring-security/src/main/java/com/baeldung/util/DummyContentUtil.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/util/DummyContentUtil.java diff --git a/spring-security-mvc-boot/src/main/resources/logback.xml b/spring-security-mvc-boot/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-mvc-boot/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-data-spring-security/src/main/resources/persistence-h2.properties b/spring-security-mvc-boot/src/main/resources/persistence-h2.properties similarity index 100% rename from spring-data-spring-security/src/main/resources/persistence-h2.properties rename to spring-security-mvc-boot/src/main/resources/persistence-h2.properties diff --git a/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityUnitTest.java b/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityUnitTest.java new file mode 100644 index 0000000000..8207363a70 --- /dev/null +++ b/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityUnitTest.java @@ -0,0 +1,100 @@ +package com.baeldung.relationships; + +import static org.springframework.util.Assert.isTrue; + +import java.util.Date; +import java.util.List; + +import javax.servlet.ServletContext; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.InvalidDataAccessApiUsageException; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; + +import com.baeldung.AppConfig; +import com.baeldung.data.repositories.TweetRepository; +import com.baeldung.data.repositories.UserRepository; +import com.baeldung.models.AppUser; +import com.baeldung.models.Tweet; +import com.baeldung.security.AppUserPrincipal; +import com.baeldung.util.DummyContentUtil; + +@RunWith(SpringRunner.class) +@WebAppConfiguration +@ContextConfiguration +@DirtiesContext +public class SpringDataWithSecurityUnitTest { + AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); + @Autowired + private ServletContext servletContext; + private static UserRepository userRepository; + private static TweetRepository tweetRepository; + + @Before + public void testInit() { + ctx.register(AppConfig.class); + ctx.setServletContext(servletContext); + ctx.refresh(); + userRepository = ctx.getBean(UserRepository.class); + tweetRepository = ctx.getBean(TweetRepository.class); + List appUsers = (List) userRepository.saveAll(DummyContentUtil.generateDummyUsers()); + tweetRepository.saveAll(DummyContentUtil.generateDummyTweets(appUsers)); + } + + @AfterClass + public static void tearDown() { + tweetRepository.deleteAll(); + userRepository.deleteAll(); + } + + @Test + public void givenAppUser_whenLoginSuccessful_shouldUpdateLastLogin() { + AppUser appUser = userRepository.findByUsername("lionel@messi.com"); + Authentication auth = new UsernamePasswordAuthenticationToken(new AppUserPrincipal(appUser), null, DummyContentUtil.getAuthorities()); + SecurityContextHolder.getContext() + .setAuthentication(auth); + userRepository.updateLastLogin(new Date()); + } + + @Test(expected = InvalidDataAccessApiUsageException.class) + public void givenNoAppUserInSecurityContext_whenUpdateLastLoginAttempted_shouldFail() { + userRepository.updateLastLogin(new Date()); + } + + @Test + public void givenAppUser_whenLoginSuccessful_shouldReadMyPagedTweets() { + AppUser appUser = userRepository.findByUsername("lionel@messi.com"); + Authentication auth = new UsernamePasswordAuthenticationToken(new AppUserPrincipal(appUser), null, DummyContentUtil.getAuthorities()); + SecurityContextHolder.getContext() + .setAuthentication(auth); + Page page = null; + do { + page = tweetRepository.getMyTweetsAndTheOnesILiked(new PageRequest(page != null ? page.getNumber() + 1 : 0, 5)); + for (Tweet twt : page.getContent()) { + isTrue((twt.getOwner() == appUser.getUsername()) || (twt.getLikes() + .contains(appUser.getUsername())), "I do not have any Tweets"); + } + } while (page.hasNext()); + } + + @Test(expected = InvalidDataAccessApiUsageException.class) + public void givenNoAppUser_whenPaginatedResultsRetrievalAttempted_shouldFail() { + Page page = null; + do { + page = tweetRepository.getMyTweetsAndTheOnesILiked(new PageRequest(page != null ? page.getNumber() + 1 : 0, 5)); + } while (page != null && page.hasNext()); + } +} diff --git a/spring-security-mvc-custom/pom.xml b/spring-security-mvc-custom/pom.xml index a320f6b137..a1a1beb4f4 100644 --- a/spring-security-mvc-custom/pom.xml +++ b/spring-security-mvc-custom/pom.xml @@ -1,225 +1,213 @@ - 4.0.0 - com.baeldung - spring-security-mvc-custom - 0.1-SNAPSHOT - spring-security-mvc-custom - war + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + com.baeldung + spring-security-mvc-custom + 0.1-SNAPSHOT + spring-security-mvc-custom + war - - com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring - + + com.baeldung + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 + - + - + - - org.springframework.security - spring-security-web - ${org.springframework.security.version} - - - org.springframework.security - spring-security-config - ${org.springframework.security.version} - - - org.springframework.security - spring-security-taglibs - ${org.springframework.security.version} - + + org.springframework.security + spring-security-web + ${org.springframework.security.version} + + + org.springframework.security + spring-security-config + ${org.springframework.security.version} + + + org.springframework.security + spring-security-taglibs + ${org.springframework.security.version} + - + - - org.springframework - spring-core - ${spring.version} - - - commons-logging - commons-logging - - - - - org.springframework - spring-context - ${spring.version} - - - org.springframework - spring-jdbc - ${spring.version} - - - org.springframework - spring-beans - ${spring.version} - - - org.springframework - spring-aop - ${spring.version} - - - org.springframework - spring-tx - ${spring.version} - - - org.springframework - spring-expression - ${spring.version} - + + org.springframework + spring-core + ${spring.version} + + + commons-logging + commons-logging + + + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-jdbc + ${spring.version} + + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-aop + ${spring.version} + + + org.springframework + spring-tx + ${spring.version} + + + org.springframework + spring-expression + ${spring.version} + - - org.springframework - spring-web - ${spring.version} - - - org.springframework - spring-webmvc - ${spring.version} - + + org.springframework + spring-web + ${spring.version} + + + org.springframework + spring-webmvc + ${spring.version} + - + - - javax.servlet - javax.servlet-api - ${javax.servlet.version} - provided - + + javax.servlet + javax.servlet-api + ${javax.servlet.version} + provided + - - javax.servlet - jstl - ${jstl.version} - runtime - + + javax.servlet + jstl + ${jstl.version} + runtime + - + - - - - - + + + + + - - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind.version} - + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-databind.version} + - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + - - com.google.guava - guava - ${guava.version} - + + com.google.guava + guava + ${guava.version} + - + - - org.springframework - spring-test - ${spring.version} - test - + + org.springframework + spring-test + ${spring.version} + test + - - org.springframework.security - spring-security-test - ${org.springframework.security.version} - test - - + + org.springframework.security + spring-security-test + ${org.springframework.security.version} + test + + - - spring-security-mvc-custom - - - src/main/resources - true - - + + spring-security-mvc-custom + + + src/main/resources + true + + - + - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + + 8082 + + + + - + - + - - - 4.3.4.RELEASE - 4.2.0.RELEASE + + + 5.0.6.RELEASE - - 5.2.5.Final - 5.1.40 + + 3.1.0 + 1.2 - - 5.3.3.Final - 3.1.0 - 1.2 + + 19.0 + 3.5 + 2.9.4 - - 19.0 - 3.5 - 2.9.1 + + 2.6 + 1.6.1 - 4.5.2 - 4.4.5 - - 2.9.0 - - - 2.6 - 2.7 - 1.6.1 - - + \ No newline at end of file diff --git a/spring-security-mvc-custom/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-mvc-custom/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java index 19f1ca76a6..19f49ea59d 100644 --- a/spring-security-mvc-custom/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java +++ b/spring-security-mvc-custom/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -21,7 +21,7 @@ public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSu private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); - protected MySimpleUrlAuthenticationSuccessHandler() { + public MySimpleUrlAuthenticationSuccessHandler() { super(); } diff --git a/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MvcConfig.java index 3b97afc22d..db6141d43e 100644 --- a/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MvcConfig.java @@ -10,14 +10,14 @@ import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration @ComponentScan("org.baeldung.web.controller") -public class MvcConfig extends WebMvcConfigurerAdapter { +public class MvcConfig implements WebMvcConfigurer { public MvcConfig() { super(); @@ -27,8 +27,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/anonymous.html"); registry.addViewController("/login.html"); diff --git a/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java index 4da114c78b..ebe23950a7 100644 --- a/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -1,14 +1,70 @@ package org.baeldung.spring; +import org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; @Configuration -@ImportResource({ "classpath:webSecurityConfig.xml" }) -public class SecSecurityConfig { - +//@ImportResource({ "classpath:webSecurityConfig.xml" }) +@EnableWebSecurity +public class SecSecurityConfig extends WebSecurityConfigurerAdapter { + public SecSecurityConfig() { super(); } + @Bean("authenticationManager") + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("user1").password("{noop}user1Pass").roles("USER") + .and() + .withUser("admin1").password("{noop}admin1Pass").roles("ADMIN"); + // @formatter:on + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/anonymous*").anonymous() + .antMatchers("/login*").permitAll() + .anyRequest().authenticated() + + .and() + .formLogin() + .loginPage("/login.html") + .loginProcessingUrl("/login") + .successHandler(myAuthenticationSuccessHandler()) + .failureUrl("/login.html?error=true") + + .and() + .logout().deleteCookies("JSESSIONID") + + .and() + .rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400) + + .and() + .csrf().disable() + ; + // @formatter:on + } + + @Bean + public AuthenticationSuccessHandler myAuthenticationSuccessHandler(){ + return new MySimpleUrlAuthenticationSuccessHandler(); + } } diff --git a/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/LoginController.java b/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/LoginController.java index c67a6f667e..99bf345a41 100644 --- a/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/LoginController.java +++ b/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/LoginController.java @@ -1,5 +1,6 @@ package org.baeldung.web.controller; +import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; @@ -18,7 +19,7 @@ import org.springframework.web.bind.annotation.RequestParam; @RequestMapping(value = "/custom") public class LoginController { - @Autowired + @Resource(name="authenticationManager") private AuthenticationManager authManager; public LoginController() { diff --git a/spring-security-mvc-custom/src/main/resources/logback.xml b/spring-security-mvc-custom/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-security-mvc-custom/src/main/resources/logback.xml +++ b/spring-security-mvc-custom/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml index f2ecaba5c8..e79e14abeb 100644 --- a/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml @@ -2,9 +2,9 @@ @@ -24,11 +24,11 @@ - + - - + + diff --git a/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityConfig.java b/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityConfig.java index 874856095c..23d13a0ff1 100644 --- a/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityConfig.java +++ b/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityConfig.java @@ -3,7 +3,6 @@ package org.baeldung.security.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.BeanIds; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; @@ -24,7 +23,7 @@ public class ManualSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER").and().withUser("admin").password("adminPass").authorities("ROLE_ADMIN"); + auth.inMemoryAuthentication().withUser("user1").password("{noop}user1Pass").authorities("ROLE_USER").and().withUser("admin").password("adminPass").authorities("ROLE_ADMIN"); } @Override @@ -32,7 +31,7 @@ public class ManualSecurityConfig extends WebSecurityConfigurerAdapter { web.ignoring().antMatchers("/resources/**"); } - @Bean(name = BeanIds.AUTHENTICATION_MANAGER) + @Bean("authenticationManager") @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); diff --git a/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java b/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java index 9600977e37..ca401622c0 100644 --- a/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java +++ b/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java @@ -1,6 +1,8 @@ package org.baeldung.security.spring; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; @@ -17,7 +19,11 @@ public class SecurityWithCsrfConfig extends WebSecurityConfigurerAdapter { super(); } - // java config + @Bean("authenticationManager") + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { diff --git a/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java b/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java index f7dbd5b42c..1067c70fea 100644 --- a/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java +++ b/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java @@ -1,6 +1,8 @@ package org.baeldung.security.spring; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; @@ -17,7 +19,11 @@ public class SecurityWithoutCsrfConfig extends WebSecurityConfigurerAdapter { super(); } - // java config + @Bean("authenticationManager") + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { diff --git a/spring-security-mvc-digest-auth/pom.xml b/spring-security-mvc-digest-auth/pom.xml index 9387220b2a..33b3b5ff31 100644 --- a/spring-security-mvc-digest-auth/pom.xml +++ b/spring-security-mvc-digest-auth/pom.xml @@ -1,19 +1,17 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-security-mvc-digest-auth 0.1-SNAPSHOT - spring-security-mvc-digest-auth war - com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring - + com.baeldung + parent-spring-4 + 0.0.1-SNAPSHOT + ../parent-spring-4 + @@ -35,7 +33,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -46,55 +44,49 @@ org.springframework spring-context - ${org.springframework.version} + ${spring.version} org.springframework spring-jdbc - ${org.springframework.version} + ${spring.version} org.springframework spring-beans - ${org.springframework.version} + ${spring.version} org.springframework spring-aop - ${org.springframework.version} + ${spring.version} org.springframework spring-tx - ${org.springframework.version} + ${spring.version} org.springframework spring-expression - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} org.springframework spring-oxm - ${org.springframework.version} - - - - org.springframework - spring-web - ${org.springframework.version} + ${spring.version} @@ -149,7 +141,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -200,15 +192,9 @@ - 4.3.4.RELEASE - 4.2.0.RELEASE - - - 5.2.5.Final - 5.1.40 + 4.2.6.RELEASE - 5.3.3.Final 1.2 3.1.0 @@ -219,13 +205,9 @@ 4.4.5 4.5.2 - 2.9.0 - 2.6 - 2.7 1.6.1 - \ No newline at end of file diff --git a/spring-security-mvc-digest-auth/src/main/resources/logback.xml b/spring-security-mvc-digest-auth/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-security-mvc-digest-auth/src/main/resources/logback.xml +++ b/spring-security-mvc-digest-auth/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-security-mvc-ldap/pom.xml b/spring-security-mvc-ldap/pom.xml index 286b189d87..1c5df368a7 100644 --- a/spring-security-mvc-ldap/pom.xml +++ b/spring-security-mvc-ldap/pom.xml @@ -1,18 +1,17 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-security-mvc-ldap 0.1-SNAPSHOT - spring-security-mvc-ldap war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-security-mvc-ldap/src/main/resources/logback.xml b/spring-security-mvc-ldap/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-security-mvc-ldap/src/main/resources/logback.xml +++ b/spring-security-mvc-ldap/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-security-mvc-login/README.md b/spring-security-mvc-login/README.md index f7eb314869..c19cbc87a5 100644 --- a/spring-security-mvc-login/README.md +++ b/spring-security-mvc-login/README.md @@ -12,6 +12,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Spring HTTP/HTTPS Channel Security](http://www.baeldung.com/spring-channel-security-https) - [Spring Security - Customize the 403 Forbidden/Access Denied Page](http://www.baeldung.com/spring-security-custom-access-denied-page) - [Spring Security – Redirect to the Previous URL After Login](http://www.baeldung.com/spring-security-redirect-login) +- [Spring Security Custom AuthenticationFailureHandler](http://www.baeldung.com/spring-security-custom-authentication-failure-handler) ### Build the Project ``` diff --git a/spring-security-mvc-login/pom.xml b/spring-security-mvc-login/pom.xml index ee11bf067c..f70cf256dc 100644 --- a/spring-security-mvc-login/pom.xml +++ b/spring-security-mvc-login/pom.xml @@ -1,19 +1,19 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + com.baeldung spring-security-mvc-login 0.1-SNAPSHOT - spring-security-mvc-login war - com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring - + com.baeldung + parent-spring-4 + 0.0.1-SNAPSHOT + ../parent-spring-4 + @@ -40,7 +40,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -51,43 +51,43 @@ org.springframework spring-context - ${org.springframework.version} + ${spring.version} org.springframework spring-jdbc - ${org.springframework.version} + ${spring.version} org.springframework spring-beans - ${org.springframework.version} + ${spring.version} org.springframework spring-aop - ${org.springframework.version} + ${spring.version} org.springframework spring-tx - ${org.springframework.version} + ${spring.version} org.springframework spring-expression - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} @@ -111,7 +111,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -167,30 +167,14 @@ - 4.3.6.RELEASE - 4.2.1.RELEASE - - - 5.2.5.Final - 5.1.40 + 4.2.6.RELEASE - 5.3.3.Final 3.1.0 1.2 - - 19.0 - 3.5 - - 4.4.5 - 4.5.2 - - 2.9.0 - 2.6 - 2.7 1.6.1 diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java b/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java new file mode 100644 index 0000000000..5eddf3883e --- /dev/null +++ b/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java @@ -0,0 +1,22 @@ +package org.baeldung.security; + +import org.springframework.http.HttpStatus; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Calendar; + +public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler { + + @Override + public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { + httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); + + String jsonPayload = "{\"message\" : \"%s\", \"timestamp\" : \"%s\" }"; + httpServletResponse.getOutputStream().println(String.format(jsonPayload, e.getMessage(), Calendar.getInstance().getTime())); + } +} diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java index d9a43d48d0..accc7c9afd 100644 --- a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -1,6 +1,7 @@ package org.baeldung.spring; import org.baeldung.security.CustomAccessDeniedHandler; +import org.baeldung.security.CustomAuthenticationFailureHandler; import org.baeldung.security.CustomLogoutSuccessHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -10,6 +11,7 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; @Configuration @@ -26,11 +28,11 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { protected void configure(final AuthenticationManagerBuilder auth) throws Exception { // @formatter:off auth.inMemoryAuthentication() - .withUser("user1").password("user1Pass").roles("USER") - .and() - .withUser("user2").password("user2Pass").roles("USER") - .and() - .withUser("admin").password("adminPass").roles("ADMIN"); + .withUser("user1").password("user1Pass").roles("USER") + .and() + .withUser("user2").password("user2Pass").roles("USER") + .and() + .withUser("admin").password("adminPass").roles("ADMIN"); // @formatter:on } @@ -38,23 +40,24 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { protected void configure(final HttpSecurity http) throws Exception { // @formatter:off http - .csrf().disable() - .authorizeRequests() - .antMatchers("/admin/**").hasRole("ADMIN") - .antMatchers("/anonymous*").anonymous() - .antMatchers("/login*").permitAll() - .anyRequest().authenticated() - .and() - .formLogin() - .loginPage("/login.html") - .loginProcessingUrl("/perform_login") - .defaultSuccessUrl("/homepage.html",true) - .failureUrl("/login.html?error=true") - .and() - .logout() - .logoutUrl("/perform_logout") - .deleteCookies("JSESSIONID") - .logoutSuccessHandler(logoutSuccessHandler()); + .csrf().disable() + .authorizeRequests() + .antMatchers("/admin/**").hasRole("ADMIN") + .antMatchers("/anonymous*").anonymous() + .antMatchers("/login*").permitAll() + .anyRequest().authenticated() + .and() + .formLogin() + .loginPage("/login.html") + .loginProcessingUrl("/perform_login") + .defaultSuccessUrl("/homepage.html", true) + //.failureUrl("/login.html?error=true") + .failureHandler(authenticationFailureHandler()) + .and() + .logout() + .logoutUrl("/perform_logout") + .deleteCookies("JSESSIONID") + .logoutSuccessHandler(logoutSuccessHandler()); //.and() //.exceptionHandling().accessDeniedPage("/accessDenied"); //.exceptionHandling().accessDeniedHandler(accessDeniedHandler()); @@ -71,4 +74,8 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { return new CustomAccessDeniedHandler(); } + @Bean + public AuthenticationFailureHandler authenticationFailureHandler() { + return new CustomAuthenticationFailureHandler(); + } } diff --git a/spring-security-mvc-login/src/main/resources/logback.xml b/spring-security-mvc-login/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-security-mvc-login/src/main/resources/logback.xml +++ b/spring-security-mvc-login/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml index f0fa956934..189522889f 100644 --- a/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml @@ -15,20 +15,22 @@ - + - + + + diff --git a/spring-security-mvc-login/src/test/java/org/baeldung/security/FormLoginUnitTest.java b/spring-security-mvc-login/src/test/java/org/baeldung/security/FormLoginUnitTest.java new file mode 100644 index 0000000000..4b3a091e6c --- /dev/null +++ b/spring-security-mvc-login/src/test/java/org/baeldung/security/FormLoginUnitTest.java @@ -0,0 +1,63 @@ +package org.baeldung.security; + +import org.baeldung.spring.SecSecurityConfig; +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.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import javax.servlet.Filter; + +import static org.junit.Assert.assertTrue; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {SecSecurityConfig.class}) +@WebAppConfiguration +public class FormLoginUnitTest { + + @Autowired + private WebApplicationContext context; + + @Autowired + private Filter springSecurityFilterChain; + + private MockMvc mvc; + + @Before + public void setup() { + mvc = MockMvcBuilders + .webAppContextSetup(context) + .addFilters(springSecurityFilterChain) + .build(); + } + + @Test + public void givenValidRequestWithValidCredentials_shouldLoginSuccessfully() throws Exception { + mvc + .perform(formLogin("/perform_login").user("user1").password("user1Pass")) + .andExpect(status().isFound()) + .andExpect(authenticated().withUsername("user1")); + } + + @Test + public void givenValidRequestWithInvalidCredentials_shouldFailWith401() throws Exception { + MvcResult result = mvc + .perform(formLogin("/perform_login").user("random").password("random")).andReturn(); + /*.andExpect(status().isUnauthorized()) + .andDo(print()) + .andExpect(unauthenticated()) + .andReturn();*/ + + assertTrue(result.getResponse().getContentAsString().contains("Bad credentials")); + } +} diff --git a/spring-security-mvc-persisted-remember-me/pom.xml b/spring-security-mvc-persisted-remember-me/pom.xml index 5c3ac4b7c4..2add895ecb 100644 --- a/spring-security-mvc-persisted-remember-me/pom.xml +++ b/spring-security-mvc-persisted-remember-me/pom.xml @@ -1,19 +1,19 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + com.baeldung spring-security-mvc-persisted-remember-me 0.1-SNAPSHOT - spring-security-mvc-persisted-remember-me war - com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring - + com.baeldung + parent-spring-4 + 0.0.1-SNAPSHOT + ../parent-spring-4 + @@ -37,7 +37,7 @@ org.springframework spring-orm - ${org.springframework.version} + ${spring.version} @@ -45,7 +45,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -56,43 +56,43 @@ org.springframework spring-context - ${org.springframework.version} + ${spring.version} org.springframework spring-jdbc - ${org.springframework.version} + ${spring.version} org.springframework spring-beans - ${org.springframework.version} + ${spring.version} org.springframework spring-aop - ${org.springframework.version} + ${spring.version} org.springframework spring-tx - ${org.springframework.version} + ${spring.version} org.springframework spring-expression - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} @@ -134,7 +134,6 @@ ${guava.version} - @@ -189,32 +188,21 @@ - 4.3.4.RELEASE - 4.2.0.RELEASE + 4.2.6.RELEASE - 5.2.5.Final - 5.1.40 1.4.193 9.4.1212 - 5.3.3.Final 3.1.0 1.2 19.0 - 3.4 - - 4.5.2 - 4.4.5 - - 2.9.0 2.6 - 2.7 1.6.1 diff --git a/spring-security-mvc-persisted-remember-me/src/main/resources/logback.xml b/spring-security-mvc-persisted-remember-me/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-security-mvc-persisted-remember-me/src/main/resources/logback.xml +++ b/spring-security-mvc-persisted-remember-me/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml index 130778151f..7ffbd76aac 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc-session/pom.xml @@ -1,18 +1,18 @@ 4.0.0 + com.baeldung spring-security-mvc-session 0.1-SNAPSHOT - spring-security-mvc-session war com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -40,7 +40,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -51,43 +51,43 @@ org.springframework spring-context - ${org.springframework.version} + ${spring.version} org.springframework spring-jdbc - ${org.springframework.version} + ${spring.version} org.springframework spring-beans - ${org.springframework.version} + ${spring.version} org.springframework spring-aop - ${org.springframework.version} + ${spring.version} org.springframework spring-tx - ${org.springframework.version} + ${spring.version} org.springframework spring-expression - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} @@ -160,33 +160,16 @@ - 4.3.4.RELEASE - 4.2.0.RELEASE - - - 5.2.5.Final - 5.1.40 + 4.2.6.RELEASE - 5.3.3.Final 3.0.2 1.2 3.1.0 - - 19.0 - 3.5 - - 4.5.2 - 4.4.5 - - 2.9.0 - 2.6 - 2.7 1.6.1 - \ No newline at end of file diff --git a/spring-security-mvc-session/src/main/resources/logback.xml b/spring-security-mvc-session/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-security-mvc-session/src/main/resources/logback.xml +++ b/spring-security-mvc-session/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-security-mvc-socket/README.md b/spring-security-mvc-socket/README.md index 5ae9d4f4cd..828d9a3448 100644 --- a/spring-security-mvc-socket/README.md +++ b/spring-security-mvc-socket/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: - [Intro to Security and WebSockets](http://www.baeldung.com/spring-security-websockets) +- [Spring WebSockets: Specific User Chat](http://www.baeldung.com/spring-websocket-specific-user-chat) \ No newline at end of file diff --git a/spring-security-mvc-socket/pom.xml b/spring-security-mvc-socket/pom.xml index 6168740cb7..b7559753b5 100644 --- a/spring-security-mvc-socket/pom.xml +++ b/spring-security-mvc-socket/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 + com.baeldung.springsecuredsockets spring-security-mvc-socket 1.0.0 @@ -9,18 +10,18 @@ war - com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring - + com.baeldung + parent-spring-4 + 0.0.1-SNAPSHOT + ../parent-spring-4 + org.springframework spring-core - ${springframework.version} + ${spring.version} commons-logging @@ -31,7 +32,7 @@ org.springframework spring-web - ${springframework.version} + ${spring.version} commons-logging @@ -42,7 +43,7 @@ org.springframework spring-webmvc - ${springframework.version} + ${spring.version} commons-logging @@ -55,12 +56,12 @@ org.springframework.security spring-security-web - ${springsecurity.version} + ${spring-security.version} org.springframework.security spring-security-config - ${springsecurity.version} + ${spring-security.version} @@ -84,24 +85,24 @@ org.springframework spring-websocket - ${springframework.version} + ${spring.version} org.springframework spring-messaging - ${springframework.version} + ${spring.version} org.springframework.security spring-security-messaging - ${springsecurity.version} + ${spring-security.version} org.slf4j jcl-over-slf4j - ${slf4j.version} + ${org.slf4j.version} ch.qos.logback @@ -148,6 +149,7 @@ ${jackson.version} + @@ -174,14 +176,12 @@ - 4.3.8.RELEASE - 4.2.3.RELEASE - 2.8.7 - 1.7.25 5.2.10.Final + 4.2.3.RELEASE 1.11.3.RELEASE 1.4.196 1.2.3 + 2.8.7 \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/Constants.java b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/Constants.java new file mode 100644 index 0000000000..77bcf7f343 --- /dev/null +++ b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/Constants.java @@ -0,0 +1,8 @@ +package com.baeldung.springsecuredsockets; + +public class Constants { + public static final String SECURED_CHAT_HISTORY = "/secured/history"; + public static final String SECURED_CHAT = "/secured/chat"; + public static final String SECURED_CHAT_ROOM = "/secured/room"; + public static final String SECURED_CHAT_SPECIFIC_USER = "/secured/user/queue/specific-user"; +} diff --git a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/AppConfig.java b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/AppConfig.java index da687a328a..afb1970b25 100644 --- a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/AppConfig.java +++ b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/AppConfig.java @@ -51,6 +51,6 @@ public class AppConfig extends WebMvcConfigurerAdapter { // View H2 @Bean(initMethod="start", destroyMethod="stop") public Server h2Console () throws SQLException { - return Server.createWebServer("-web","-webAllowOthers","-webDaemon","-webPort", "8082"); + return Server.createWebServer("-web","-webAllowOthers","-webDaemon","-webPort", "8084"); } } \ No newline at end of file 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 d7b57d1829..be00662e3e 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,7 +88,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { .authorizeRequests() .antMatchers("/", "/index", "/authenticate") .permitAll() - .antMatchers("/secured/**/**", "/secured/socket", "/secured/success") + .antMatchers("/secured/**/**", "/secured/**/**/**", "/secured/socket", "/secured/success") .authenticated() .anyRequest().authenticated() .and() diff --git a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SocketBrokerConfig.java b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SocketBrokerConfig.java index 5affbd4c0e..9b19de7b5a 100644 --- a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SocketBrokerConfig.java +++ b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SocketBrokerConfig.java @@ -1,5 +1,10 @@ package com.baeldung.springsecuredsockets.config; +import static com.baeldung.springsecuredsockets.Constants.SECURED_CHAT; +import static com.baeldung.springsecuredsockets.Constants.SECURED_CHAT_HISTORY; +import static com.baeldung.springsecuredsockets.Constants.SECURED_CHAT_ROOM; +import static com.baeldung.springsecuredsockets.Constants.SECURED_CHAT_SPECIFIC_USER; + import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; @@ -7,7 +12,6 @@ import org.springframework.web.socket.config.annotation.AbstractWebSocketMessage import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; - @Configuration @EnableWebSocketMessageBroker @ComponentScan("com.baeldung.springsecuredsockets.controllers") @@ -15,13 +19,15 @@ public class SocketBrokerConfig extends AbstractWebSocketMessageBrokerConfigurer @Override public void configureMessageBroker(MessageBrokerRegistry config) { - config.enableSimpleBroker("/secured/history"); + config.enableSimpleBroker(SECURED_CHAT_HISTORY, SECURED_CHAT_SPECIFIC_USER); config.setApplicationDestinationPrefixes("/spring-security-mvc-socket"); + config.setUserDestinationPrefix("/secured/user"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { - registry.addEndpoint("/secured/chat").withSockJS(); + registry.addEndpoint(SECURED_CHAT_ROOM).withSockJS(); + registry.addEndpoint(SECURED_CHAT).withSockJS(); } } diff --git a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SocketSecurityConfig.java b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SocketSecurityConfig.java index a37dfb7672..c833e70d47 100644 --- a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SocketSecurityConfig.java +++ b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SocketSecurityConfig.java @@ -15,7 +15,7 @@ public class SocketSecurityConfig extends AbstractSecurityWebSocketMessageBroker @Override protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) { messages - .simpDestMatchers("/secured/**").authenticated() + .simpDestMatchers("/secured/**", "/secured/**/**").authenticated() .anyMessage().authenticated(); } } \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/WebAppInitializer.java b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/WebAppInitializer.java index 20311426c7..84c045a75a 100644 --- a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/WebAppInitializer.java +++ b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/WebAppInitializer.java @@ -1,6 +1,5 @@ package com.baeldung.springsecuredsockets.config; -import org.hibernate.cfg.Configuration; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; diff --git a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/controllers/SocketController.java b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/controllers/SocketController.java index 68c5e306d8..6a74009c16 100644 --- a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/controllers/SocketController.java +++ b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/controllers/SocketController.java @@ -1,11 +1,19 @@ package com.baeldung.springsecuredsockets.controllers; +import static com.baeldung.springsecuredsockets.Constants.SECURED_CHAT; +import static com.baeldung.springsecuredsockets.Constants.SECURED_CHAT_HISTORY; +import static com.baeldung.springsecuredsockets.Constants.SECURED_CHAT_ROOM; +import static com.baeldung.springsecuredsockets.Constants.SECURED_CHAT_SPECIFIC_USER; + import com.baeldung.springsecuredsockets.transfer.socket.Message; import com.baeldung.springsecuredsockets.transfer.socket.OutputMessage; +import java.security.Principal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.handler.annotation.MessageMapping; +import org.springframework.messaging.handler.annotation.Payload; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; @@ -19,10 +27,19 @@ public class SocketController { private SimpMessagingTemplate simpMessagingTemplate; private static final Logger log = LoggerFactory.getLogger(SocketController.class); - @MessageMapping("/secured/chat") - @SendTo("/secured/history") - public OutputMessage send(Message msg) throws Exception { + @MessageMapping(SECURED_CHAT) + @SendTo(SECURED_CHAT_HISTORY) + public OutputMessage sendAll(Message msg) throws Exception { OutputMessage out = new OutputMessage(msg.getFrom(), msg.getText(), new SimpleDateFormat("HH:mm").format(new Date())); return out; } + + /** + * Example of sending message to specific user using 'convertAndSendToUser()' and '/queue' + */ + @MessageMapping(SECURED_CHAT_ROOM) + public void sendSpecific(@Payload Message msg, Principal user, @Header("simpSessionId") String sessionId) throws Exception { + OutputMessage out = new OutputMessage(msg.getFrom(), msg.getText(), new SimpleDateFormat("HH:mm").format(new Date())); + simpMessagingTemplate.convertAndSendToUser(msg.getTo(), SECURED_CHAT_SPECIFIC_USER, out); + } } diff --git a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/security/CustomDaoAuthenticationProvider.java b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/security/CustomDaoAuthenticationProvider.java index 576495bedf..5b246ac380 100644 --- a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/security/CustomDaoAuthenticationProvider.java +++ b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/security/CustomDaoAuthenticationProvider.java @@ -8,7 +8,6 @@ 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.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; public class CustomDaoAuthenticationProvider extends DaoAuthenticationProvider { diff --git a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/transfer/socket/Message.java b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/transfer/socket/Message.java index 024b386164..fd5d632fce 100644 --- a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/transfer/socket/Message.java +++ b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/transfer/socket/Message.java @@ -3,6 +3,7 @@ package com.baeldung.springsecuredsockets.transfer.socket; public class Message { private String from; + private String to; private String text; public String getFrom() { @@ -11,6 +12,13 @@ public class Message { public void setFrom(String from) { this.from = from; } + + public String getTo() { + return to; + } + public void setTo(String to) { + this.to = to; + } public String getText() { return text; } diff --git a/spring-security-mvc-socket/src/main/resources/logback.xml b/spring-security-mvc-socket/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-mvc-socket/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/denied.jsp b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/denied.jsp index d61148b04f..e4c40da0a8 100644 --- a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/denied.jsp +++ b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/denied.jsp @@ -4,15 +4,20 @@ - - Spring Secured Sockets - " rel="stylesheet"> - - - -

    ACCESS DENIED!

    -
    -
    - Click to login. - + + + Spring Secured Sockets + " rel="stylesheet"> + " rel="stylesheet"> + + + + +
    +
    +

    ACCESS DENIED!

    + Click to login. +
    +
    + \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/index.jsp index d83338680e..d1435e8c2b 100644 --- a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/index.jsp +++ b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/index.jsp @@ -4,27 +4,32 @@ - - Spring Secured Sockets - " rel="stylesheet"> - - - - - - - - - - - - -

    Welcome!

    -
    - {{greeting}} -
    -
    - Click to login. - + + Spring Secured Sockets + " rel="stylesheet"> + " rel="stylesheet"> + + + + + + + + + + + + + + +
    +
    +

    Welcome!

    + {{greeting}} + Click to login. +
    +
    + + \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/login.jsp b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/login.jsp index d50059c674..76e3334bbe 100644 --- a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/login.jsp +++ b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/login.jsp @@ -4,42 +4,50 @@ - - Spring Secured Sockets - " rel="stylesheet"> - - - - - - - - - - - - - - -

    JSP Login Form


    -
    - - - - - - - - - - - - -
    User:
    Password:
    -
    + + Spring Secured Sockets + " rel="stylesheet"> + " rel="stylesheet"> + + + + + + + + + + + + + + + +
    +
    + +

    JSP Login Form

    +
    + + + + + + + + + + + + +
    User:
    Password:
    +
    + +
    +
    + + + - - - \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/socket.jsp b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/socket.jsp index b5807d74a6..ccd48672a1 100644 --- a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/socket.jsp +++ b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/socket.jsp @@ -4,48 +4,56 @@ - - Spring Secured Sockets - " rel="stylesheet"> - - - - - - - - - - - - - - -

    Socket Chat

    - -
    -
    - -
    -
    -
    - - - -
    -
    -
    - - -

    -
    -
    + + Spring Secured Sockets + " rel="stylesheet"> + " rel="stylesheet"> -Click to go back! -Click to start over (you will still be authenticated)! + + + + + + + + + + + + + + + + +
    +
    +

    Socket Chat

    +
    +

    (Chat With Everyone)

    + + + +
    +
    +

    (Chat With A Specific User)

    + + + +
    +
    +

    (Send and See Messages)

    + + +
    + +
    + Click to go back! + Click to start over (you will still be authenticated)! +
    +
    + + + - - - \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/success.jsp b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/success.jsp index 27e8f7aa44..4cff3f7a25 100644 --- a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/success.jsp +++ b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/success.jsp @@ -4,28 +4,33 @@ - - Spring Secured Sockets - " rel="stylesheet"> - - - - - - - - - - - - -

    Congrats! You've logged in.

    + + Spring Secured Sockets + " rel="stylesheet"> + " rel="stylesheet"> - Click to chat! - Click to start over (you will still be authenticated)! + + + - - - + + + + + + + + + +
    + +
    + + + \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/indexController.js b/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/indexController.js index 04c02e339b..5de3dcc78b 100644 --- a/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/indexController.js +++ b/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/indexController.js @@ -1,12 +1,13 @@ 'use strict'; angularApp - .controller('indexController', function ($scope) { - $scope.greeting = ''; +.controller('indexController', function ($scope) { - $scope.initialize = function () { - $scope.greeting = "Howdy!" - }; + $scope.greeting = ''; - $scope.initialize(); - }); \ No newline at end of file + $scope.initialize = function () { + $scope.greeting = "Howdy!" + }; + + $scope.initialize(); +}); \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/loginController.js b/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/loginController.js deleted file mode 100644 index 07187d5327..0000000000 --- a/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/loginController.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -angularApp - .controller('loginController', function ($scope) { - - }); diff --git a/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/socketController.js b/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/socketController.js index 395bf85c4a..ff000c251e 100644 --- a/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/socketController.js +++ b/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/socketController.js @@ -1,37 +1,52 @@ 'use strict'; angularApp - .controller('socketController', function ($scope, SocketService) { +.controller('socketController', function ($scope, SocketService) { - $scope.stompClient = null; - $scope.sendEndpoint = '/secured/chat'; - $scope.subscribeEndpoint = '/secured/history'; - $scope.elems = { - connect: 'connect', - from: 'from', - text: 'text', - disconnect: 'disconnect', - conversationDiv: 'conversationDiv', - response: 'response' - }; + /** + * URL mapping endpoints. + */ - $scope.connect = function (context) { - $scope.sendEndpoint = '/secured/chat'; - $scope.sendEndpoint = context + $scope.sendEndpoint ; - $scope.stompClient = SocketService.connect($scope.sendEndpoint, $scope.elems); - }; + var SECURED_CHAT = '/secured/chat'; + var SECURED_CHAT_HISTORY = '/secured/history'; + var SECURED_CHAT_ROOM = '/secured/room'; + var SECURED_CHAT_SPECIFIC_USER = '/secured/user/queue/specific-user'; - $scope.subscribe = function () { - $scope.stompClient.subscribe($scope.subscribeEndpoint, function (msgOut) { - SocketService.messageOut(JSON.parse(msgOut.body), $scope.elems); - }); - }; + var opts = { + from: 'from', + to: 'to', + text: 'text', + disconnect: 'disconnect', + conversationDiv: 'conversationDiv', + response: 'response' + }; - $scope.disconnect = function () { - SocketService.disconnect($scope.elems, $scope.stompClient); - }; + $scope.sendEndpoint = ''; + $scope.stompClient = null; - $scope.sendMessage = function () { - SocketService.sendMessage( $scope.elems, $scope.stompClient, $scope.sendEndpoint); - }; - }); \ No newline at end of file + /** + * Broadcast to All Users. + */ + + $scope.connectAll = function (context) { + $scope.sendEndpoint = context + SECURED_CHAT; + $scope.stompClient = SocketService.connect($scope.sendEndpoint , opts, true); + }; + + $scope.subscribeAll = function () { SocketService.subscribeToAll($scope.stompClient, SECURED_CHAT_HISTORY, opts); }; + + /** + * Broadcast to Specific User. + */ + + $scope.connectSpecific = function (context) { + $scope.sendEndpoint = context + SECURED_CHAT_ROOM; + $scope.stompClient = SocketService.connect(context + SECURED_CHAT_ROOM, opts, false); + }; + + $scope.subscribeSpecific = function () { SocketService.subscribeToSpecific($scope.stompClient, SECURED_CHAT_SPECIFIC_USER, opts); }; + + $scope.disconnect = function () { SocketService.disconnect(opts, $scope.stompClient); }; + + $scope.sendMessage = function () { SocketService.sendMessage(opts, $scope.stompClient, $scope.sendEndpoint); }; +}); \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/successController.js b/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/successController.js index ccb972202d..6926239202 100644 --- a/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/successController.js +++ b/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/successController.js @@ -1,13 +1,12 @@ 'use strict'; angularApp - .controller('successController', function ($scope) { +.controller('successController', function ($scope) { + $scope.successMsg = ''; - $scope.successMsg = ''; + $scope.initialize = function () { + $scope.successMsg = "You've logged in!"; + }; - $scope.initialize = function () { - $scope.successMsg = "You've logged in!"; - }; - - $scope.initialize(); - }); + $scope.initialize(); +}); diff --git a/spring-security-mvc-socket/src/main/webapp/resources/scripts/routes/router.js b/spring-security-mvc-socket/src/main/webapp/resources/scripts/routes/router.js index 70644f996d..004c7b331a 100644 --- a/spring-security-mvc-socket/src/main/webapp/resources/scripts/routes/router.js +++ b/spring-security-mvc-socket/src/main/webapp/resources/scripts/routes/router.js @@ -1,19 +1,16 @@ 'use strict'; angularApp - .config(function ($routeProvider) { - $routeProvider - .when('/index', { - controller: 'indexController' - }) - .when('/login', { - controller: 'loginController' - }) - .when('/sockets', { - controller: 'socketController' - }) - .when('/success', { - controller: 'successController' - }) - .otherwise('/index'); - }); \ No newline at end of file +.config(function ($routeProvider) { + $routeProvider + .when('/index', { + controller: 'indexController' + }) + .when('/sockets', { + controller: 'socketController' + }) + .when('/success', { + controller: 'successController' + }) + .otherwise('/index'); +}); \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/resources/scripts/services/SocketService.js b/spring-security-mvc-socket/src/main/webapp/resources/scripts/services/SocketService.js index 56930808a3..ba3f397f89 100644 --- a/spring-security-mvc-socket/src/main/webapp/resources/scripts/services/SocketService.js +++ b/spring-security-mvc-socket/src/main/webapp/resources/scripts/services/SocketService.js @@ -1,46 +1,99 @@ 'use strict'; +var idHelper = function (context) { + return document.getElementById(context); +}; + function SocketService() { - var that = this, - idHelper = function(context) { - return document.getElementById(context); - }; - that.setConnected = function (elems, connected) { - idHelper(elems.connect).disabled = connected; - idHelper(elems.disconnect).disabled = !connected; - idHelper(elems.conversationDiv).style.visibility = connected ? 'visible' : 'hidden'; - idHelper(elems.response).innerHTML = ''; + var that = this; + + that.sessionId = ''; + + /** + * Generic methods. + */ + + that.setConnected = function (opts, connected) { + idHelper('connectAll').disabled = connected; + idHelper('connectSpecific').disabled = connected; + idHelper(opts.disconnect).disabled = !connected; + idHelper(opts.response).innerHTML = ''; + idHelper('subscribeAll').disabled = !connected; + idHelper('subscribeSpecific').disabled = !connected; + }; + + that.connect = function (endpoint, opts, isBroadcastAll) { + var socket = new SockJS(endpoint), stompClient = Stomp.over(socket); + stompClient.connect({}, function (frame) { + that.setConnected(opts, true); + + if (!isBroadcastAll) { + var url = stompClient.ws._transport.url; + console.log(stompClient.ws._transport.url); + url = url.replace("ws://localhost:8080/spring-security-mvc-socket/secured/room/", ""); + url = url.replace("/websocket", ""); + url = url.replace(/^[0-9]+\//, ""); + console.log("Your current session is: " + url); + that.sessionId = url; + } + + }); + return stompClient; + }; + + that.disconnect = function (opts, stompClient) { + if (stompClient !== null && stompClient !== undefined) { stompClient.disconnect(); } + that.setConnected(opts, false); + }; + + that.sendMessage = function (opts, stompClient, endpoint) { + var to = idHelper(opts.to).value; + var from = idHelper(opts.from).value; + + var msg = { + 'from': (from === undefined || from === null ) ? to : from, + 'to': (to === undefined || to === null ) ? "ALL" : to, + 'text': idHelper(opts.text).value }; - that.connect = function (endpoint, elems) { - var socket = new SockJS(endpoint), stompClient = Stomp.over(socket); - stompClient.connect({}, function (frame) { - that.setConnected(elems, true); - }); - return stompClient; - }; + console.log(JSON.stringify(msg)); + stompClient.send(endpoint, {}, JSON.stringify(msg)); + }; - that.disconnect = function (elems, stompClient) { - if (stompClient !== null && stompClient !== undefined) stompClient.disconnect(); - that.setConnected(elems, false); - }; + that.messageOut = function (msg, opts) { + var r = idHelper(opts.response), p = document.createElement('p'); + p.style.wordWrap = 'break-word'; + p.appendChild(document.createTextNode(msg.from + ': ' + msg.text + ' (' + msg.time + ')')); + r.appendChild(p); + }; + + /** + * Broadcast to All Users. + */ + + that.subscribeToAll = function(client, url, opts) { + idHelper('subscribeAll').disabled = true; + idHelper('subscribeSpecific').disabled = true; + client.subscribe(url, function (msgOut) { + that.messageOut(JSON.parse(msgOut.body), opts); + }); + }; + + /** + * Broadcast to Specific User. + */ + + that.subscribeToSpecific = function(client, url, opts) { + idHelper('subscribeAll').disabled = true; + idHelper('subscribeSpecific').disabled = true; + client.subscribe(url + "-user" + that.sessionId, function (msgOut) { + that.messageOut(JSON.parse(msgOut.body), opts); + }); + }; - that.sendMessage = function (elems, stompClient, endpoint) { - stompClient.send(endpoint, {}, - JSON.stringify({ - 'from': idHelper(elems.from).value, - 'text': idHelper(elems.text).value - })); - }; - that.messageOut = function (msg, elems) { - var r = idHelper(elems.response), p = document.createElement('p'); - p.style.wordWrap = 'break-word'; - p.appendChild(document.createTextNode(msg.from + ': ' + msg.text + ' (' + msg.time + ')')); - r.appendChild(p); - }; } angularApp - .service('SocketService', SocketService); \ No newline at end of file +.service('SocketService', SocketService); \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/resources/styles/app.css b/spring-security-mvc-socket/src/main/webapp/resources/styles/app.css new file mode 100644 index 0000000000..ee2cb4d717 --- /dev/null +++ b/spring-security-mvc-socket/src/main/webapp/resources/styles/app.css @@ -0,0 +1,70 @@ +@import url('https://fonts.googleapis.com/css?family=Poiret+One'); + +html, body, main { + padding: 0; + margin: 0; + position: absolute; + height: 100%; + width: 100%; + color: white; + font-family: 'Poiret One', sans-serif; + opacity:.95; +} + +main { + background-size: cover; +} + +main > div.wrapper { + position: relative; + left: 15%; + top: 15%; + width: 40%; +} + +h1 { + text-transform: uppercase; + font-size: 48px; + letter-spacing: 2px; +} + +span, a { + font-size: 24px; + letter-spacing: 1px; +} + +a { + text-decoration: none; + color: white; +} + +a:hover { + color: lightgray; +} + +input { + width: 225px; + background: none !important; + border-radius: 25px; + background-color: #fff; + color: white; + outline: none; + margin-left: 2px; + padding-left: 25px; + padding-bottom: 9px; + padding-top: 9px; +} + +button { + width: 100px; + align-content: center; + text-align: center; + background: transparent; + border-radius: 25px; + padding: 6px; + color: white; +} + +button:hover { + opacity: .6; +} \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/resources/styles/denied.css b/spring-security-mvc-socket/src/main/webapp/resources/styles/denied.css new file mode 100644 index 0000000000..3956715e4a --- /dev/null +++ b/spring-security-mvc-socket/src/main/webapp/resources/styles/denied.css @@ -0,0 +1,3 @@ +main { + background-color: black; +} diff --git a/spring-security-mvc-socket/src/main/webapp/resources/styles/index.css b/spring-security-mvc-socket/src/main/webapp/resources/styles/index.css new file mode 100644 index 0000000000..b6da4814b7 --- /dev/null +++ b/spring-security-mvc-socket/src/main/webapp/resources/styles/index.css @@ -0,0 +1,7 @@ +main { + background-color: black; +} + +span, a { + top: 175px; +} \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/resources/styles/login.css b/spring-security-mvc-socket/src/main/webapp/resources/styles/login.css new file mode 100644 index 0000000000..197f3e41bb --- /dev/null +++ b/spring-security-mvc-socket/src/main/webapp/resources/styles/login.css @@ -0,0 +1,17 @@ +main { + background-color: black; +} + +input[type="submit"] { + width: 100px; + align-content: center; + text-align: center; + background: transparent; + border-radius: 25px; + padding: 6px; + color: white; +} + +input[type="submit"]:hover { + opacity:.6; +} \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/resources/styles/socket.css b/spring-security-mvc-socket/src/main/webapp/resources/styles/socket.css new file mode 100644 index 0000000000..aa483fd684 --- /dev/null +++ b/spring-security-mvc-socket/src/main/webapp/resources/styles/socket.css @@ -0,0 +1,19 @@ +main { + background-color: black; +} + +div#all, div#specific, div#conversationDiv { + border: 1px solid white; + border-radius: 25px; + padding: 15px; + margin: 15px +} + +button[disabled=true] { + color: lightgray; + border: 1px solid lightgray; +} + +button[disabled=true]:hover { + opacity: 1; +} \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/resources/styles/success.css b/spring-security-mvc-socket/src/main/webapp/resources/styles/success.css new file mode 100644 index 0000000000..3956715e4a --- /dev/null +++ b/spring-security-mvc-socket/src/main/webapp/resources/styles/success.css @@ -0,0 +1,3 @@ +main { + background-color: black; +} diff --git a/spring-security-openid/pom.xml b/spring-security-openid/pom.xml index 89e0977c05..a2c0b6b119 100644 --- a/spring-security-openid/pom.xml +++ b/spring-security-openid/pom.xml @@ -1,21 +1,20 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-security-openid 0.0.1-SNAPSHOT war - spring-security-openid Spring OpenID sample project - org.springframework.boot - spring-boot-starter-parent - 2.0.0.M7 - + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 @@ -52,27 +51,6 @@ - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - 2.2.1.RELEASE 1.0.9.RELEASE diff --git a/spring-security-openid/src/main/resources/logback.xml b/spring-security-openid/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-openid/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-react/.gitignore b/spring-security-react/.gitignore new file mode 100644 index 0000000000..7bb0610394 --- /dev/null +++ b/spring-security-react/.gitignore @@ -0,0 +1,121 @@ +# Created by .ignore support plugin (hsz.mobi) +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +.idea + +# CMake +cmake-build-debug/ +cmake-build-release/ + +## File-based project format: +*.iws + +## Plugin-specific files: + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties +### Eclipse template + +.metadata +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.settings/ +.loadpath +.recommenders + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# PyDev specific (Python IDE for Eclipse) +*.pydevproject + +# CDT-specific (C/C++ Development Tooling) +.cproject + +# CDT- autotools +.autotools + +# Java annotation processor (APT) +.factorypath + +# PDT-specific (PHP Development Tools) +.buildpath + +# sbteclipse plugin +.target + +# Tern plugin +.tern-project + +# TeXlipse plugin +.texlipse + +# STS (Spring Tool Suite) +.springBeans + +# Code Recommenders +.recommenders/ + +# Scala IDE specific (Scala & Java development for Eclipse) +.cache-main +.scala_dependencies +.worksheet +### Maven template +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties + +# Avoid ignoring Maven wrapper jar file (.jar files are usually ignored) +!/.mvn/wrapper/maven-wrapper.jar +### Java template +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* diff --git a/spring-security-react/README.md b/spring-security-react/README.md new file mode 100644 index 0000000000..1a845f0daa --- /dev/null +++ b/spring-security-react/README.md @@ -0,0 +1,17 @@ +========= + +## Spring Security React Example Project + +### The Course + +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com + +### Relevant Articles: + +* [Spring Security Login Page with React](http://www.baeldung.com/spring-security-login-react) + +### Build the Project + +``` +mvn clean install +``` diff --git a/spring-security-react/pom.xml b/spring-security-react/pom.xml new file mode 100644 index 0000000000..11ad679128 --- /dev/null +++ b/spring-security-react/pom.xml @@ -0,0 +1,183 @@ + + 4.0.0 + spring-security-react + 0.1-SNAPSHOT + + spring-security-react + war + + + com.baeldung + parent-spring-4 + 0.0.1-SNAPSHOT + ../parent-spring-4 + + + + + + + + org.springframework.security + spring-security-web + ${org.springframework.security.version} + + + org.springframework.security + spring-security-config + ${org.springframework.security.version} + + + org.springframework.security + spring-security-taglibs + ${org.springframework.security.version} + + + + + + org.springframework + spring-core + ${org.springframework.version} + + + org.springframework + spring-context + ${org.springframework.version} + + + org.springframework + spring-beans + ${org.springframework.version} + + + org.springframework + spring-aop + ${org.springframework.version} + + + + org.springframework + spring-web + ${org.springframework.version} + + + org.springframework + spring-webmvc + ${org.springframework.version} + + + + + + javax.servlet + javax.servlet-api + ${javax.servlet.version} + provided + + + javax.servlet + jstl + ${jstl.version} + runtime + + + + + + spring-security-react + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + + WEB-INF/view/react/node/**, + WEB-INF/view/react/node_modules/**, + WEB-INF/view/react/public/**, + WEB-INF/view/react/src/**, + WEB-INF/view/react/* + + + + + + com.github.eirslett + frontend-maven-plugin + ${frontend-maven-plugin.version} + + ${node.version} + ${npm.version} + src/main/webapp/WEB-INF/view/react + + + + install node and npm + + install-node-and-npm + + + + npm install + + npm + + + + npm run build + + npm + + + run build + + + + + + + org.eclipse.jetty + jetty-maven-plugin + 9.4.11.v20180605 + + + + + + + + + 4.3.6.RELEASE + 4.2.1.RELEASE + + + 3.1.0 + 1.2 + + + 19.0 + 3.5 + + + 2.6 + 2.7 + 1.6 + 9.4.11.v20180605 + + + v8.11.3 + 6.1.0 + + + + \ No newline at end of file diff --git a/spring-security-react/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-react/src/main/java/org/baeldung/spring/MvcConfig.java new file mode 100644 index 0000000000..f970b84585 --- /dev/null +++ b/spring-security-react/src/main/java/org/baeldung/spring/MvcConfig.java @@ -0,0 +1,55 @@ +package org.baeldung.spring; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +@EnableWebMvc +@Configuration +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + // API + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + + registry.addViewController("/anonymous.html"); + + registry.addViewController("/login.html"); + registry.addViewController("/homepage.html"); + registry.addViewController("/admin/adminpage.html"); + registry.addViewController("/accessDenied"); + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/static/**").addResourceLocations("/WEB-INF/view/react/build/static/"); + + registry.addResourceHandler("/*.js").addResourceLocations("/WEB-INF/view/react/build/"); + registry.addResourceHandler("/*.json").addResourceLocations("/WEB-INF/view/react/build/"); + registry.addResourceHandler("/*.ico").addResourceLocations("/WEB-INF/view/react/build/"); + registry.addResourceHandler("/index.html").addResourceLocations("/WEB-INF/view/react/build/index.html"); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + + return bean; + } +} \ No newline at end of file diff --git a/spring-security-react/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-react/src/main/java/org/baeldung/spring/SecSecurityConfig.java new file mode 100644 index 0000000000..c64b433544 --- /dev/null +++ b/spring-security-react/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -0,0 +1,56 @@ +package org.baeldung.spring; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +@Profile("!https") +public class SecSecurityConfig extends WebSecurityConfigurerAdapter { + + public SecSecurityConfig() { + super(); + } + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("user1").password("user1Pass").roles("USER") + .and() + .withUser("user2").password("user2Pass").roles("USER") + .and() + .withUser("admin").password("admin0Pass").roles("ADMIN"); + // @formatter:on + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/admin/**").hasRole("ADMIN") + .antMatchers("/anonymous*").anonymous() + .antMatchers(HttpMethod.GET, "/index*", "/static/**", "/*.js", "/*.json", "/*.ico").permitAll() + .anyRequest().authenticated() + .and() + .formLogin() + .loginPage("/index.html") + .loginProcessingUrl("/perform_login") + .defaultSuccessUrl("/homepage.html",true) + .failureUrl("/index.html?error=true") + .and() + .logout() + .logoutUrl("/perform_logout") + .deleteCookies("JSESSIONID"); + // @formatter:on + } + + +} diff --git a/spring-security-react/src/main/resources/logback.xml b/spring-security-react/src/main/resources/logback.xml new file mode 100644 index 0000000000..25f3f36d1a --- /dev/null +++ b/spring-security-react/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-security-react/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-security-react/src/main/webapp/WEB-INF/mvc-servlet.xml new file mode 100644 index 0000000000..4ba9642448 --- /dev/null +++ b/spring-security-react/src/main/webapp/WEB-INF/mvc-servlet.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/spring-security-react/src/main/webapp/WEB-INF/view/accessDenied.jsp b/spring-security-react/src/main/webapp/WEB-INF/view/accessDenied.jsp new file mode 100644 index 0000000000..45820cf43d --- /dev/null +++ b/spring-security-react/src/main/webapp/WEB-INF/view/accessDenied.jsp @@ -0,0 +1,15 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> + + + + +Access Denied + + +

    Sorry, you do not have permission to view this page.

    + +Click ">here to go back to the Homepage. + + \ No newline at end of file diff --git a/spring-security-react/src/main/webapp/WEB-INF/view/admin/adminpage.jsp b/spring-security-react/src/main/webapp/WEB-INF/view/admin/adminpage.jsp new file mode 100644 index 0000000000..813ef02d1d --- /dev/null +++ b/spring-security-react/src/main/webapp/WEB-INF/view/admin/adminpage.jsp @@ -0,0 +1,15 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> + + + + +

    This is the body of the sample admin page

    + + This page is only visible to an admin +
    + + ">Logout + + + \ No newline at end of file diff --git a/spring-security-react/src/main/webapp/WEB-INF/view/anonymous.jsp b/spring-security-react/src/main/webapp/WEB-INF/view/anonymous.jsp new file mode 100644 index 0000000000..d4e9c0289b --- /dev/null +++ b/spring-security-react/src/main/webapp/WEB-INF/view/anonymous.jsp @@ -0,0 +1,10 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> + + + + +

    Anonymous page

    + + ">To Login + + \ No newline at end of file diff --git a/spring-security-react/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-security-react/src/main/webapp/WEB-INF/view/homepage.jsp new file mode 100644 index 0000000000..c9d88cbc9b --- /dev/null +++ b/spring-security-react/src/main/webapp/WEB-INF/view/homepage.jsp @@ -0,0 +1,26 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> + + + + +

    This is the body of the sample view

    + + + This text is only visible to a user +

    + ">Restricted Admin Page +

    +
    + + + This text is only visible to an admin +
    + ">Admin Page +
    +
    + + ">Logout + + + \ No newline at end of file diff --git a/spring-security-react/src/main/webapp/WEB-INF/view/react/.babelrc b/spring-security-react/src/main/webapp/WEB-INF/view/react/.babelrc new file mode 100644 index 0000000000..2f01e1d615 --- /dev/null +++ b/spring-security-react/src/main/webapp/WEB-INF/view/react/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": ["env"] +} \ No newline at end of file diff --git a/spring-security-react/src/main/webapp/WEB-INF/view/react/.eslintignore b/spring-security-react/src/main/webapp/WEB-INF/view/react/.eslintignore new file mode 100644 index 0000000000..48912d244b --- /dev/null +++ b/spring-security-react/src/main/webapp/WEB-INF/view/react/.eslintignore @@ -0,0 +1,2 @@ +build +node_modules \ No newline at end of file diff --git a/spring-security-react/src/main/webapp/WEB-INF/view/react/.eslintrc b/spring-security-react/src/main/webapp/WEB-INF/view/react/.eslintrc new file mode 100644 index 0000000000..c977d77e77 --- /dev/null +++ b/spring-security-react/src/main/webapp/WEB-INF/view/react/.eslintrc @@ -0,0 +1,22 @@ +{ + "rules": { + "linebreak-style": [2, "unix"], + "semi":"off", + "no-console": "off" + }, + "ecmaFeatures": { + "jsx": true + }, + "env": { + "es6": true, + "browser": true, + "node": true, + "mocha": true + }, + "plugins": ["react"], + "parser": "babel-eslint", + "parserOptions": { + "sourceType": "module" + }, + "extends": ["eslint:recommended", "plugin:react/recommended"] +} \ No newline at end of file diff --git a/spring-security-react/src/main/webapp/WEB-INF/view/react/.gitignore b/spring-security-react/src/main/webapp/WEB-INF/view/react/.gitignore new file mode 100644 index 0000000000..146fcfd8bb --- /dev/null +++ b/spring-security-react/src/main/webapp/WEB-INF/view/react/.gitignore @@ -0,0 +1,22 @@ +# See https://help.github.com/ignore-files/ for more about ignoring files. + +# dependencies +node_modules +node + +# development +build + +# testing +coverage + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/spring-security-react/src/main/webapp/WEB-INF/view/react/package-lock.json b/spring-security-react/src/main/webapp/WEB-INF/view/react/package-lock.json new file mode 100644 index 0000000000..46f3a86c20 --- /dev/null +++ b/spring-security-react/src/main/webapp/WEB-INF/view/react/package-lock.json @@ -0,0 +1,10253 @@ +{ + "name": "react", + "version": "0.1.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "abab": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/abab/-/abab-1.0.4.tgz", + "integrity": "sha1-X6rZwsB/YN12dw9xzwJbYqY8/U4=" + }, + "acorn": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.7.1.tgz", + "integrity": "sha512-d+nbxBUGKg7Arpsvbnlq61mc12ek3EY8EQldM3GPAhWJ1UVxC6TDGbIvUMNU6obBX3i1+ptCIzV4vq0gFPEGVQ==" + }, + "acorn-dynamic-import": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/acorn-dynamic-import/-/acorn-dynamic-import-2.0.2.tgz", + "integrity": "sha1-x1K9IQvvZ5UBtsbLf8hPj0cVjMQ=", + "requires": { + "acorn": "^4.0.3" + }, + "dependencies": { + "acorn": { + "version": "4.0.13", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-4.0.13.tgz", + "integrity": "sha1-EFSVrlNh1pe9GVyCUZLhrX8lN4c=" + } + } + }, + "acorn-globals": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-3.1.0.tgz", + "integrity": "sha1-/YJw9x+7SZawBPqIDuXUZXOnMb8=", + "requires": { + "acorn": "^4.0.4" + }, + "dependencies": { + "acorn": { + "version": "4.0.13", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-4.0.13.tgz", + "integrity": "sha1-EFSVrlNh1pe9GVyCUZLhrX8lN4c=" + } + } + }, + "acorn-jsx": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-3.0.1.tgz", + "integrity": "sha1-r9+UiPsezvyDSPb7IvRk4ypYs2s=", + "requires": { + "acorn": "^3.0.4" + }, + "dependencies": { + "acorn": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-3.3.0.tgz", + "integrity": "sha1-ReN/s56No/JbruP/U2niu18iAXo=" + } + } + }, + "address": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/address/-/address-1.0.3.tgz", + "integrity": "sha512-z55ocwKBRLryBs394Sm3ushTtBeg6VAeuku7utSoSnsJKvKcnXFIyC6vh27n3rXyxSgkJBBCAvyOn7gSUcTYjg==" + }, + "ajv": { + "version": "5.5.2", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-5.5.2.tgz", + "integrity": "sha1-c7Xuyj+rZT49P5Qis0GtQiBdyWU=", + "requires": { + "co": "^4.6.0", + "fast-deep-equal": "^1.0.0", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.3.0" + } + }, + "ajv-keywords": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.2.0.tgz", + "integrity": "sha1-6GuBnGAs+IIa1jdBNpjx3sAhhHo=" + }, + "align-text": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/align-text/-/align-text-0.1.4.tgz", + "integrity": "sha1-DNkKVhCT810KmSVsIrcGlDP60Rc=", + "requires": { + "kind-of": "^3.0.2", + "longest": "^1.0.1", + "repeat-string": "^1.5.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "alphanum-sort": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/alphanum-sort/-/alphanum-sort-1.0.2.tgz", + "integrity": "sha1-l6ERlkmyEa0zaR2fn0hqjsn74KM=" + }, + "amdefine": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/amdefine/-/amdefine-1.0.1.tgz", + "integrity": "sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=" + }, + "ansi-align": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ansi-align/-/ansi-align-2.0.0.tgz", + "integrity": "sha1-w2rsy6VjuJzrVW82kPCx2eNUf38=", + "requires": { + "string-width": "^2.0.0" + } + }, + "ansi-escapes": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", + "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "requires": { + "color-convert": "^1.9.0" + } + }, + "anymatch": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-1.3.2.tgz", + "integrity": "sha512-0XNayC8lTHQ2OI8aljNCN3sSx6hsr/1+rlcDAotXJR7C1oZZHCNsfpbKwMjRA3Uqb5tF1Rae2oloTr4xpq+WjA==", + "requires": { + "micromatch": "^2.1.5", + "normalize-path": "^2.0.0" + }, + "dependencies": { + "arr-diff": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-2.0.0.tgz", + "integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=", + "requires": { + "arr-flatten": "^1.0.1" + } + }, + "array-unique": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.2.1.tgz", + "integrity": "sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=" + }, + "braces": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/braces/-/braces-1.8.5.tgz", + "integrity": "sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=", + "requires": { + "expand-range": "^1.8.1", + "preserve": "^0.2.0", + "repeat-element": "^1.1.2" + } + }, + "expand-brackets": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-0.1.5.tgz", + "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=", + "requires": { + "is-posix-bracket": "^0.1.0" + } + }, + "extglob": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-0.3.2.tgz", + "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=", + "requires": { + "is-extglob": "^1.0.0" + } + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "requires": { + "is-buffer": "^1.1.5" + } + }, + "micromatch": { + "version": "2.3.11", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-2.3.11.tgz", + "integrity": "sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=", + "requires": { + "arr-diff": "^2.0.0", + "array-unique": "^0.2.1", + "braces": "^1.8.2", + "expand-brackets": "^0.1.4", + "extglob": "^0.3.1", + "filename-regex": "^2.0.0", + "is-extglob": "^1.0.0", + "is-glob": "^2.0.1", + "kind-of": "^3.0.2", + "normalize-path": "^2.0.1", + "object.omit": "^2.0.0", + "parse-glob": "^3.0.4", + "regex-cache": "^0.4.2" + } + } + } + }, + "append-transform": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/append-transform/-/append-transform-1.0.0.tgz", + "integrity": "sha512-P009oYkeHyU742iSZJzZZywj4QRJdnTWffaKuJQLablCZ1uz6/cW4yaRgcDaoQ+uwOxxnt0gRUcwfsNP2ri0gw==", + "requires": { + "default-require-extensions": "^2.0.0" + } + }, + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "requires": { + "sprintf-js": "~1.0.2" + } + }, + "aria-query": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-0.7.1.tgz", + "integrity": "sha1-Jsu1r/ZBRLCoJb4YRuCxbPoAsR4=", + "requires": { + "ast-types-flow": "0.0.7", + "commander": "^2.11.0" + } + }, + "arr-diff": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", + "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=" + }, + "arr-flatten": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/arr-flatten/-/arr-flatten-1.1.0.tgz", + "integrity": "sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==" + }, + "arr-union": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-3.1.0.tgz", + "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=" + }, + "array-equal": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/array-equal/-/array-equal-1.0.0.tgz", + "integrity": "sha1-jCpe8kcv2ep0KwTHenUJO6J1fJM=" + }, + "array-filter": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/array-filter/-/array-filter-0.0.1.tgz", + "integrity": "sha1-fajPLiZijtcygDWB/SH2fKzS7uw=" + }, + "array-find-index": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-find-index/-/array-find-index-1.0.2.tgz", + "integrity": "sha1-3wEKoSh+Fku9pvlyOwqWoexBh6E=" + }, + "array-includes": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.0.3.tgz", + "integrity": "sha1-GEtI9i2S10UrsxsyMWXH+L0CJm0=", + "requires": { + "define-properties": "^1.1.2", + "es-abstract": "^1.7.0" + } + }, + "array-map": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/array-map/-/array-map-0.0.0.tgz", + "integrity": "sha1-iKK6tz0c97zVwbEYoAP2b2ZfpmI=" + }, + "array-reduce": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/array-reduce/-/array-reduce-0.0.0.tgz", + "integrity": "sha1-FziZ0//Rx9k4PkR5Ul2+J4yrXys=" + }, + "array-union": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz", + "integrity": "sha1-mjRBDk9OPaI96jdb5b5w8kd47Dk=", + "requires": { + "array-uniq": "^1.0.1" + } + }, + "array-uniq": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", + "integrity": "sha1-r2rId6Jcx/dOBYiUdThY39sk/bY=" + }, + "array-unique": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", + "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=" + }, + "arrify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", + "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" + }, + "asap": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz", + "integrity": "sha1-5QNHYR1+aQlDIIu9r+vLwvuGbUY=" + }, + "asn1": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.3.tgz", + "integrity": "sha1-2sh4dxPJlmhJ/IGAd36+nB3fO4Y=" + }, + "asn1.js": { + "version": "4.10.1", + "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-4.10.1.tgz", + "integrity": "sha512-p32cOF5q0Zqs9uBiONKYLm6BClCoBCM5O9JfeUSlnQLBTxYdTK+pW+nXflm8UkKd2UYlEbYz5qEi0JuZR9ckSw==", + "requires": { + "bn.js": "^4.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" + } + }, + "assert": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/assert/-/assert-1.4.1.tgz", + "integrity": "sha1-mZEtWRg2tab1s0XA8H7vwI/GXZE=", + "requires": { + "util": "0.10.3" + }, + "dependencies": { + "inherits": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "integrity": "sha1-sX0I0ya0Qj5Wjv9xn5GwscvfafE=" + }, + "util": { + "version": "0.10.3", + "resolved": "https://registry.npmjs.org/util/-/util-0.10.3.tgz", + "integrity": "sha1-evsa/lCAUkZInj23/g7TeTNqwPk=", + "requires": { + "inherits": "2.0.1" + } + } + } + }, + "assert-plus": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", + "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=" + }, + "assign-symbols": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assign-symbols/-/assign-symbols-1.0.0.tgz", + "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=" + }, + "ast-types-flow": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/ast-types-flow/-/ast-types-flow-0.0.7.tgz", + "integrity": "sha1-9wtzXGvKGlycItmCw+Oef+ujva0=" + }, + "async": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.1.tgz", + "integrity": "sha512-fNEiL2+AZt6AlAw/29Cr0UDe4sRAHCpEHh54WMz+Bb7QfNcFw4h3loofyJpLeQs4Yx7yuqu/2dLgM5hKOs6HlQ==", + "requires": { + "lodash": "^4.17.10" + } + }, + "async-each": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/async-each/-/async-each-1.0.1.tgz", + "integrity": "sha1-GdOGodntxufByF04iu28xW0zYC0=" + }, + "asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=" + }, + "atob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.1.tgz", + "integrity": "sha1-ri1acpR38onWDdf5amMUoi3Wwio=" + }, + "autoprefixer": { + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-7.1.6.tgz", + "integrity": "sha512-C9yv/UF3X+eJTi/zvfxuyfxmLibYrntpF3qoJYrMeQwgUJOZrZvpJiMG2FMQ3qnhWtF/be4pYONBBw95ZGe3vA==", + "requires": { + "browserslist": "^2.5.1", + "caniuse-lite": "^1.0.30000748", + "normalize-range": "^0.1.2", + "num2fraction": "^1.2.2", + "postcss": "^6.0.13", + "postcss-value-parser": "^3.2.3" + } + }, + "aws-sign2": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", + "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=" + }, + "aws4": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.7.0.tgz", + "integrity": "sha512-32NDda82rhwD9/JBCCkB+MRYDp0oSvlo2IL6rQWA10PQi7tDUM3eqMSltXmY+Oyl/7N3P3qNtAlv7X0d9bI28w==" + }, + "axobject-query": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-0.1.0.tgz", + "integrity": "sha1-YvWdvFnJ+SQnWco0mWDnov48NsA=", + "requires": { + "ast-types-flow": "0.0.7" + } + }, + "babel-code-frame": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", + "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", + "requires": { + "chalk": "^1.1.3", + "esutils": "^2.0.2", + "js-tokens": "^3.0.2" + } + }, + "babel-core": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-core/-/babel-core-6.26.0.tgz", + "integrity": "sha1-rzL3izGm/O8RnIew/Y2XU/A6C7g=", + "requires": { + "babel-code-frame": "^6.26.0", + "babel-generator": "^6.26.0", + "babel-helpers": "^6.24.1", + "babel-messages": "^6.23.0", + "babel-register": "^6.26.0", + "babel-runtime": "^6.26.0", + "babel-template": "^6.26.0", + "babel-traverse": "^6.26.0", + "babel-types": "^6.26.0", + "babylon": "^6.18.0", + "convert-source-map": "^1.5.0", + "debug": "^2.6.8", + "json5": "^0.5.1", + "lodash": "^4.17.4", + "minimatch": "^3.0.4", + "path-is-absolute": "^1.0.1", + "private": "^0.1.7", + "slash": "^1.0.0", + "source-map": "^0.5.6" + }, + "dependencies": { + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + } + } + }, + "babel-eslint": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/babel-eslint/-/babel-eslint-7.2.3.tgz", + "integrity": "sha1-sv4tgBJkcPXBlELcdXJTqJdxCCc=", + "requires": { + "babel-code-frame": "^6.22.0", + "babel-traverse": "^6.23.1", + "babel-types": "^6.23.0", + "babylon": "^6.17.0" + } + }, + "babel-generator": { + "version": "6.26.1", + "resolved": "https://registry.npmjs.org/babel-generator/-/babel-generator-6.26.1.tgz", + "integrity": "sha512-HyfwY6ApZj7BYTcJURpM5tznulaBvyio7/0d4zFOeMPUmfxkCjHocCuoLa2SAGzBI8AREcH3eP3758F672DppA==", + "requires": { + "babel-messages": "^6.23.0", + "babel-runtime": "^6.26.0", + "babel-types": "^6.26.0", + "detect-indent": "^4.0.0", + "jsesc": "^1.3.0", + "lodash": "^4.17.4", + "source-map": "^0.5.7", + "trim-right": "^1.0.1" + }, + "dependencies": { + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + } + } + }, + "babel-helper-builder-binary-assignment-operator-visitor": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-helper-builder-binary-assignment-operator-visitor/-/babel-helper-builder-binary-assignment-operator-visitor-6.24.1.tgz", + "integrity": "sha1-zORReto1b0IgvK6KAsKzRvmlZmQ=", + "requires": { + "babel-helper-explode-assignable-expression": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" + } + }, + "babel-helper-builder-react-jsx": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-helper-builder-react-jsx/-/babel-helper-builder-react-jsx-6.26.0.tgz", + "integrity": "sha1-Of+DE7dci2Xc7/HzHTg+D/KkCKA=", + "requires": { + "babel-runtime": "^6.26.0", + "babel-types": "^6.26.0", + "esutils": "^2.0.2" + } + }, + "babel-helper-call-delegate": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-helper-call-delegate/-/babel-helper-call-delegate-6.24.1.tgz", + "integrity": "sha1-7Oaqzdx25Bw0YfiL/Fdb0Nqi340=", + "requires": { + "babel-helper-hoist-variables": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1" + } + }, + "babel-helper-define-map": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-helper-define-map/-/babel-helper-define-map-6.26.0.tgz", + "integrity": "sha1-pfVtq0GiX5fstJjH66ypgZ+Vvl8=", + "requires": { + "babel-helper-function-name": "^6.24.1", + "babel-runtime": "^6.26.0", + "babel-types": "^6.26.0", + "lodash": "^4.17.4" + } + }, + "babel-helper-explode-assignable-expression": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-helper-explode-assignable-expression/-/babel-helper-explode-assignable-expression-6.24.1.tgz", + "integrity": "sha1-8luCz33BBDPFX3BZLVdGQArCLKo=", + "requires": { + "babel-runtime": "^6.22.0", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1" + } + }, + "babel-helper-function-name": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-helper-function-name/-/babel-helper-function-name-6.24.1.tgz", + "integrity": "sha1-00dbjAPtmCQqJbSDUasYOZ01gKk=", + "requires": { + "babel-helper-get-function-arity": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1" + } + }, + "babel-helper-get-function-arity": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-helper-get-function-arity/-/babel-helper-get-function-arity-6.24.1.tgz", + "integrity": "sha1-j3eCqpNAfEHTqlCQj4mwMbG2hT0=", + "requires": { + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" + } + }, + "babel-helper-hoist-variables": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-helper-hoist-variables/-/babel-helper-hoist-variables-6.24.1.tgz", + "integrity": "sha1-HssnaJydJVE+rbyZFKc/VAi+enY=", + "requires": { + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" + } + }, + "babel-helper-optimise-call-expression": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-helper-optimise-call-expression/-/babel-helper-optimise-call-expression-6.24.1.tgz", + "integrity": "sha1-96E0J7qfc/j0+pk8VKl4gtEkQlc=", + "requires": { + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" + } + }, + "babel-helper-regex": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-helper-regex/-/babel-helper-regex-6.26.0.tgz", + "integrity": "sha1-MlxZ+QL4LyS3T6zu0DY5VPZJXnI=", + "requires": { + "babel-runtime": "^6.26.0", + "babel-types": "^6.26.0", + "lodash": "^4.17.4" + } + }, + "babel-helper-remap-async-to-generator": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-helper-remap-async-to-generator/-/babel-helper-remap-async-to-generator-6.24.1.tgz", + "integrity": "sha1-XsWBgnrXI/7N04HxySg5BnbkVRs=", + "requires": { + "babel-helper-function-name": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1" + } + }, + "babel-helper-replace-supers": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-helper-replace-supers/-/babel-helper-replace-supers-6.24.1.tgz", + "integrity": "sha1-v22/5Dk40XNpohPKiov3S2qQqxo=", + "requires": { + "babel-helper-optimise-call-expression": "^6.24.1", + "babel-messages": "^6.23.0", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1" + } + }, + "babel-helpers": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-helpers/-/babel-helpers-6.24.1.tgz", + "integrity": "sha1-NHHenK7DiOXIUOWX5Yom3fN2ArI=", + "requires": { + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1" + } + }, + "babel-jest": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-20.0.3.tgz", + "integrity": "sha1-5KA7E9wQOJ4UD8ZF0J/8TO0wFnE=", + "requires": { + "babel-core": "^6.0.0", + "babel-plugin-istanbul": "^4.0.0", + "babel-preset-jest": "^20.0.3" + } + }, + "babel-loader": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/babel-loader/-/babel-loader-7.1.2.tgz", + "integrity": "sha512-jRwlFbINAeyDStqK6Dd5YuY0k5YuzQUvlz2ZamuXrXmxav3pNqe9vfJ402+2G+OmlJSXxCOpB6Uz0INM7RQe2A==", + "requires": { + "find-cache-dir": "^1.0.0", + "loader-utils": "^1.0.2", + "mkdirp": "^0.5.1" + } + }, + "babel-messages": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-messages/-/babel-messages-6.23.0.tgz", + "integrity": "sha1-8830cDhYA1sqKVHG7F7fbGLyYw4=", + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-check-es2015-constants": { + "version": "6.22.0", + "resolved": "https://registry.npmjs.org/babel-plugin-check-es2015-constants/-/babel-plugin-check-es2015-constants-6.22.0.tgz", + "integrity": "sha1-NRV7EBQm/S/9PaP3XH0ekYNbv4o=", + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-dynamic-import-node": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/babel-plugin-dynamic-import-node/-/babel-plugin-dynamic-import-node-1.1.0.tgz", + "integrity": "sha512-tTfZbM9Ecwj3GK50mnPrUpinTwA4xXmDiQGCk/aBYbvl1+X8YqldK86wZ1owVJ4u3mrKbRlXMma80J18qwiaTQ==", + "requires": { + "babel-plugin-syntax-dynamic-import": "^6.18.0", + "babel-template": "^6.26.0", + "babel-types": "^6.26.0" + } + }, + "babel-plugin-istanbul": { + "version": "4.1.6", + "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-4.1.6.tgz", + "integrity": "sha512-PWP9FQ1AhZhS01T/4qLSKoHGY/xvkZdVBGlKM/HuxxS3+sC66HhTNR7+MpbO/so/cz/wY94MeSWJuP1hXIPfwQ==", + "requires": { + "babel-plugin-syntax-object-rest-spread": "^6.13.0", + "find-up": "^2.1.0", + "istanbul-lib-instrument": "^1.10.1", + "test-exclude": "^4.2.1" + } + }, + "babel-plugin-jest-hoist": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-20.0.3.tgz", + "integrity": "sha1-r+3IU70/jcNUjqZx++adA8wsF2c=" + }, + "babel-plugin-syntax-async-functions": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/babel-plugin-syntax-async-functions/-/babel-plugin-syntax-async-functions-6.13.0.tgz", + "integrity": "sha1-ytnK0RkbWtY0vzCuCHI5HgZHvpU=" + }, + "babel-plugin-syntax-class-properties": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/babel-plugin-syntax-class-properties/-/babel-plugin-syntax-class-properties-6.13.0.tgz", + "integrity": "sha1-1+sjt5oxf4VDlixQW4J8fWysJ94=" + }, + "babel-plugin-syntax-dynamic-import": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/babel-plugin-syntax-dynamic-import/-/babel-plugin-syntax-dynamic-import-6.18.0.tgz", + "integrity": "sha1-jWomIpyDdFqZgqRBBRVyyqF5sdo=" + }, + "babel-plugin-syntax-exponentiation-operator": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/babel-plugin-syntax-exponentiation-operator/-/babel-plugin-syntax-exponentiation-operator-6.13.0.tgz", + "integrity": "sha1-nufoM3KQ2pUoggGmpX9BcDF4MN4=" + }, + "babel-plugin-syntax-flow": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/babel-plugin-syntax-flow/-/babel-plugin-syntax-flow-6.18.0.tgz", + "integrity": "sha1-TDqyCiryaqIM0lmVw5jE63AxDI0=" + }, + "babel-plugin-syntax-jsx": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/babel-plugin-syntax-jsx/-/babel-plugin-syntax-jsx-6.18.0.tgz", + "integrity": "sha1-CvMqmm4Tyno/1QaeYtew9Y0NiUY=" + }, + "babel-plugin-syntax-object-rest-spread": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/babel-plugin-syntax-object-rest-spread/-/babel-plugin-syntax-object-rest-spread-6.13.0.tgz", + "integrity": "sha1-/WU28rzhODb/o6VFjEkDpZe7O/U=" + }, + "babel-plugin-syntax-trailing-function-commas": { + "version": "6.22.0", + "resolved": "https://registry.npmjs.org/babel-plugin-syntax-trailing-function-commas/-/babel-plugin-syntax-trailing-function-commas-6.22.0.tgz", + "integrity": "sha1-ugNgk3+NBuQBgKQ/4NVhb/9TLPM=" + }, + "babel-plugin-transform-async-to-generator": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-async-to-generator/-/babel-plugin-transform-async-to-generator-6.24.1.tgz", + "integrity": "sha1-ZTbjeK/2yx1VF6wOQOs+n8jQh2E=", + "requires": { + "babel-helper-remap-async-to-generator": "^6.24.1", + "babel-plugin-syntax-async-functions": "^6.8.0", + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-class-properties": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-class-properties/-/babel-plugin-transform-class-properties-6.24.1.tgz", + "integrity": "sha1-anl2PqYdM9NvN7YRqp3vgagbRqw=", + "requires": { + "babel-helper-function-name": "^6.24.1", + "babel-plugin-syntax-class-properties": "^6.8.0", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-arrow-functions": { + "version": "6.22.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-arrow-functions/-/babel-plugin-transform-es2015-arrow-functions-6.22.0.tgz", + "integrity": "sha1-RSaSy3EdX3ncf4XkQM5BufJE0iE=", + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-es2015-block-scoped-functions": { + "version": "6.22.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-block-scoped-functions/-/babel-plugin-transform-es2015-block-scoped-functions-6.22.0.tgz", + "integrity": "sha1-u8UbSflk1wy42OC5ToICRs46YUE=", + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-es2015-block-scoping": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-block-scoping/-/babel-plugin-transform-es2015-block-scoping-6.26.0.tgz", + "integrity": "sha1-1w9SmcEwjQXBL0Y4E7CgnnOxiV8=", + "requires": { + "babel-runtime": "^6.26.0", + "babel-template": "^6.26.0", + "babel-traverse": "^6.26.0", + "babel-types": "^6.26.0", + "lodash": "^4.17.4" + } + }, + "babel-plugin-transform-es2015-classes": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-classes/-/babel-plugin-transform-es2015-classes-6.24.1.tgz", + "integrity": "sha1-WkxYpQyclGHlZLSyo7+ryXolhNs=", + "requires": { + "babel-helper-define-map": "^6.24.1", + "babel-helper-function-name": "^6.24.1", + "babel-helper-optimise-call-expression": "^6.24.1", + "babel-helper-replace-supers": "^6.24.1", + "babel-messages": "^6.23.0", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-computed-properties": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-computed-properties/-/babel-plugin-transform-es2015-computed-properties-6.24.1.tgz", + "integrity": "sha1-b+Ko0WiV1WNPTNmZttNICjCBWbM=", + "requires": { + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-destructuring": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-destructuring/-/babel-plugin-transform-es2015-destructuring-6.23.0.tgz", + "integrity": "sha1-mXux8auWf2gtKwh2/jWNYOdlxW0=", + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-es2015-duplicate-keys": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-duplicate-keys/-/babel-plugin-transform-es2015-duplicate-keys-6.24.1.tgz", + "integrity": "sha1-c+s9MQypaePvnskcU3QabxV2Qj4=", + "requires": { + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-for-of": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-for-of/-/babel-plugin-transform-es2015-for-of-6.23.0.tgz", + "integrity": "sha1-9HyVsrYT3x0+zC/bdXNiPHUkhpE=", + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-es2015-function-name": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-function-name/-/babel-plugin-transform-es2015-function-name-6.24.1.tgz", + "integrity": "sha1-g0yJhTvDaxrw86TF26qU/Y6sqos=", + "requires": { + "babel-helper-function-name": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-literals": { + "version": "6.22.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-literals/-/babel-plugin-transform-es2015-literals-6.22.0.tgz", + "integrity": "sha1-T1SgLWzWbPkVKAAZox0xklN3yi4=", + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-es2015-modules-amd": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-modules-amd/-/babel-plugin-transform-es2015-modules-amd-6.24.1.tgz", + "integrity": "sha1-Oz5UAXI5hC1tGcMBHEvS8AoA0VQ=", + "requires": { + "babel-plugin-transform-es2015-modules-commonjs": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-modules-commonjs": { + "version": "6.26.2", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-modules-commonjs/-/babel-plugin-transform-es2015-modules-commonjs-6.26.2.tgz", + "integrity": "sha512-CV9ROOHEdrjcwhIaJNBGMBCodN+1cfkwtM1SbUHmvyy35KGT7fohbpOxkE2uLz1o6odKK2Ck/tz47z+VqQfi9Q==", + "requires": { + "babel-plugin-transform-strict-mode": "^6.24.1", + "babel-runtime": "^6.26.0", + "babel-template": "^6.26.0", + "babel-types": "^6.26.0" + } + }, + "babel-plugin-transform-es2015-modules-systemjs": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-modules-systemjs/-/babel-plugin-transform-es2015-modules-systemjs-6.24.1.tgz", + "integrity": "sha1-/4mhQrkRmpBhlfXxBuzzBdlAfSM=", + "requires": { + "babel-helper-hoist-variables": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-modules-umd": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-modules-umd/-/babel-plugin-transform-es2015-modules-umd-6.24.1.tgz", + "integrity": "sha1-rJl+YoXNGO1hdq22B9YCNErThGg=", + "requires": { + "babel-plugin-transform-es2015-modules-amd": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-object-super": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-object-super/-/babel-plugin-transform-es2015-object-super-6.24.1.tgz", + "integrity": "sha1-JM72muIcuDp/hgPa0CH1cusnj40=", + "requires": { + "babel-helper-replace-supers": "^6.24.1", + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-es2015-parameters": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-parameters/-/babel-plugin-transform-es2015-parameters-6.24.1.tgz", + "integrity": "sha1-V6w1GrScrxSpfNE7CfZv3wpiXys=", + "requires": { + "babel-helper-call-delegate": "^6.24.1", + "babel-helper-get-function-arity": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-shorthand-properties": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-shorthand-properties/-/babel-plugin-transform-es2015-shorthand-properties-6.24.1.tgz", + "integrity": "sha1-JPh11nIch2YbvZmkYi5R8U3jiqA=", + "requires": { + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-spread": { + "version": "6.22.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-spread/-/babel-plugin-transform-es2015-spread-6.22.0.tgz", + "integrity": "sha1-1taKmfia7cRTbIGlQujdnxdG+NE=", + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-es2015-sticky-regex": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-sticky-regex/-/babel-plugin-transform-es2015-sticky-regex-6.24.1.tgz", + "integrity": "sha1-AMHNsaynERLN8M9hJsLta0V8zbw=", + "requires": { + "babel-helper-regex": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-template-literals": { + "version": "6.22.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-template-literals/-/babel-plugin-transform-es2015-template-literals-6.22.0.tgz", + "integrity": "sha1-qEs0UPfp+PH2g51taH2oS7EjbY0=", + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-es2015-typeof-symbol": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-typeof-symbol/-/babel-plugin-transform-es2015-typeof-symbol-6.23.0.tgz", + "integrity": "sha1-3sCfHN3/lLUqxz1QXITfWdzOs3I=", + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-es2015-unicode-regex": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-unicode-regex/-/babel-plugin-transform-es2015-unicode-regex-6.24.1.tgz", + "integrity": "sha1-04sS9C6nMj9yk4fxinxa4frrNek=", + "requires": { + "babel-helper-regex": "^6.24.1", + "babel-runtime": "^6.22.0", + "regexpu-core": "^2.0.0" + } + }, + "babel-plugin-transform-exponentiation-operator": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-exponentiation-operator/-/babel-plugin-transform-exponentiation-operator-6.24.1.tgz", + "integrity": "sha1-KrDJx/MJj6SJB3cruBP+QejeOg4=", + "requires": { + "babel-helper-builder-binary-assignment-operator-visitor": "^6.24.1", + "babel-plugin-syntax-exponentiation-operator": "^6.8.0", + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-flow-strip-types": { + "version": "6.22.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-flow-strip-types/-/babel-plugin-transform-flow-strip-types-6.22.0.tgz", + "integrity": "sha1-hMtnKTXUNxT9wyvOhFaNh0Qc988=", + "requires": { + "babel-plugin-syntax-flow": "^6.18.0", + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-object-rest-spread": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-object-rest-spread/-/babel-plugin-transform-object-rest-spread-6.26.0.tgz", + "integrity": "sha1-DzZpLVD+9rfi1LOsFHgTepY7ewY=", + "requires": { + "babel-plugin-syntax-object-rest-spread": "^6.8.0", + "babel-runtime": "^6.26.0" + } + }, + "babel-plugin-transform-react-constant-elements": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-react-constant-elements/-/babel-plugin-transform-react-constant-elements-6.23.0.tgz", + "integrity": "sha1-LxGb9NLN1F65uqrldAU8YE9hR90=", + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-react-display-name": { + "version": "6.25.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-react-display-name/-/babel-plugin-transform-react-display-name-6.25.0.tgz", + "integrity": "sha1-Z+K/Hx6ck6sI25Z5LgU5K/LMKNE=", + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-react-jsx": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-react-jsx/-/babel-plugin-transform-react-jsx-6.24.1.tgz", + "integrity": "sha1-hAoCjn30YN/DotKfDA2R9jduZqM=", + "requires": { + "babel-helper-builder-react-jsx": "^6.24.1", + "babel-plugin-syntax-jsx": "^6.8.0", + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-react-jsx-self": { + "version": "6.22.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-react-jsx-self/-/babel-plugin-transform-react-jsx-self-6.22.0.tgz", + "integrity": "sha1-322AqdomEqEh5t3XVYvL7PBuY24=", + "requires": { + "babel-plugin-syntax-jsx": "^6.8.0", + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-react-jsx-source": { + "version": "6.22.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-react-jsx-source/-/babel-plugin-transform-react-jsx-source-6.22.0.tgz", + "integrity": "sha1-ZqwSFT9c0tF7PBkmj0vwGX9E7NY=", + "requires": { + "babel-plugin-syntax-jsx": "^6.8.0", + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-regenerator": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-regenerator/-/babel-plugin-transform-regenerator-6.26.0.tgz", + "integrity": "sha1-4HA2lvveJ/Cj78rPi03KL3s6jy8=", + "requires": { + "regenerator-transform": "^0.10.0" + } + }, + "babel-plugin-transform-runtime": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-runtime/-/babel-plugin-transform-runtime-6.23.0.tgz", + "integrity": "sha1-iEkNRGUC6puOfvsP4J7E2ZR5se4=", + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-strict-mode": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-strict-mode/-/babel-plugin-transform-strict-mode-6.24.1.tgz", + "integrity": "sha1-1fr3qleKZbvlkc9e2uBKDGcCB1g=", + "requires": { + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" + } + }, + "babel-preset-env": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/babel-preset-env/-/babel-preset-env-1.6.1.tgz", + "integrity": "sha512-W6VIyA6Ch9ePMI7VptNn2wBM6dbG0eSz25HEiL40nQXCsXGTGZSTZu1Iap+cj3Q0S5a7T9+529l/5Bkvd+afNA==", + "requires": { + "babel-plugin-check-es2015-constants": "^6.22.0", + "babel-plugin-syntax-trailing-function-commas": "^6.22.0", + "babel-plugin-transform-async-to-generator": "^6.22.0", + "babel-plugin-transform-es2015-arrow-functions": "^6.22.0", + "babel-plugin-transform-es2015-block-scoped-functions": "^6.22.0", + "babel-plugin-transform-es2015-block-scoping": "^6.23.0", + "babel-plugin-transform-es2015-classes": "^6.23.0", + "babel-plugin-transform-es2015-computed-properties": "^6.22.0", + "babel-plugin-transform-es2015-destructuring": "^6.23.0", + "babel-plugin-transform-es2015-duplicate-keys": "^6.22.0", + "babel-plugin-transform-es2015-for-of": "^6.23.0", + "babel-plugin-transform-es2015-function-name": "^6.22.0", + "babel-plugin-transform-es2015-literals": "^6.22.0", + "babel-plugin-transform-es2015-modules-amd": "^6.22.0", + "babel-plugin-transform-es2015-modules-commonjs": "^6.23.0", + "babel-plugin-transform-es2015-modules-systemjs": "^6.23.0", + "babel-plugin-transform-es2015-modules-umd": "^6.23.0", + "babel-plugin-transform-es2015-object-super": "^6.22.0", + "babel-plugin-transform-es2015-parameters": "^6.23.0", + "babel-plugin-transform-es2015-shorthand-properties": "^6.22.0", + "babel-plugin-transform-es2015-spread": "^6.22.0", + "babel-plugin-transform-es2015-sticky-regex": "^6.22.0", + "babel-plugin-transform-es2015-template-literals": "^6.22.0", + "babel-plugin-transform-es2015-typeof-symbol": "^6.23.0", + "babel-plugin-transform-es2015-unicode-regex": "^6.22.0", + "babel-plugin-transform-exponentiation-operator": "^6.22.0", + "babel-plugin-transform-regenerator": "^6.22.0", + "browserslist": "^2.1.2", + "invariant": "^2.2.2", + "semver": "^5.3.0" + } + }, + "babel-preset-flow": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-preset-flow/-/babel-preset-flow-6.23.0.tgz", + "integrity": "sha1-5xIYiHCFrpoktb5Baa/7WZgWxJ0=", + "requires": { + "babel-plugin-transform-flow-strip-types": "^6.22.0" + } + }, + "babel-preset-jest": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-20.0.3.tgz", + "integrity": "sha1-y6yq3stdaJyh4d4TYOv8ZoYsF4o=", + "requires": { + "babel-plugin-jest-hoist": "^20.0.3" + } + }, + "babel-preset-react": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-preset-react/-/babel-preset-react-6.24.1.tgz", + "integrity": "sha1-umnfrqRfw+xjm2pOzqbhdwLJE4A=", + "requires": { + "babel-plugin-syntax-jsx": "^6.3.13", + "babel-plugin-transform-react-display-name": "^6.23.0", + "babel-plugin-transform-react-jsx": "^6.24.1", + "babel-plugin-transform-react-jsx-self": "^6.22.0", + "babel-plugin-transform-react-jsx-source": "^6.22.0", + "babel-preset-flow": "^6.23.0" + } + }, + "babel-preset-react-app": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/babel-preset-react-app/-/babel-preset-react-app-3.1.2.tgz", + "integrity": "sha512-/sh5Qd5T08PYa6t4kuCdKh9tXp6/m/Jwyx7PJTqugsYMfsDUJMlBXOs5EwFODHprzjWrmQ0SydnMZu9FY4MZYg==", + "requires": { + "babel-plugin-dynamic-import-node": "1.1.0", + "babel-plugin-syntax-dynamic-import": "6.18.0", + "babel-plugin-transform-class-properties": "6.24.1", + "babel-plugin-transform-es2015-destructuring": "6.23.0", + "babel-plugin-transform-object-rest-spread": "6.26.0", + "babel-plugin-transform-react-constant-elements": "6.23.0", + "babel-plugin-transform-react-jsx": "6.24.1", + "babel-plugin-transform-react-jsx-self": "6.22.0", + "babel-plugin-transform-react-jsx-source": "6.22.0", + "babel-plugin-transform-regenerator": "6.26.0", + "babel-plugin-transform-runtime": "6.23.0", + "babel-preset-env": "1.6.1", + "babel-preset-react": "6.24.1" + } + }, + "babel-register": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-register/-/babel-register-6.26.0.tgz", + "integrity": "sha1-btAhFz4vy0htestFxgCahW9kcHE=", + "requires": { + "babel-core": "^6.26.0", + "babel-runtime": "^6.26.0", + "core-js": "^2.5.0", + "home-or-tmp": "^2.0.0", + "lodash": "^4.17.4", + "mkdirp": "^0.5.1", + "source-map-support": "^0.4.15" + }, + "dependencies": { + "core-js": { + "version": "2.5.7", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.5.7.tgz", + "integrity": "sha512-RszJCAxg/PP6uzXVXL6BsxSXx/B05oJAQ2vkJRjyjrEcNVycaqOmNb5OTxZPE3xa5gwZduqza6L9JOCenh/Ecw==" + } + } + }, + "babel-runtime": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", + "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=", + "requires": { + "core-js": "^2.4.0", + "regenerator-runtime": "^0.11.0" + }, + "dependencies": { + "core-js": { + "version": "2.5.7", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.5.7.tgz", + "integrity": "sha512-RszJCAxg/PP6uzXVXL6BsxSXx/B05oJAQ2vkJRjyjrEcNVycaqOmNb5OTxZPE3xa5gwZduqza6L9JOCenh/Ecw==" + } + } + }, + "babel-template": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-template/-/babel-template-6.26.0.tgz", + "integrity": "sha1-3gPi0WOWsGn0bdn/+FIfsaDjXgI=", + "requires": { + "babel-runtime": "^6.26.0", + "babel-traverse": "^6.26.0", + "babel-types": "^6.26.0", + "babylon": "^6.18.0", + "lodash": "^4.17.4" + } + }, + "babel-traverse": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-traverse/-/babel-traverse-6.26.0.tgz", + "integrity": "sha1-RqnL1+3MYsjlwGTi0tjQ9ANXZu4=", + "requires": { + "babel-code-frame": "^6.26.0", + "babel-messages": "^6.23.0", + "babel-runtime": "^6.26.0", + "babel-types": "^6.26.0", + "babylon": "^6.18.0", + "debug": "^2.6.8", + "globals": "^9.18.0", + "invariant": "^2.2.2", + "lodash": "^4.17.4" + } + }, + "babel-types": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-types/-/babel-types-6.26.0.tgz", + "integrity": "sha1-o7Bz+Uq0nrb6Vc1lInozQ4BjJJc=", + "requires": { + "babel-runtime": "^6.26.0", + "esutils": "^2.0.2", + "lodash": "^4.17.4", + "to-fast-properties": "^1.0.3" + } + }, + "babylon": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-6.18.0.tgz", + "integrity": "sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ==" + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" + }, + "base": { + "version": "0.11.2", + "resolved": "https://registry.npmjs.org/base/-/base-0.11.2.tgz", + "integrity": "sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg==", + "requires": { + "cache-base": "^1.0.1", + "class-utils": "^0.3.5", + "component-emitter": "^1.2.1", + "define-property": "^1.0.0", + "isobject": "^3.0.1", + "mixin-deep": "^1.2.0", + "pascalcase": "^0.1.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "base64-js": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.3.0.tgz", + "integrity": "sha512-ccav/yGvoa80BQDljCxsmmQ3Xvx60/UpBIij5QN21W3wBi/hhIC9OoO+KLpu9IJTS9j4DRVJ3aDDF9cMSoa2lw==" + }, + "bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", + "optional": true, + "requires": { + "tweetnacl": "^0.14.3" + } + }, + "big.js": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/big.js/-/big.js-3.2.0.tgz", + "integrity": "sha512-+hN/Zh2D08Mx65pZ/4g5bsmNiZUuChDiQfTUQ7qJr4/kuopCr88xZsAXv6mBoZEsUI4OuGHlX59qE94K2mMW8Q==" + }, + "binary-extensions": { + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-1.11.0.tgz", + "integrity": "sha1-RqoXUftqL5PuXmibsQh9SxTGwgU=" + }, + "bluebird": { + "version": "3.5.1", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.1.tgz", + "integrity": "sha512-MKiLiV+I1AA596t9w1sQJ8jkiSr5+ZKi0WKrYGUn6d1Fx+Ij4tIj+m2WMQSGczs5jZVxV339chE8iwk6F64wjA==" + }, + "bn.js": { + "version": "4.11.8", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.8.tgz", + "integrity": "sha512-ItfYfPLkWHUjckQCk8xC+LwxgK8NYcXywGigJgSwOP8Y2iyWT4f2vsZnoOXTTbo+o5yXmIUJ4gn5538SO5S3gA==" + }, + "boolbase": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", + "integrity": "sha1-aN/1++YMUes3cl6p4+0xDcwed24=" + }, + "boxen": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/boxen/-/boxen-1.3.0.tgz", + "integrity": "sha512-TNPjfTr432qx7yOjQyaXm3dSR0MH9vXp7eT1BFSl/C51g+EFnOR9hTg1IreahGBmDNCehscshe45f+C1TBZbLw==", + "requires": { + "ansi-align": "^2.0.0", + "camelcase": "^4.0.0", + "chalk": "^2.0.1", + "cli-boxes": "^1.0.0", + "string-width": "^2.0.0", + "term-size": "^1.2.0", + "widest-line": "^2.0.0" + }, + "dependencies": { + "camelcase": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-4.1.0.tgz", + "integrity": "sha1-1UVjW+HjPFQmScaRc+Xeas+uNN0=" + }, + "chalk": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", + "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + } + } + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "braces": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.2.tgz", + "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==", + "requires": { + "arr-flatten": "^1.1.0", + "array-unique": "^0.3.2", + "extend-shallow": "^2.0.1", + "fill-range": "^4.0.0", + "isobject": "^3.0.1", + "repeat-element": "^1.1.2", + "snapdragon": "^0.8.1", + "snapdragon-node": "^2.0.1", + "split-string": "^3.0.2", + "to-regex": "^3.0.1" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "brorand": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/brorand/-/brorand-1.1.0.tgz", + "integrity": "sha1-EsJe/kCkXjwyPrhnWgoM5XsiNx8=" + }, + "browser-resolve": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/browser-resolve/-/browser-resolve-1.11.3.tgz", + "integrity": "sha512-exDi1BYWB/6raKHmDTCicQfTkqwN5fioMFV4j8BsfMU4R2DK/QfZfK7kOVkmWCNANf0snkBzqGqAJBao9gZMdQ==", + "requires": { + "resolve": "1.1.7" + }, + "dependencies": { + "resolve": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.1.7.tgz", + "integrity": "sha1-IDEU2CrSxe2ejgQRs5ModeiJ6Xs=" + } + } + }, + "browserify-aes": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", + "integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==", + "requires": { + "buffer-xor": "^1.0.3", + "cipher-base": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.3", + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "browserify-cipher": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/browserify-cipher/-/browserify-cipher-1.0.1.tgz", + "integrity": "sha512-sPhkz0ARKbf4rRQt2hTpAHqn47X3llLkUGn+xEJzLjwY8LRs2p0v7ljvI5EyoRO/mexrNunNECisZs+gw2zz1w==", + "requires": { + "browserify-aes": "^1.0.4", + "browserify-des": "^1.0.0", + "evp_bytestokey": "^1.0.0" + } + }, + "browserify-des": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/browserify-des/-/browserify-des-1.0.1.tgz", + "integrity": "sha512-zy0Cobe3hhgpiOM32Tj7KQ3Vl91m0njwsjzZQK1L+JDf11dzP9qIvjreVinsvXrgfjhStXwUWAEpB9D7Gwmayw==", + "requires": { + "cipher-base": "^1.0.1", + "des.js": "^1.0.0", + "inherits": "^2.0.1" + } + }, + "browserify-rsa": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz", + "integrity": "sha1-IeCr+vbyApzy+vsTNWenAdQTVSQ=", + "requires": { + "bn.js": "^4.1.0", + "randombytes": "^2.0.1" + } + }, + "browserify-sign": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.0.4.tgz", + "integrity": "sha1-qk62jl17ZYuqa/alfmMMvXqT0pg=", + "requires": { + "bn.js": "^4.1.1", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "create-hmac": "^1.1.2", + "elliptic": "^6.0.0", + "inherits": "^2.0.1", + "parse-asn1": "^5.0.0" + } + }, + "browserify-zlib": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.2.0.tgz", + "integrity": "sha512-Z942RysHXmJrhqk88FmKBVq/v5tqmSkDz7p54G/MGyjMnCFFnC79XWNbg+Vta8W6Wb2qtSZTSxIGkJrRpCFEiA==", + "requires": { + "pako": "~1.0.5" + } + }, + "browserslist": { + "version": "2.11.3", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-2.11.3.tgz", + "integrity": "sha512-yWu5cXT7Av6mVwzWc8lMsJMHWn4xyjSuGYi4IozbVTLUOEYPSagUB8kiMDUHA1fS3zjr8nkxkn9jdvug4BBRmA==", + "requires": { + "caniuse-lite": "^1.0.30000792", + "electron-to-chromium": "^1.3.30" + } + }, + "bser": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/bser/-/bser-2.0.0.tgz", + "integrity": "sha1-mseNPtXZFYBP2HrLFYvHlxR6Fxk=", + "requires": { + "node-int64": "^0.4.0" + } + }, + "buffer": { + "version": "4.9.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.1.tgz", + "integrity": "sha1-bRu2AbB6TvztlwlBMgkwJ8lbwpg=", + "requires": { + "base64-js": "^1.0.2", + "ieee754": "^1.1.4", + "isarray": "^1.0.0" + } + }, + "buffer-from": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.0.tgz", + "integrity": "sha512-c5mRlguI/Pe2dSZmpER62rSCu0ryKmWddzRYsuXc50U2/g8jMOulc31VZMa4mYx31U5xsmSOpDCgH88Vl9cDGQ==" + }, + "buffer-xor": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", + "integrity": "sha1-JuYe0UIvtw3ULm42cp7VHYVf6Nk=" + }, + "builtin-modules": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-1.1.1.tgz", + "integrity": "sha1-Jw8HbFpywC9bZaR9+Uxf46J4iS8=" + }, + "builtin-status-codes": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/builtin-status-codes/-/builtin-status-codes-3.0.0.tgz", + "integrity": "sha1-hZgoeOIbmOHGZCXgPQF0eI9Wnug=" + }, + "cache-base": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz", + "integrity": "sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ==", + "requires": { + "collection-visit": "^1.0.0", + "component-emitter": "^1.2.1", + "get-value": "^2.0.6", + "has-value": "^1.0.0", + "isobject": "^3.0.1", + "set-value": "^2.0.0", + "to-object-path": "^0.3.0", + "union-value": "^1.0.0", + "unset-value": "^1.0.0" + } + }, + "caller-path": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/caller-path/-/caller-path-0.1.0.tgz", + "integrity": "sha1-lAhe9jWB7NPaqSREqP6U6CV3dR8=", + "requires": { + "callsites": "^0.2.0" + } + }, + "callsites": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-0.2.0.tgz", + "integrity": "sha1-r6uWJikQp/M8GaV3WCXGnzTjUMo=" + }, + "camel-case": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/camel-case/-/camel-case-3.0.0.tgz", + "integrity": "sha1-yjw2iKTpzzpM2nd9xNy8cTJJz3M=", + "requires": { + "no-case": "^2.2.0", + "upper-case": "^1.1.1" + } + }, + "camelcase": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-1.2.1.tgz", + "integrity": "sha1-m7UwTS4LVmmLLHWLCKPqqdqlijk=" + }, + "camelcase-keys": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz", + "integrity": "sha1-MIvur/3ygRkFHvodkyITyRuPkuc=", + "requires": { + "camelcase": "^2.0.0", + "map-obj": "^1.0.0" + }, + "dependencies": { + "camelcase": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-2.1.1.tgz", + "integrity": "sha1-fB0W1nmhu+WcoCys7PsBHiAfWh8=" + } + } + }, + "caniuse-api": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/caniuse-api/-/caniuse-api-1.6.1.tgz", + "integrity": "sha1-tTTnxzTE+B7F++isoq0kNUuWLGw=", + "requires": { + "browserslist": "^1.3.6", + "caniuse-db": "^1.0.30000529", + "lodash.memoize": "^4.1.2", + "lodash.uniq": "^4.5.0" + }, + "dependencies": { + "browserslist": { + "version": "1.7.7", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-1.7.7.tgz", + "integrity": "sha1-C9dnBCWL6CmyOYu1Dkti0aFmsLk=", + "requires": { + "caniuse-db": "^1.0.30000639", + "electron-to-chromium": "^1.2.7" + } + } + } + }, + "caniuse-db": { + "version": "1.0.30000861", + "resolved": "https://registry.npmjs.org/caniuse-db/-/caniuse-db-1.0.30000861.tgz", + "integrity": "sha1-byeEChMMEMCx4A+rdynB+vj0zNM=" + }, + "caniuse-lite": { + "version": "1.0.30000861", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30000861.tgz", + "integrity": "sha512-aeEQ4kyd41qCl8XFbCjWgVBI3EOd66M9sC43MFn0kuD/vcrNqvoIAlKon4xdp8yMCYvVjdCltI3lgArj8I6cNA==" + }, + "capture-stack-trace": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/capture-stack-trace/-/capture-stack-trace-1.0.0.tgz", + "integrity": "sha1-Sm+gc5nCa7pH8LJJa00PtAjFVQ0=" + }, + "case-sensitive-paths-webpack-plugin": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/case-sensitive-paths-webpack-plugin/-/case-sensitive-paths-webpack-plugin-2.1.1.tgz", + "integrity": "sha1-PSnO2MHxJL9vU4Rvs/WJRzH9yQk=" + }, + "caseless": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", + "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=" + }, + "center-align": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/center-align/-/center-align-0.1.3.tgz", + "integrity": "sha1-qg0yYptu6XIgBBHL1EYckHvCt60=", + "requires": { + "align-text": "^0.1.3", + "lazy-cache": "^1.0.3" + } + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "requires": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + }, + "dependencies": { + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" + } + } + }, + "chardet": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.4.2.tgz", + "integrity": "sha1-tUc7M9yXxCTl2Y3IfVXU2KKci/I=" + }, + "chokidar": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-2.0.4.tgz", + "integrity": "sha512-z9n7yt9rOvIJrMhvDtDictKrkFHeihkNl6uWMmZlmL6tJtX9Cs+87oK+teBx+JIgzvbX3yZHT3eF8vpbDxHJXQ==", + "requires": { + "anymatch": "^2.0.0", + "async-each": "^1.0.0", + "braces": "^2.3.0", + "fsevents": "^1.2.2", + "glob-parent": "^3.1.0", + "inherits": "^2.0.1", + "is-binary-path": "^1.0.0", + "is-glob": "^4.0.0", + "lodash.debounce": "^4.0.8", + "normalize-path": "^2.1.1", + "path-is-absolute": "^1.0.0", + "readdirp": "^2.0.0", + "upath": "^1.0.5" + }, + "dependencies": { + "anymatch": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-2.0.0.tgz", + "integrity": "sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw==", + "requires": { + "micromatch": "^3.1.4", + "normalize-path": "^2.1.1" + } + }, + "glob-parent": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-3.1.0.tgz", + "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", + "requires": { + "is-glob": "^3.1.0", + "path-dirname": "^1.0.0" + }, + "dependencies": { + "is-glob": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", + "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", + "requires": { + "is-extglob": "^2.1.0" + } + } + } + }, + "is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=" + }, + "is-glob": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.0.tgz", + "integrity": "sha1-lSHHaEXMJhCoUgPd8ICpWML/q8A=", + "requires": { + "is-extglob": "^2.1.1" + } + } + } + }, + "ci-info": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.1.3.tgz", + "integrity": "sha512-SK/846h/Rcy8q9Z9CAwGBLfCJ6EkjJWdpelWDufQpqVDYq2Wnnv8zlSO6AMQap02jvhVruKKpEtQOufo3pFhLg==" + }, + "cipher-base": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.4.tgz", + "integrity": "sha512-Kkht5ye6ZGmwv40uUDZztayT2ThLQGfnj/T71N/XzeZeo3nf8foyW7zGTsPYkEya3m5f3cAypH+qe7YOrM1U2Q==", + "requires": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "circular-json": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/circular-json/-/circular-json-0.3.3.tgz", + "integrity": "sha512-UZK3NBx2Mca+b5LsG7bY183pHWt5Y1xts4P3Pz7ENTwGVnJOUWbRb3ocjvX7hx9tq/yTAdclXm9sZ38gNuem4A==" + }, + "clap": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/clap/-/clap-1.2.3.tgz", + "integrity": "sha512-4CoL/A3hf90V3VIEjeuhSvlGFEHKzOz+Wfc2IVZc+FaUgU0ZQafJTP49fvnULipOPcAfqhyI2duwQyns6xqjYA==", + "requires": { + "chalk": "^1.1.3" + } + }, + "class-utils": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz", + "integrity": "sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg==", + "requires": { + "arr-union": "^3.1.0", + "define-property": "^0.2.5", + "isobject": "^3.0.0", + "static-extend": "^0.1.1" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "requires": { + "is-descriptor": "^0.1.0" + } + } + } + }, + "clean-css": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/clean-css/-/clean-css-4.1.11.tgz", + "integrity": "sha1-Ls3xRaujj1R0DybO/Q/z4D4SXWo=", + "requires": { + "source-map": "0.5.x" + }, + "dependencies": { + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + } + } + }, + "cli-boxes": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", + "integrity": "sha1-T6kXw+WclKAEzWH47lCdplFocUM=" + }, + "cli-cursor": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-2.1.0.tgz", + "integrity": "sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU=", + "requires": { + "restore-cursor": "^2.0.0" + } + }, + "cli-width": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-2.2.0.tgz", + "integrity": "sha1-/xnt6Kml5XkyQUewwR8PvLq+1jk=" + }, + "cliui": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-2.1.0.tgz", + "integrity": "sha1-S0dXYP+AJkx2LDoXGQMukcf+oNE=", + "requires": { + "center-align": "^0.1.1", + "right-align": "^0.1.1", + "wordwrap": "0.0.2" + }, + "dependencies": { + "wordwrap": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.2.tgz", + "integrity": "sha1-t5Zpu0LstAn4PVg8rVLKF+qhZD8=" + } + } + }, + "clone": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", + "integrity": "sha1-2jCcwmPfFZlMaIypAheco8fNfH4=" + }, + "co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=" + }, + "coa": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/coa/-/coa-1.0.4.tgz", + "integrity": "sha1-qe8VNmDWqGqL3sAomlxoTSF0Mv0=", + "requires": { + "q": "^1.1.2" + } + }, + "code-point-at": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz", + "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=" + }, + "collection-visit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/collection-visit/-/collection-visit-1.0.0.tgz", + "integrity": "sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA=", + "requires": { + "map-visit": "^1.0.0", + "object-visit": "^1.0.0" + } + }, + "color": { + "version": "0.11.4", + "resolved": "https://registry.npmjs.org/color/-/color-0.11.4.tgz", + "integrity": "sha1-bXtcdPtl6EHNSHkq0e1eB7kE12Q=", + "requires": { + "clone": "^1.0.2", + "color-convert": "^1.3.0", + "color-string": "^0.3.0" + } + }, + "color-convert": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.2.tgz", + "integrity": "sha512-3NUJZdhMhcdPn8vJ9v2UQJoH0qqoGUkYTgFEPZaPjEtwmmKUfNV46zZmgB2M5M4DCEQHMaCfWHCxiBflLm04Tg==", + "requires": { + "color-name": "1.1.1" + } + }, + "color-name": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.1.tgz", + "integrity": "sha1-SxQVMEz1ACjqgWQ2Q72C6gWANok=" + }, + "color-string": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/color-string/-/color-string-0.3.0.tgz", + "integrity": "sha1-J9RvtnAlxcL6JZk7+/V55HhBuZE=", + "requires": { + "color-name": "^1.0.0" + } + }, + "colormin": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/colormin/-/colormin-1.1.2.tgz", + "integrity": "sha1-6i90IKcrlogaOKrlnsEkpvcpgTM=", + "requires": { + "color": "^0.11.0", + "css-color-names": "0.0.4", + "has": "^1.0.1" + } + }, + "colors": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.1.2.tgz", + "integrity": "sha1-FopHAXVran9RoSzgyXv6KMCE7WM=" + }, + "combined-stream": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.6.tgz", + "integrity": "sha1-cj599ugBrFYTETp+RFqbactjKBg=", + "requires": { + "delayed-stream": "~1.0.0" + } + }, + "commander": { + "version": "2.16.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.16.0.tgz", + "integrity": "sha512-sVXqklSaotK9at437sFlFpyOcJonxe0yST/AG9DkQKUdIE6IqGIMv4SfAQSKaJbSdVEJYItASCrBiVQHq1HQew==" + }, + "commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=" + }, + "compare-versions": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-3.3.0.tgz", + "integrity": "sha512-MAAAIOdi2s4Gl6rZ76PNcUa9IOYB+5ICdT41o5uMRf09aEu/F9RK+qhe8RjXNPwcTjGV7KU7h2P/fljThFVqyQ==" + }, + "component-emitter": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.2.1.tgz", + "integrity": "sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=" + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" + }, + "concat-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "requires": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + } + }, + "configstore": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/configstore/-/configstore-3.1.2.tgz", + "integrity": "sha512-vtv5HtGjcYUgFrXc6Kx747B83MRRVS5R1VTEQoXvuP+kMI+if6uywV0nDGoiydJRy4yk7h9od5Og0kxx4zUXmw==", + "requires": { + "dot-prop": "^4.1.0", + "graceful-fs": "^4.1.2", + "make-dir": "^1.0.0", + "unique-string": "^1.0.0", + "write-file-atomic": "^2.0.0", + "xdg-basedir": "^3.0.0" + } + }, + "console-browserify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.1.0.tgz", + "integrity": "sha1-8CQcRXMKn8YyOyBtvzjtx0HQuxA=", + "requires": { + "date-now": "^0.1.4" + } + }, + "constants-browserify": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/constants-browserify/-/constants-browserify-1.0.0.tgz", + "integrity": "sha1-wguW2MYXdIqvHBYCF2DNJ/y4y3U=" + }, + "contains-path": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/contains-path/-/contains-path-0.1.0.tgz", + "integrity": "sha1-/ozxhP9mcLa67wGp1IYaXL7EEgo=" + }, + "content-type-parser": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/content-type-parser/-/content-type-parser-1.0.2.tgz", + "integrity": "sha512-lM4l4CnMEwOLHAHr/P6MEZwZFPJFtAAKgL6pogbXmVZggIqXhdB6RbBtPOTsw2FcXwYhehRGERJmRrjOiIB8pQ==" + }, + "convert-source-map": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.5.1.tgz", + "integrity": "sha1-uCeAl7m8IpNl3lxiz1/K7YtVmeU=" + }, + "copy-descriptor": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", + "integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=" + }, + "core-js": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-1.2.7.tgz", + "integrity": "sha1-ZSKUwUZR2yj6k70tX/KYOk8IxjY=" + }, + "core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" + }, + "cosmiconfig": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-2.2.2.tgz", + "integrity": "sha512-GiNXLwAFPYHy25XmTPpafYvn3CLAkJ8FLsscq78MQd1Kh0OU6Yzhn4eV2MVF4G9WEQZoWEGltatdR+ntGPMl5A==", + "requires": { + "is-directory": "^0.3.1", + "js-yaml": "^3.4.3", + "minimist": "^1.2.0", + "object-assign": "^4.1.0", + "os-homedir": "^1.0.1", + "parse-json": "^2.2.0", + "require-from-string": "^1.1.0" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=" + } + } + }, + "create-ecdh": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/create-ecdh/-/create-ecdh-4.0.3.tgz", + "integrity": "sha512-GbEHQPMOswGpKXM9kCWVrremUcBmjteUaQ01T9rkKCPDXfUHX0IoP9LpHYo2NPFampa4e+/pFDc3jQdxrxQLaw==", + "requires": { + "bn.js": "^4.1.0", + "elliptic": "^6.0.0" + } + }, + "create-error-class": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/create-error-class/-/create-error-class-3.0.2.tgz", + "integrity": "sha1-Br56vvlHo/FKMP1hBnHUAbyot7Y=", + "requires": { + "capture-stack-trace": "^1.0.0" + } + }, + "create-hash": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", + "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==", + "requires": { + "cipher-base": "^1.0.1", + "inherits": "^2.0.1", + "md5.js": "^1.3.4", + "ripemd160": "^2.0.1", + "sha.js": "^2.4.0" + } + }, + "create-hmac": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz", + "integrity": "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==", + "requires": { + "cipher-base": "^1.0.3", + "create-hash": "^1.1.0", + "inherits": "^2.0.1", + "ripemd160": "^2.0.0", + "safe-buffer": "^5.0.1", + "sha.js": "^2.4.8" + } + }, + "cross-spawn": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-5.1.0.tgz", + "integrity": "sha1-6L0O/uWPz/b4+UUQoKVUu/ojVEk=", + "requires": { + "lru-cache": "^4.0.1", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + }, + "crypto-browserify": { + "version": "3.12.0", + "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.12.0.tgz", + "integrity": "sha512-fz4spIh+znjO2VjL+IdhEpRJ3YN6sMzITSBijk6FK2UvTqruSQW+/cCZTSNsMiZNvUeq0CqurF+dAbyiGOY6Wg==", + "requires": { + "browserify-cipher": "^1.0.0", + "browserify-sign": "^4.0.0", + "create-ecdh": "^4.0.0", + "create-hash": "^1.1.0", + "create-hmac": "^1.1.0", + "diffie-hellman": "^5.0.0", + "inherits": "^2.0.1", + "pbkdf2": "^3.0.3", + "public-encrypt": "^4.0.0", + "randombytes": "^2.0.0", + "randomfill": "^1.0.3" + } + }, + "crypto-random-string": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-1.0.0.tgz", + "integrity": "sha1-ojD2T1aDEOFJgAmUB5DsmVRbyn4=" + }, + "css-color-names": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/css-color-names/-/css-color-names-0.0.4.tgz", + "integrity": "sha1-gIrcLnnPhHOAabZGyyDsJ762KeA=" + }, + "css-loader": { + "version": "0.28.7", + "resolved": "https://registry.npmjs.org/css-loader/-/css-loader-0.28.7.tgz", + "integrity": "sha512-GxMpax8a/VgcfRrVy0gXD6yLd5ePYbXX/5zGgTVYp4wXtJklS8Z2VaUArJgc//f6/Dzil7BaJObdSv8eKKCPgg==", + "requires": { + "babel-code-frame": "^6.11.0", + "css-selector-tokenizer": "^0.7.0", + "cssnano": ">=2.6.1 <4", + "icss-utils": "^2.1.0", + "loader-utils": "^1.0.2", + "lodash.camelcase": "^4.3.0", + "object-assign": "^4.0.1", + "postcss": "^5.0.6", + "postcss-modules-extract-imports": "^1.0.0", + "postcss-modules-local-by-default": "^1.0.1", + "postcss-modules-scope": "^1.0.0", + "postcss-modules-values": "^1.1.0", + "postcss-value-parser": "^3.3.0", + "source-list-map": "^2.0.0" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "css-select": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/css-select/-/css-select-1.2.0.tgz", + "integrity": "sha1-KzoRBTnFNV8c2NMUYj6HCxIeyFg=", + "requires": { + "boolbase": "~1.0.0", + "css-what": "2.1", + "domutils": "1.5.1", + "nth-check": "~1.0.1" + } + }, + "css-selector-tokenizer": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/css-selector-tokenizer/-/css-selector-tokenizer-0.7.0.tgz", + "integrity": "sha1-5piEdK6MlTR3v15+/s/OzNnPTIY=", + "requires": { + "cssesc": "^0.1.0", + "fastparse": "^1.1.1", + "regexpu-core": "^1.0.0" + }, + "dependencies": { + "regexpu-core": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-1.0.0.tgz", + "integrity": "sha1-hqdj9Y7k18L2sQLkdkBQ3n7ZDGs=", + "requires": { + "regenerate": "^1.2.1", + "regjsgen": "^0.2.0", + "regjsparser": "^0.1.4" + } + } + } + }, + "css-what": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-2.1.0.tgz", + "integrity": "sha1-lGfQMsOM+u+58teVASUwYvh/ob0=" + }, + "cssesc": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-0.1.0.tgz", + "integrity": "sha1-yBSQPkViM3GgR3tAEJqq++6t27Q=" + }, + "cssnano": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/cssnano/-/cssnano-3.10.0.tgz", + "integrity": "sha1-Tzj2zqK5sX+gFJDyPx3GjqZcHDg=", + "requires": { + "autoprefixer": "^6.3.1", + "decamelize": "^1.1.2", + "defined": "^1.0.0", + "has": "^1.0.1", + "object-assign": "^4.0.1", + "postcss": "^5.0.14", + "postcss-calc": "^5.2.0", + "postcss-colormin": "^2.1.8", + "postcss-convert-values": "^2.3.4", + "postcss-discard-comments": "^2.0.4", + "postcss-discard-duplicates": "^2.0.1", + "postcss-discard-empty": "^2.0.1", + "postcss-discard-overridden": "^0.1.1", + "postcss-discard-unused": "^2.2.1", + "postcss-filter-plugins": "^2.0.0", + "postcss-merge-idents": "^2.1.5", + "postcss-merge-longhand": "^2.0.1", + "postcss-merge-rules": "^2.0.3", + "postcss-minify-font-values": "^1.0.2", + "postcss-minify-gradients": "^1.0.1", + "postcss-minify-params": "^1.0.4", + "postcss-minify-selectors": "^2.0.4", + "postcss-normalize-charset": "^1.1.0", + "postcss-normalize-url": "^3.0.7", + "postcss-ordered-values": "^2.1.0", + "postcss-reduce-idents": "^2.2.2", + "postcss-reduce-initial": "^1.0.0", + "postcss-reduce-transforms": "^1.0.3", + "postcss-svgo": "^2.1.1", + "postcss-unique-selectors": "^2.0.2", + "postcss-value-parser": "^3.2.3", + "postcss-zindex": "^2.0.1" + }, + "dependencies": { + "autoprefixer": { + "version": "6.7.7", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-6.7.7.tgz", + "integrity": "sha1-Hb0cg1ZY41zj+ZhAmdsAWFx4IBQ=", + "requires": { + "browserslist": "^1.7.6", + "caniuse-db": "^1.0.30000634", + "normalize-range": "^0.1.2", + "num2fraction": "^1.2.2", + "postcss": "^5.2.16", + "postcss-value-parser": "^3.2.3" + } + }, + "browserslist": { + "version": "1.7.7", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-1.7.7.tgz", + "integrity": "sha1-C9dnBCWL6CmyOYu1Dkti0aFmsLk=", + "requires": { + "caniuse-db": "^1.0.30000639", + "electron-to-chromium": "^1.2.7" + } + }, + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "csso": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/csso/-/csso-2.3.2.tgz", + "integrity": "sha1-3dUsWHAz9J6Utx/FVWnyUuj/X4U=", + "requires": { + "clap": "^1.0.9", + "source-map": "^0.5.3" + }, + "dependencies": { + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + } + } + }, + "cssom": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.3.3.tgz", + "integrity": "sha512-pjE/I/NSp3iyeoxXN5QaoJpgzYUMj2dJHx9OSufoTliJLDx+kuOQaMCJW8OwvrKJswhXUHnHN6eUmUSETN0msg==" + }, + "cssstyle": { + "version": "0.2.37", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-0.2.37.tgz", + "integrity": "sha1-VBCXI0yyUTyDzu06zdwn/yeYfVQ=", + "requires": { + "cssom": "0.3.x" + } + }, + "currently-unhandled": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/currently-unhandled/-/currently-unhandled-0.4.1.tgz", + "integrity": "sha1-mI3zP+qxke95mmE2nddsF635V+o=", + "requires": { + "array-find-index": "^1.0.1" + } + }, + "d": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/d/-/d-1.0.0.tgz", + "integrity": "sha1-dUu1v+VUUdpppYuU1F9MWwRi1Y8=", + "requires": { + "es5-ext": "^0.10.9" + } + }, + "damerau-levenshtein": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.4.tgz", + "integrity": "sha1-AxkcQyy27qFou3fzpV/9zLiXhRQ=" + }, + "dashdash": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", + "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", + "requires": { + "assert-plus": "^1.0.0" + } + }, + "date-now": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/date-now/-/date-now-0.1.4.tgz", + "integrity": "sha1-6vQ5/U1ISK105cx9vvIAZyueNFs=" + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=" + }, + "decode-uri-component": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz", + "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=" + }, + "deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==" + }, + "deep-is": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=" + }, + "default-require-extensions": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/default-require-extensions/-/default-require-extensions-2.0.0.tgz", + "integrity": "sha1-9fj7sYp9bVCyH2QfZJ67Uiz+JPc=", + "requires": { + "strip-bom": "^3.0.0" + }, + "dependencies": { + "strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=" + } + } + }, + "define-properties": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.2.tgz", + "integrity": "sha1-g6c/L+pWmJj7c3GTyPhzyvbUXJQ=", + "requires": { + "foreach": "^2.0.5", + "object-keys": "^1.0.8" + } + }, + "define-property": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-2.0.2.tgz", + "integrity": "sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ==", + "requires": { + "is-descriptor": "^1.0.2", + "isobject": "^3.0.1" + }, + "dependencies": { + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "defined": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/defined/-/defined-1.0.0.tgz", + "integrity": "sha1-yY2bzvdWdBiOEQlpFRGZ45sfppM=" + }, + "del": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/del/-/del-2.2.2.tgz", + "integrity": "sha1-wSyYHQZ4RshLyvhiz/kw2Qf/0ag=", + "requires": { + "globby": "^5.0.0", + "is-path-cwd": "^1.0.0", + "is-path-in-cwd": "^1.0.0", + "object-assign": "^4.0.1", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0", + "rimraf": "^2.2.8" + } + }, + "delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=" + }, + "des.js": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.0.0.tgz", + "integrity": "sha1-wHTS4qpqipoH29YfmhXCzYPsjsw=", + "requires": { + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" + } + }, + "detect-indent": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-4.0.0.tgz", + "integrity": "sha1-920GQ1LN9Docts5hnE7jqUdd4gg=", + "requires": { + "repeating": "^2.0.0" + } + }, + "detect-port-alt": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/detect-port-alt/-/detect-port-alt-1.1.6.tgz", + "integrity": "sha512-5tQykt+LqfJFBEYaDITx7S7cR7mJ/zQmLXZ2qt5w04ainYZw6tBf9dBunMjVeVOdYVRUzUOE4HkY5J7+uttb5Q==", + "requires": { + "address": "^1.0.1", + "debug": "^2.6.0" + } + }, + "diff": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz", + "integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==" + }, + "diffie-hellman": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz", + "integrity": "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==", + "requires": { + "bn.js": "^4.1.0", + "miller-rabin": "^4.0.0", + "randombytes": "^2.0.0" + } + }, + "doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "requires": { + "esutils": "^2.0.2" + } + }, + "dom-converter": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/dom-converter/-/dom-converter-0.1.4.tgz", + "integrity": "sha1-pF71cnuJDJv/5tfIduexnLDhfzs=", + "requires": { + "utila": "~0.3" + }, + "dependencies": { + "utila": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/utila/-/utila-0.3.3.tgz", + "integrity": "sha1-1+jn1+MJEHCSsF+NloiCTWM6QiY=" + } + } + }, + "dom-serializer": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.1.0.tgz", + "integrity": "sha1-BzxpdUbOB4DOI75KKOKT5AvDDII=", + "requires": { + "domelementtype": "~1.1.1", + "entities": "~1.1.1" + }, + "dependencies": { + "domelementtype": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.1.3.tgz", + "integrity": "sha1-vSh3PiZCiBrsUVRJJCmcXNgiGFs=" + } + } + }, + "dom-urls": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/dom-urls/-/dom-urls-1.1.0.tgz", + "integrity": "sha1-AB3fgWKM0ecGElxxdvU8zsVdkY4=", + "requires": { + "urijs": "^1.16.1" + } + }, + "domain-browser": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/domain-browser/-/domain-browser-1.2.0.tgz", + "integrity": "sha512-jnjyiM6eRyZl2H+W8Q/zLMA481hzi0eszAaBUzIVnmYVDBbnLxVNnfu1HgEBvCbL+71FrxMl3E6lpKH7Ge3OXA==" + }, + "domelementtype": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.0.tgz", + "integrity": "sha1-sXrtguirWeUt2cGbF1bg/BhyBMI=" + }, + "domhandler": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.1.0.tgz", + "integrity": "sha1-0mRvXlf2w7qxHPbLBdPArPdBJZQ=", + "requires": { + "domelementtype": "1" + } + }, + "domutils": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.5.1.tgz", + "integrity": "sha1-3NhIiib1Y9YQeeSMn3t+Mjc2gs8=", + "requires": { + "dom-serializer": "0", + "domelementtype": "1" + } + }, + "dot-prop": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-4.2.0.tgz", + "integrity": "sha512-tUMXrxlExSW6U2EXiiKGSBVdYgtV8qlHL+C10TsW4PURY/ic+eaysnSkwB4kA/mBlCyy/IKDJ+Lc3wbWeaXtuQ==", + "requires": { + "is-obj": "^1.0.0" + } + }, + "dotenv": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-4.0.0.tgz", + "integrity": "sha1-hk7xN5rO1Vzm+V3r7NzhefegzR0=" + }, + "dotenv-expand": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/dotenv-expand/-/dotenv-expand-4.2.0.tgz", + "integrity": "sha1-3vHxyl1gWdJKdm5YeULCEQbOEnU=" + }, + "duplexer": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.1.tgz", + "integrity": "sha1-rOb/gIwc5mtX0ev5eXessCM0z8E=" + }, + "duplexer3": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/duplexer3/-/duplexer3-0.1.4.tgz", + "integrity": "sha1-7gHdHKwO08vH/b6jfcCo8c4ALOI=" + }, + "ecc-jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz", + "integrity": "sha1-D8c6ntXw1Tw4GTOYUj735UN3dQU=", + "optional": true, + "requires": { + "jsbn": "~0.1.0" + } + }, + "electron-to-chromium": { + "version": "1.3.50", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.50.tgz", + "integrity": "sha1-dDi3b5K0G5GfP73TUPvQdX2s3fc=" + }, + "elliptic": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.4.0.tgz", + "integrity": "sha1-ysmvh2LIWDYYcAPI3+GT5eLq5d8=", + "requires": { + "bn.js": "^4.4.0", + "brorand": "^1.0.1", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.0" + } + }, + "emoji-regex": { + "version": "6.5.1", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-6.5.1.tgz", + "integrity": "sha512-PAHp6TxrCy7MGMFidro8uikr+zlJJKJ/Q6mm2ExZ7HwkyR9lSVFfE3kt36qcwa24BQL7y0G9axycGjK1A/0uNQ==" + }, + "emojis-list": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-2.1.0.tgz", + "integrity": "sha1-TapNnbAPmBmIDHn6RXrlsJof04k=" + }, + "encoding": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.12.tgz", + "integrity": "sha1-U4tm8+5izRq1HsMjgp0flIDHS+s=", + "requires": { + "iconv-lite": "~0.4.13" + } + }, + "enhanced-resolve": { + "version": "3.4.1", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-3.4.1.tgz", + "integrity": "sha1-BCHjOf1xQZs9oT0Smzl5BAIwR24=", + "requires": { + "graceful-fs": "^4.1.2", + "memory-fs": "^0.4.0", + "object-assign": "^4.0.1", + "tapable": "^0.2.7" + } + }, + "entities": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-1.1.1.tgz", + "integrity": "sha1-blwtClYhtdra7O+AuQ7ftc13cvA=" + }, + "errno": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/errno/-/errno-0.1.7.tgz", + "integrity": "sha512-MfrRBDWzIWifgq6tJj60gkAwtLNb6sQPlcFrSOflcP1aFmmruKQ2wRnze/8V6kgyz7H3FF8Npzv78mZ7XLLflg==", + "requires": { + "prr": "~1.0.1" + } + }, + "error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "requires": { + "is-arrayish": "^0.2.1" + } + }, + "es-abstract": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.12.0.tgz", + "integrity": "sha512-C8Fx/0jFmV5IPoMOFPA9P9G5NtqW+4cOPit3MIuvR2t7Ag2K15EJTpxnHAYTzL+aYQJIESYeXZmDBfOBE1HcpA==", + "requires": { + "es-to-primitive": "^1.1.1", + "function-bind": "^1.1.1", + "has": "^1.0.1", + "is-callable": "^1.1.3", + "is-regex": "^1.0.4" + } + }, + "es-to-primitive": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.1.1.tgz", + "integrity": "sha1-RTVSSKiJeQNLZ5Lhm7gfK3l13Q0=", + "requires": { + "is-callable": "^1.1.1", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.1" + } + }, + "es5-ext": { + "version": "0.10.45", + "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.45.tgz", + "integrity": "sha512-FkfM6Vxxfmztilbxxz5UKSD4ICMf5tSpRFtDNtkAhOxZ0EKtX6qwmXNyH/sFyIbX2P/nU5AMiA9jilWsUGJzCQ==", + "requires": { + "es6-iterator": "~2.0.3", + "es6-symbol": "~3.1.1", + "next-tick": "1" + } + }, + "es6-iterator": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz", + "integrity": "sha1-p96IkUGgWpSwhUQDstCg+/qY87c=", + "requires": { + "d": "1", + "es5-ext": "^0.10.35", + "es6-symbol": "^3.1.1" + } + }, + "es6-map": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/es6-map/-/es6-map-0.1.5.tgz", + "integrity": "sha1-kTbgUD3MBqMBaQ8LsU/042TpSfA=", + "requires": { + "d": "1", + "es5-ext": "~0.10.14", + "es6-iterator": "~2.0.1", + "es6-set": "~0.1.5", + "es6-symbol": "~3.1.1", + "event-emitter": "~0.3.5" + } + }, + "es6-promise": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.4.tgz", + "integrity": "sha512-/NdNZVJg+uZgtm9eS3O6lrOLYmQag2DjdEXuPaHlZ6RuVqgqaVZfgYCepEIKsLqwdQArOPtC3XzRLqGGfT8KQQ==" + }, + "es6-set": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/es6-set/-/es6-set-0.1.5.tgz", + "integrity": "sha1-0rPsXU2ADO2BjbU40ol02wpzzLE=", + "requires": { + "d": "1", + "es5-ext": "~0.10.14", + "es6-iterator": "~2.0.1", + "es6-symbol": "3.1.1", + "event-emitter": "~0.3.5" + } + }, + "es6-symbol": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.1.tgz", + "integrity": "sha1-vwDvT9q2uhtG7Le2KbTH7VcVzHc=", + "requires": { + "d": "1", + "es5-ext": "~0.10.14" + } + }, + "es6-weak-map": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/es6-weak-map/-/es6-weak-map-2.0.2.tgz", + "integrity": "sha1-XjqzIlH/0VOKH45f+hNXdy+S2W8=", + "requires": { + "d": "1", + "es5-ext": "^0.10.14", + "es6-iterator": "^2.0.1", + "es6-symbol": "^3.1.1" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" + }, + "escodegen": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.10.0.tgz", + "integrity": "sha512-fjUOf8johsv23WuIKdNQU4P9t9jhQ4Qzx6pC2uW890OloK3Zs1ZAoCNpg/2larNF501jLl3UNy0kIRcF6VI22g==", + "requires": { + "esprima": "^3.1.3", + "estraverse": "^4.2.0", + "esutils": "^2.0.2", + "optionator": "^0.8.1", + "source-map": "~0.6.1" + }, + "dependencies": { + "esprima": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-3.1.3.tgz", + "integrity": "sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM=" + } + } + }, + "escope": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/escope/-/escope-3.6.0.tgz", + "integrity": "sha1-4Bl16BJ4GhY6ba392AOY3GTIicM=", + "requires": { + "es6-map": "^0.1.3", + "es6-weak-map": "^2.0.1", + "esrecurse": "^4.1.0", + "estraverse": "^4.1.1" + } + }, + "eslint": { + "version": "4.10.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-4.10.0.tgz", + "integrity": "sha512-MMVl8P/dYUFZEvolL8PYt7qc5LNdS2lwheq9BYa5Y07FblhcZqFyaUqlS8TW5QITGex21tV4Lk0a3fK8lsJIkA==", + "requires": { + "ajv": "^5.2.0", + "babel-code-frame": "^6.22.0", + "chalk": "^2.1.0", + "concat-stream": "^1.6.0", + "cross-spawn": "^5.1.0", + "debug": "^3.0.1", + "doctrine": "^2.0.0", + "eslint-scope": "^3.7.1", + "espree": "^3.5.1", + "esquery": "^1.0.0", + "estraverse": "^4.2.0", + "esutils": "^2.0.2", + "file-entry-cache": "^2.0.0", + "functional-red-black-tree": "^1.0.1", + "glob": "^7.1.2", + "globals": "^9.17.0", + "ignore": "^3.3.3", + "imurmurhash": "^0.1.4", + "inquirer": "^3.0.6", + "is-resolvable": "^1.0.0", + "js-yaml": "^3.9.1", + "json-stable-stringify": "^1.0.1", + "levn": "^0.3.0", + "lodash": "^4.17.4", + "minimatch": "^3.0.2", + "mkdirp": "^0.5.1", + "natural-compare": "^1.4.0", + "optionator": "^0.8.2", + "path-is-inside": "^1.0.2", + "pluralize": "^7.0.0", + "progress": "^2.0.0", + "require-uncached": "^1.0.3", + "semver": "^5.3.0", + "strip-ansi": "^4.0.0", + "strip-json-comments": "~2.0.1", + "table": "^4.0.1", + "text-table": "~0.2.0" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" + }, + "chalk": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", + "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "requires": { + "ms": "2.0.0" + } + }, + "esprima": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.0.tgz", + "integrity": "sha512-oftTcaMu/EGrEIu904mWteKIv8vMuOgGYo7EhVJJN00R/EED9DCua/xxHRdYnKtcECzVg7xOWhflvJMnqcFZjw==" + }, + "js-yaml": { + "version": "3.12.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", + "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "requires": { + "ansi-regex": "^3.0.0" + } + } + } + }, + "eslint-config-react-app": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/eslint-config-react-app/-/eslint-config-react-app-2.1.0.tgz", + "integrity": "sha512-8QZrKWuHVC57Fmu+SsKAVxnI9LycZl7NFQ4H9L+oeISuCXhYdXqsOOIVSjQFW6JF5MXZLFE+21Syhd7mF1IRZQ==" + }, + "eslint-import-resolver-node": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.2.tgz", + "integrity": "sha512-sfmTqJfPSizWu4aymbPr4Iidp5yKm8yDkHp+Ir3YiTHiiDfxh69mOUsmiqW6RZ9zRXFaF64GtYmN7e+8GHBv6Q==", + "requires": { + "debug": "^2.6.9", + "resolve": "^1.5.0" + } + }, + "eslint-loader": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/eslint-loader/-/eslint-loader-1.9.0.tgz", + "integrity": "sha512-40aN976qSNPyb9ejTqjEthZITpls1SVKtwguahmH1dzGCwQU/vySE+xX33VZmD8csU0ahVNCtFlsPgKqRBiqgg==", + "requires": { + "loader-fs-cache": "^1.0.0", + "loader-utils": "^1.0.2", + "object-assign": "^4.0.1", + "object-hash": "^1.1.4", + "rimraf": "^2.6.1" + } + }, + "eslint-module-utils": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.2.0.tgz", + "integrity": "sha1-snA2LNiLGkitMIl2zn+lTphBF0Y=", + "requires": { + "debug": "^2.6.8", + "pkg-dir": "^1.0.0" + }, + "dependencies": { + "find-up": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz", + "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", + "requires": { + "path-exists": "^2.0.0", + "pinkie-promise": "^2.0.0" + } + }, + "path-exists": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz", + "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", + "requires": { + "pinkie-promise": "^2.0.0" + } + }, + "pkg-dir": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-1.0.0.tgz", + "integrity": "sha1-ektQio1bstYp1EcFb/TpyTFM89Q=", + "requires": { + "find-up": "^1.0.0" + } + } + } + }, + "eslint-plugin-flowtype": { + "version": "2.39.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-flowtype/-/eslint-plugin-flowtype-2.39.1.tgz", + "integrity": "sha512-RiQv+7Z9QDJuzt+NO8sYgkLGT+h+WeCrxP7y8lI7wpU41x3x/2o3PGtHk9ck8QnA9/mlbNcy/hG0eKvmd7npaA==", + "requires": { + "lodash": "^4.15.0" + } + }, + "eslint-plugin-import": { + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.8.0.tgz", + "integrity": "sha512-Rf7dfKJxZ16QuTgVv1OYNxkZcsu/hULFnC+e+w0Gzi6jMC3guQoWQgxYxc54IDRinlb6/0v5z/PxxIKmVctN+g==", + "requires": { + "builtin-modules": "^1.1.1", + "contains-path": "^0.1.0", + "debug": "^2.6.8", + "doctrine": "1.5.0", + "eslint-import-resolver-node": "^0.3.1", + "eslint-module-utils": "^2.1.1", + "has": "^1.0.1", + "lodash.cond": "^4.3.0", + "minimatch": "^3.0.3", + "read-pkg-up": "^2.0.0" + }, + "dependencies": { + "doctrine": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-1.5.0.tgz", + "integrity": "sha1-N53Ocw9hZvds76TmcHoVmwLFpvo=", + "requires": { + "esutils": "^2.0.2", + "isarray": "^1.0.0" + } + }, + "load-json-file": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-2.0.0.tgz", + "integrity": "sha1-eUfkIUmvgNaWy/eXvKq8/h/inKg=", + "requires": { + "graceful-fs": "^4.1.2", + "parse-json": "^2.2.0", + "pify": "^2.0.0", + "strip-bom": "^3.0.0" + } + }, + "path-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-2.0.0.tgz", + "integrity": "sha1-8BLMuEFbcJb8LaoQVMPXI4lZTHM=", + "requires": { + "pify": "^2.0.0" + } + }, + "read-pkg": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-2.0.0.tgz", + "integrity": "sha1-jvHAYjxqbbDcZxPEv6xGMysjaPg=", + "requires": { + "load-json-file": "^2.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^2.0.0" + } + }, + "read-pkg-up": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-2.0.0.tgz", + "integrity": "sha1-a3KoBImE4MQeeVEP1en6mbO1Sb4=", + "requires": { + "find-up": "^2.0.0", + "read-pkg": "^2.0.0" + } + }, + "strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=" + } + } + }, + "eslint-plugin-jsx-a11y": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-jsx-a11y/-/eslint-plugin-jsx-a11y-5.1.1.tgz", + "integrity": "sha512-5I9SpoP7gT4wBFOtXT8/tXNPYohHBVfyVfO17vkbC7r9kEIxYJF12D3pKqhk8+xnk12rfxKClS3WCFpVckFTPQ==", + "requires": { + "aria-query": "^0.7.0", + "array-includes": "^3.0.3", + "ast-types-flow": "0.0.7", + "axobject-query": "^0.1.0", + "damerau-levenshtein": "^1.0.0", + "emoji-regex": "^6.1.0", + "jsx-ast-utils": "^1.4.0" + } + }, + "eslint-plugin-react": { + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.10.0.tgz", + "integrity": "sha512-18rzWn4AtbSUxFKKM7aCVcj5LXOhOKdwBino3KKWy4psxfPW0YtIbE8WNRDUdyHFL50BeLb6qFd4vpvNYyp7hw==", + "dev": true, + "requires": { + "doctrine": "^2.1.0", + "has": "^1.0.3", + "jsx-ast-utils": "^2.0.1", + "prop-types": "^15.6.2" + }, + "dependencies": { + "jsx-ast-utils": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-2.0.1.tgz", + "integrity": "sha1-6AGxs5mF4g//yHtA43SAgOLcrH8=", + "dev": true, + "requires": { + "array-includes": "^3.0.3" + } + } + } + }, + "eslint-scope": { + "version": "3.7.1", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-3.7.1.tgz", + "integrity": "sha1-PWPD7f2gLgbgGkUq2IyqzHzctug=", + "requires": { + "esrecurse": "^4.1.0", + "estraverse": "^4.1.1" + } + }, + "espree": { + "version": "3.5.4", + "resolved": "https://registry.npmjs.org/espree/-/espree-3.5.4.tgz", + "integrity": "sha512-yAcIQxtmMiB/jL32dzEp2enBeidsB7xWPLNiw3IIkpVds1P+h7qF9YwJq1yUNzp2OKXgAprs4F61ih66UsoD1A==", + "requires": { + "acorn": "^5.5.0", + "acorn-jsx": "^3.0.0" + } + }, + "esprima": { + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-2.7.3.tgz", + "integrity": "sha1-luO3DVd59q1JzQMmc9HDEnZ7pYE=" + }, + "esquery": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.0.1.tgz", + "integrity": "sha512-SmiyZ5zIWH9VM+SRUReLS5Q8a7GxtRdxEBVZpm98rJM7Sb+A9DVCndXfkeFUd3byderg+EbDkfnevfCwynWaNA==", + "requires": { + "estraverse": "^4.0.0" + } + }, + "esrecurse": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.1.tgz", + "integrity": "sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ==", + "requires": { + "estraverse": "^4.1.0" + } + }, + "estraverse": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", + "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=" + }, + "esutils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", + "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=" + }, + "event-emitter": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/event-emitter/-/event-emitter-0.3.5.tgz", + "integrity": "sha1-34xp7vFkeSPHFXuc6DhAYQsCzDk=", + "requires": { + "d": "1", + "es5-ext": "~0.10.14" + } + }, + "events": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/events/-/events-1.1.1.tgz", + "integrity": "sha1-nr23Y1rQmccNzEwqH1AEKI6L2SQ=" + }, + "evp_bytestokey": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz", + "integrity": "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA==", + "requires": { + "md5.js": "^1.3.4", + "safe-buffer": "^5.1.1" + } + }, + "exec-sh": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/exec-sh/-/exec-sh-0.2.2.tgz", + "integrity": "sha512-FIUCJz1RbuS0FKTdaAafAByGS0CPvU3R0MeHxgtl+djzCc//F8HakL8GzmVNZanasTbTAY/3DRFA0KpVqj/eAw==", + "requires": { + "merge": "^1.2.0" + } + }, + "execa": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-0.7.0.tgz", + "integrity": "sha1-lEvs00zEHuMqY6n68nrVpl/Fl3c=", + "requires": { + "cross-spawn": "^5.0.1", + "get-stream": "^3.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" + } + }, + "expand-brackets": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz", + "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=", + "requires": { + "debug": "^2.3.3", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "posix-character-classes": "^0.1.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "expand-range": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/expand-range/-/expand-range-1.8.2.tgz", + "integrity": "sha1-opnv/TNf4nIeuujiV+x5ZE/IUzc=", + "requires": { + "fill-range": "^2.1.0" + }, + "dependencies": { + "fill-range": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-2.2.4.tgz", + "integrity": "sha512-cnrcCbj01+j2gTG921VZPnHbjmdAf8oQV/iGeV2kZxGSyfYjjTyY79ErsK1WJWMpw6DaApEX72binqJE+/d+5Q==", + "requires": { + "is-number": "^2.1.0", + "isobject": "^2.0.0", + "randomatic": "^3.0.0", + "repeat-element": "^1.1.2", + "repeat-string": "^1.5.2" + } + }, + "is-number": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-2.1.0.tgz", + "integrity": "sha1-Afy7s5NGOlSPL0ZszhbezknbkI8=", + "requires": { + "kind-of": "^3.0.2" + } + }, + "isobject": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", + "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", + "requires": { + "isarray": "1.0.0" + } + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "expand-tilde": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/expand-tilde/-/expand-tilde-2.0.2.tgz", + "integrity": "sha1-l+gBqgUt8CRU3kawK/YhZCzchQI=", + "requires": { + "homedir-polyfill": "^1.0.1" + } + }, + "extend": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.1.tgz", + "integrity": "sha1-p1Xqe8Gt/MWjHOfnYtuq3F5jZEQ=" + }, + "extend-shallow": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-3.0.2.tgz", + "integrity": "sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=", + "requires": { + "assign-symbols": "^1.0.0", + "is-extendable": "^1.0.1" + }, + "dependencies": { + "is-extendable": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", + "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", + "requires": { + "is-plain-object": "^2.0.4" + } + } + } + }, + "external-editor": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-2.2.0.tgz", + "integrity": "sha512-bSn6gvGxKt+b7+6TKEv1ZycHleA7aHhRHyAqJyp5pbUFuYYNIzpZnQDk7AsYckyWdEnTeAnay0aCy2aV6iTk9A==", + "requires": { + "chardet": "^0.4.0", + "iconv-lite": "^0.4.17", + "tmp": "^0.0.33" + } + }, + "extglob": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz", + "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==", + "requires": { + "array-unique": "^0.3.2", + "define-property": "^1.0.0", + "expand-brackets": "^2.1.4", + "extend-shallow": "^2.0.1", + "fragment-cache": "^0.2.1", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "requires": { + "is-extendable": "^0.1.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "extract-text-webpack-plugin": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extract-text-webpack-plugin/-/extract-text-webpack-plugin-3.0.2.tgz", + "integrity": "sha512-bt/LZ4m5Rqt/Crl2HiKuAl/oqg0psx1tsTLkvWbJen1CtD+fftkZhMaQ9HOtY2gWsl2Wq+sABmMVi9z3DhKWQQ==", + "requires": { + "async": "^2.4.1", + "loader-utils": "^1.1.0", + "schema-utils": "^0.3.0", + "webpack-sources": "^1.0.1" + } + }, + "extsprintf": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", + "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=" + }, + "fast-deep-equal": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-1.1.0.tgz", + "integrity": "sha1-wFNHeBfIa1HaqFPIHgWbcz0CNhQ=" + }, + "fast-json-stable-stringify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz", + "integrity": "sha1-1RQsDK7msRifh9OnYREGT4bIu/I=" + }, + "fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=" + }, + "fastparse": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/fastparse/-/fastparse-1.1.1.tgz", + "integrity": "sha1-0eJkOzipTXWDtHkGDmxK/8lAcfg=" + }, + "fb-watchman": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.0.tgz", + "integrity": "sha1-VOmr99+i8mzZsWNsWIwa/AXeXVg=", + "requires": { + "bser": "^2.0.0" + } + }, + "fbjs": { + "version": "0.8.17", + "resolved": "https://registry.npmjs.org/fbjs/-/fbjs-0.8.17.tgz", + "integrity": "sha1-xNWY6taUkRJlPWWIsBpc3Nn5D90=", + "requires": { + "core-js": "^1.0.0", + "isomorphic-fetch": "^2.1.1", + "loose-envify": "^1.0.0", + "object-assign": "^4.1.0", + "promise": "^7.1.1", + "setimmediate": "^1.0.5", + "ua-parser-js": "^0.7.18" + } + }, + "figures": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", + "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", + "requires": { + "escape-string-regexp": "^1.0.5" + } + }, + "file-entry-cache": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-2.0.0.tgz", + "integrity": "sha1-w5KZDD5oR4PYOLjISkXYoEhFg2E=", + "requires": { + "flat-cache": "^1.2.1", + "object-assign": "^4.0.1" + } + }, + "file-loader": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/file-loader/-/file-loader-1.1.5.tgz", + "integrity": "sha512-RzGHDatcVNpGISTvCpfUfOGpYuSR7HSsSg87ki+wF6rw1Hm0RALPTiAdsxAq1UwLf0RRhbe22/eHK6nhXspiOQ==", + "requires": { + "loader-utils": "^1.0.2", + "schema-utils": "^0.3.0" + } + }, + "filename-regex": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/filename-regex/-/filename-regex-2.0.1.tgz", + "integrity": "sha1-wcS5vuPglyXdsQa3XB4wH+LxiyY=" + }, + "fileset": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/fileset/-/fileset-2.0.3.tgz", + "integrity": "sha1-jnVIqW08wjJ+5eZ0FocjozO7oqA=", + "requires": { + "glob": "^7.0.3", + "minimatch": "^3.0.3" + } + }, + "filesize": { + "version": "3.5.11", + "resolved": "https://registry.npmjs.org/filesize/-/filesize-3.5.11.tgz", + "integrity": "sha512-ZH7loueKBoDb7yG9esn1U+fgq7BzlzW6NRi5/rMdxIZ05dj7GFD/Xc5rq2CDt5Yq86CyfSYVyx4242QQNZbx1g==" + }, + "fill-range": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", + "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=", + "requires": { + "extend-shallow": "^2.0.1", + "is-number": "^3.0.0", + "repeat-string": "^1.6.1", + "to-regex-range": "^2.1.0" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "find-cache-dir": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-1.0.0.tgz", + "integrity": "sha1-kojj6ePMN0hxfTnq3hfPcfww7m8=", + "requires": { + "commondir": "^1.0.1", + "make-dir": "^1.0.0", + "pkg-dir": "^2.0.0" + } + }, + "find-up": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", + "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", + "requires": { + "locate-path": "^2.0.0" + } + }, + "flat-cache": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-1.3.0.tgz", + "integrity": "sha1-0wMLMrOBVPTjt+nHCfSQ9++XxIE=", + "requires": { + "circular-json": "^0.3.1", + "del": "^2.0.2", + "graceful-fs": "^4.1.2", + "write": "^0.2.1" + } + }, + "flatten": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/flatten/-/flatten-1.0.2.tgz", + "integrity": "sha1-2uRqnXj74lKSJYzB54CkHZXAN4I=" + }, + "for-in": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", + "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=" + }, + "for-own": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/for-own/-/for-own-0.1.5.tgz", + "integrity": "sha1-UmXGgaTylNq78XyVCbZ2OqhFEM4=", + "requires": { + "for-in": "^1.0.1" + } + }, + "foreach": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/foreach/-/foreach-2.0.5.tgz", + "integrity": "sha1-C+4AUBiusmDQo6865ljdATbsG5k=" + }, + "forever-agent": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", + "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=" + }, + "form-data": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.2.tgz", + "integrity": "sha1-SXBJi+YEwgwAXU9cI67NIda0kJk=", + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "1.0.6", + "mime-types": "^2.1.12" + } + }, + "fragment-cache": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", + "integrity": "sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=", + "requires": { + "map-cache": "^0.2.2" + } + }, + "fs-extra": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-3.0.1.tgz", + "integrity": "sha1-N5TzeMWLNC6n27sjCVEJxLO2IpE=", + "requires": { + "graceful-fs": "^4.1.2", + "jsonfile": "^3.0.0", + "universalify": "^0.1.0" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" + }, + "fsevents": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.4.tgz", + "integrity": "sha512-z8H8/diyk76B7q5wg+Ud0+CqzcAF3mBBI/bA5ne5zrRUUIvNkJY//D3BqyH571KuAC4Nr7Rw7CjWX4r0y9DvNg==", + "optional": true, + "requires": { + "nan": "^2.9.2", + "node-pre-gyp": "^0.10.0" + }, + "dependencies": { + "abbrev": { + "version": "1.1.1", + "bundled": true, + "optional": true + }, + "ansi-regex": { + "version": "2.1.1", + "bundled": true, + "optional": true + }, + "aproba": { + "version": "1.2.0", + "bundled": true, + "optional": true + }, + "are-we-there-yet": { + "version": "1.1.4", + "bundled": true, + "optional": true, + "requires": { + "delegates": "^1.0.0", + "readable-stream": "^2.0.6" + } + }, + "balanced-match": { + "version": "1.0.0", + "bundled": true, + "optional": true + }, + "brace-expansion": { + "version": "1.1.11", + "bundled": true, + "optional": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "chownr": { + "version": "1.0.1", + "bundled": true, + "optional": true + }, + "code-point-at": { + "version": "1.1.0", + "bundled": true, + "optional": true + }, + "concat-map": { + "version": "0.0.1", + "bundled": true, + "optional": true + }, + "console-control-strings": { + "version": "1.1.0", + "bundled": true, + "optional": true + }, + "core-util-is": { + "version": "1.0.2", + "bundled": true, + "optional": true + }, + "debug": { + "version": "2.6.9", + "bundled": true, + "optional": true, + "requires": { + "ms": "2.0.0" + } + }, + "deep-extend": { + "version": "0.5.1", + "bundled": true, + "optional": true + }, + "delegates": { + "version": "1.0.0", + "bundled": true, + "optional": true + }, + "detect-libc": { + "version": "1.0.3", + "bundled": true, + "optional": true + }, + "fs-minipass": { + "version": "1.2.5", + "bundled": true, + "optional": true, + "requires": { + "minipass": "^2.2.1" + } + }, + "fs.realpath": { + "version": "1.0.0", + "bundled": true, + "optional": true + }, + "gauge": { + "version": "2.7.4", + "bundled": true, + "optional": true, + "requires": { + "aproba": "^1.0.3", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.0", + "object-assign": "^4.1.0", + "signal-exit": "^3.0.0", + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wide-align": "^1.1.0" + } + }, + "glob": { + "version": "7.1.2", + "bundled": true, + "optional": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "has-unicode": { + "version": "2.0.1", + "bundled": true, + "optional": true + }, + "iconv-lite": { + "version": "0.4.21", + "bundled": true, + "optional": true, + "requires": { + "safer-buffer": "^2.1.0" + } + }, + "ignore-walk": { + "version": "3.0.1", + "bundled": true, + "optional": true, + "requires": { + "minimatch": "^3.0.4" + } + }, + "inflight": { + "version": "1.0.6", + "bundled": true, + "optional": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.3", + "bundled": true, + "optional": true + }, + "ini": { + "version": "1.3.5", + "bundled": true, + "optional": true + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "bundled": true, + "optional": true, + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "isarray": { + "version": "1.0.0", + "bundled": true, + "optional": true + }, + "minimatch": { + "version": "3.0.4", + "bundled": true, + "optional": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.8", + "bundled": true, + "optional": true + }, + "minipass": { + "version": "2.2.4", + "bundled": true, + "optional": true, + "requires": { + "safe-buffer": "^5.1.1", + "yallist": "^3.0.0" + } + }, + "minizlib": { + "version": "1.1.0", + "bundled": true, + "optional": true, + "requires": { + "minipass": "^2.2.1" + } + }, + "mkdirp": { + "version": "0.5.1", + "bundled": true, + "optional": true, + "requires": { + "minimist": "0.0.8" + } + }, + "ms": { + "version": "2.0.0", + "bundled": true, + "optional": true + }, + "needle": { + "version": "2.2.0", + "bundled": true, + "optional": true, + "requires": { + "debug": "^2.1.2", + "iconv-lite": "^0.4.4", + "sax": "^1.2.4" + } + }, + "node-pre-gyp": { + "version": "0.10.0", + "bundled": true, + "optional": true, + "requires": { + "detect-libc": "^1.0.2", + "mkdirp": "^0.5.1", + "needle": "^2.2.0", + "nopt": "^4.0.1", + "npm-packlist": "^1.1.6", + "npmlog": "^4.0.2", + "rc": "^1.1.7", + "rimraf": "^2.6.1", + "semver": "^5.3.0", + "tar": "^4" + } + }, + "nopt": { + "version": "4.0.1", + "bundled": true, + "optional": true, + "requires": { + "abbrev": "1", + "osenv": "^0.1.4" + } + }, + "npm-bundled": { + "version": "1.0.3", + "bundled": true, + "optional": true + }, + "npm-packlist": { + "version": "1.1.10", + "bundled": true, + "optional": true, + "requires": { + "ignore-walk": "^3.0.1", + "npm-bundled": "^1.0.1" + } + }, + "npmlog": { + "version": "4.1.2", + "bundled": true, + "optional": true, + "requires": { + "are-we-there-yet": "~1.1.2", + "console-control-strings": "~1.1.0", + "gauge": "~2.7.3", + "set-blocking": "~2.0.0" + } + }, + "number-is-nan": { + "version": "1.0.1", + "bundled": true, + "optional": true + }, + "object-assign": { + "version": "4.1.1", + "bundled": true, + "optional": true + }, + "once": { + "version": "1.4.0", + "bundled": true, + "optional": true, + "requires": { + "wrappy": "1" + } + }, + "os-homedir": { + "version": "1.0.2", + "bundled": true, + "optional": true + }, + "os-tmpdir": { + "version": "1.0.2", + "bundled": true, + "optional": true + }, + "osenv": { + "version": "0.1.5", + "bundled": true, + "optional": true, + "requires": { + "os-homedir": "^1.0.0", + "os-tmpdir": "^1.0.0" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "bundled": true, + "optional": true + }, + "process-nextick-args": { + "version": "2.0.0", + "bundled": true, + "optional": true + }, + "rc": { + "version": "1.2.7", + "bundled": true, + "optional": true, + "requires": { + "deep-extend": "^0.5.1", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "bundled": true, + "optional": true + } + } + }, + "readable-stream": { + "version": "2.3.6", + "bundled": true, + "optional": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "rimraf": { + "version": "2.6.2", + "bundled": true, + "optional": true, + "requires": { + "glob": "^7.0.5" + } + }, + "safe-buffer": { + "version": "5.1.1", + "bundled": true, + "optional": true + }, + "safer-buffer": { + "version": "2.1.2", + "bundled": true, + "optional": true + }, + "sax": { + "version": "1.2.4", + "bundled": true, + "optional": true + }, + "semver": { + "version": "5.5.0", + "bundled": true, + "optional": true + }, + "set-blocking": { + "version": "2.0.0", + "bundled": true, + "optional": true + }, + "signal-exit": { + "version": "3.0.2", + "bundled": true, + "optional": true + }, + "string-width": { + "version": "1.0.2", + "bundled": true, + "optional": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + }, + "string_decoder": { + "version": "1.1.1", + "bundled": true, + "optional": true, + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "bundled": true, + "optional": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "strip-json-comments": { + "version": "2.0.1", + "bundled": true, + "optional": true + }, + "tar": { + "version": "4.4.1", + "bundled": true, + "optional": true, + "requires": { + "chownr": "^1.0.1", + "fs-minipass": "^1.2.5", + "minipass": "^2.2.4", + "minizlib": "^1.1.0", + "mkdirp": "^0.5.0", + "safe-buffer": "^5.1.1", + "yallist": "^3.0.2" + } + }, + "util-deprecate": { + "version": "1.0.2", + "bundled": true, + "optional": true + }, + "wide-align": { + "version": "1.1.2", + "bundled": true, + "optional": true, + "requires": { + "string-width": "^1.0.2" + } + }, + "wrappy": { + "version": "1.0.2", + "bundled": true, + "optional": true + }, + "yallist": { + "version": "3.0.2", + "bundled": true, + "optional": true + } + } + }, + "function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + }, + "functional-red-black-tree": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", + "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=" + }, + "get-caller-file": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-1.0.2.tgz", + "integrity": "sha1-9wLmMSfn4jHBYKgMFVSstw1QR+U=" + }, + "get-stdin": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz", + "integrity": "sha1-uWjGsKBDhDJJAui/Gl3zJXmkUP4=" + }, + "get-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-3.0.0.tgz", + "integrity": "sha1-jpQ9E1jcN1VQVOy+LtsFqhdO3hQ=" + }, + "get-value": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz", + "integrity": "sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=" + }, + "getpass": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", + "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", + "requires": { + "assert-plus": "^1.0.0" + } + }, + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "glob-base": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/glob-base/-/glob-base-0.3.0.tgz", + "integrity": "sha1-27Fk9iIbHAscz4Kuoyi0l98Oo8Q=", + "requires": { + "glob-parent": "^2.0.0", + "is-glob": "^2.0.0" + } + }, + "glob-parent": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-2.0.0.tgz", + "integrity": "sha1-gTg9ctsFT8zPUzbaqQLxgvbtuyg=", + "requires": { + "is-glob": "^2.0.0" + } + }, + "global-dirs": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/global-dirs/-/global-dirs-0.1.1.tgz", + "integrity": "sha1-sxnA3UYH81PzvpzKTHL8FIxJ9EU=", + "requires": { + "ini": "^1.3.4" + } + }, + "global-modules": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-1.0.0.tgz", + "integrity": "sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg==", + "requires": { + "global-prefix": "^1.0.1", + "is-windows": "^1.0.1", + "resolve-dir": "^1.0.0" + } + }, + "global-prefix": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-1.0.2.tgz", + "integrity": "sha1-2/dDxsFJklk8ZVVoy2btMsASLr4=", + "requires": { + "expand-tilde": "^2.0.2", + "homedir-polyfill": "^1.0.1", + "ini": "^1.3.4", + "is-windows": "^1.0.1", + "which": "^1.2.14" + } + }, + "globals": { + "version": "9.18.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-9.18.0.tgz", + "integrity": "sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ==" + }, + "globby": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-5.0.0.tgz", + "integrity": "sha1-69hGZ8oNuzMLmbz8aOrCvFQ3Dg0=", + "requires": { + "array-union": "^1.0.1", + "arrify": "^1.0.0", + "glob": "^7.0.3", + "object-assign": "^4.0.1", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" + } + }, + "got": { + "version": "6.7.1", + "resolved": "https://registry.npmjs.org/got/-/got-6.7.1.tgz", + "integrity": "sha1-JAzQV4WpoY5WHcG0S0HHY+8ejbA=", + "requires": { + "create-error-class": "^3.0.0", + "duplexer3": "^0.1.4", + "get-stream": "^3.0.0", + "is-redirect": "^1.0.0", + "is-retry-allowed": "^1.0.0", + "is-stream": "^1.0.0", + "lowercase-keys": "^1.0.0", + "safe-buffer": "^5.0.1", + "timed-out": "^4.0.0", + "unzip-response": "^2.0.1", + "url-parse-lax": "^1.0.0" + } + }, + "graceful-fs": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", + "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=" + }, + "growly": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/growly/-/growly-1.3.0.tgz", + "integrity": "sha1-8QdIy+dq+WS3yWyTxrzCivEgwIE=" + }, + "gzip-size": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/gzip-size/-/gzip-size-3.0.0.tgz", + "integrity": "sha1-VGGI6b3DN/Zzdy+BZgRks4nc5SA=", + "requires": { + "duplexer": "^0.1.1" + } + }, + "handlebars": { + "version": "4.0.11", + "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.0.11.tgz", + "integrity": "sha1-Ywo13+ApS8KB7a5v/F0yn8eYLcw=", + "requires": { + "async": "^1.4.0", + "optimist": "^0.6.1", + "source-map": "^0.4.4", + "uglify-js": "^2.6" + }, + "dependencies": { + "async": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", + "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" + }, + "source-map": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.4.4.tgz", + "integrity": "sha1-66T12pwNyZneaAMti092FzZSA2s=", + "requires": { + "amdefine": ">=0.0.4" + } + }, + "uglify-js": { + "version": "2.8.29", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-2.8.29.tgz", + "integrity": "sha1-KcVzMUgFe7Th913zW3qcty5qWd0=", + "optional": true, + "requires": { + "source-map": "~0.5.1", + "uglify-to-browserify": "~1.0.0", + "yargs": "~3.10.0" + }, + "dependencies": { + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "optional": true + } + } + }, + "yargs": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-3.10.0.tgz", + "integrity": "sha1-9+572FfdfB0tOMDnTvvWgdFDH9E=", + "optional": true, + "requires": { + "camelcase": "^1.0.2", + "cliui": "^2.1.0", + "decamelize": "^1.0.0", + "window-size": "0.1.0" + } + } + } + }, + "har-schema": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", + "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=" + }, + "har-validator": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.0.3.tgz", + "integrity": "sha1-ukAsJmGU8VlW7xXg/PJCmT9qff0=", + "requires": { + "ajv": "^5.1.0", + "har-schema": "^2.0.0" + } + }, + "has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "requires": { + "function-bind": "^1.1.1" + } + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + }, + "has-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz", + "integrity": "sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=", + "requires": { + "get-value": "^2.0.6", + "has-values": "^1.0.0", + "isobject": "^3.0.0" + } + }, + "has-values": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-values/-/has-values-1.0.0.tgz", + "integrity": "sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=", + "requires": { + "is-number": "^3.0.0", + "kind-of": "^4.0.0" + }, + "dependencies": { + "kind-of": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-4.0.0.tgz", + "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "hash-base": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-3.0.4.tgz", + "integrity": "sha1-X8hoaEfs1zSZQDMZprCj8/auSRg=", + "requires": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "hash.js": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.4.tgz", + "integrity": "sha512-A6RlQvvZEtFS5fLU43IDu0QUmBy+fDO9VMdTXvufKwIkt/rFfvICAViCax5fbDO4zdNzaC3/27ZhKUok5bAJyw==", + "requires": { + "inherits": "^2.0.3", + "minimalistic-assert": "^1.0.0" + } + }, + "he": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/he/-/he-1.1.1.tgz", + "integrity": "sha1-k0EP0hsAlzUVH4howvJx80J+I/0=" + }, + "hmac-drbg": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz", + "integrity": "sha1-0nRXAQJabHdabFRXk+1QL8DGSaE=", + "requires": { + "hash.js": "^1.0.3", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.1" + } + }, + "home-or-tmp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/home-or-tmp/-/home-or-tmp-2.0.0.tgz", + "integrity": "sha1-42w/LSyufXRqhX440Y1fMqeILbg=", + "requires": { + "os-homedir": "^1.0.0", + "os-tmpdir": "^1.0.1" + } + }, + "homedir-polyfill": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/homedir-polyfill/-/homedir-polyfill-1.0.1.tgz", + "integrity": "sha1-TCu8inWJmP7r9e1oWA921GdotLw=", + "requires": { + "parse-passwd": "^1.0.0" + } + }, + "hosted-git-info": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.6.1.tgz", + "integrity": "sha512-Ba4+0M4YvIDUUsprMjhVTU1yN9F2/LJSAl69ZpzaLT4l4j5mwTS6jqqW9Ojvj6lKz/veqPzpJBqGbXspOb533A==" + }, + "html-comment-regex": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/html-comment-regex/-/html-comment-regex-1.1.1.tgz", + "integrity": "sha1-ZouTd26q5V696POtRkswekljYl4=" + }, + "html-encoding-sniffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-1.0.2.tgz", + "integrity": "sha512-71lZziiDnsuabfdYiUeWdCVyKuqwWi23L8YeIgV9jSSZHCtb6wB1BKWooH7L3tn4/FuZJMVWyNaIDr4RGmaSYw==", + "requires": { + "whatwg-encoding": "^1.0.1" + } + }, + "html-minifier": { + "version": "3.5.17", + "resolved": "https://registry.npmjs.org/html-minifier/-/html-minifier-3.5.17.tgz", + "integrity": "sha512-O+StuKL0UWfwX5Zv4rFxd60DPcT5DVjGq1AlnP6VQ8wzudft/W4hx5Wl98aSYNwFBHY6XWJreRw/BehX4l+diQ==", + "requires": { + "camel-case": "3.0.x", + "clean-css": "4.1.x", + "commander": "2.15.x", + "he": "1.1.x", + "param-case": "2.1.x", + "relateurl": "0.2.x", + "uglify-js": "3.4.x" + }, + "dependencies": { + "commander": { + "version": "2.15.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.15.1.tgz", + "integrity": "sha512-VlfT9F3V0v+jr4yxPc5gg9s62/fIVWsd2Bk2iD435um1NlGMYdVCq+MjcXnhYq2icNOizHr1kK+5TI6H0Hy0ag==" + } + } + }, + "html-webpack-plugin": { + "version": "2.29.0", + "resolved": "https://registry.npmjs.org/html-webpack-plugin/-/html-webpack-plugin-2.29.0.tgz", + "integrity": "sha1-6Yf0IYU9O2k4yMTIFxhC5f0XryM=", + "requires": { + "bluebird": "^3.4.7", + "html-minifier": "^3.2.3", + "loader-utils": "^0.2.16", + "lodash": "^4.17.3", + "pretty-error": "^2.0.2", + "toposort": "^1.0.0" + }, + "dependencies": { + "loader-utils": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-0.2.17.tgz", + "integrity": "sha1-+G5jdNQyBabmxg6RlvF8Apm/s0g=", + "requires": { + "big.js": "^3.1.3", + "emojis-list": "^2.0.0", + "json5": "^0.5.0", + "object-assign": "^4.0.1" + } + } + } + }, + "htmlparser2": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.3.0.tgz", + "integrity": "sha1-zHDQWln2VC5D8OaFyYLhTJJKnv4=", + "requires": { + "domelementtype": "1", + "domhandler": "2.1", + "domutils": "1.1", + "readable-stream": "1.0" + }, + "dependencies": { + "domutils": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.1.6.tgz", + "integrity": "sha1-vdw94Jm5ou+sxRxiPyj0FuzFdIU=", + "requires": { + "domelementtype": "1" + } + }, + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=" + }, + "readable-stream": { + "version": "1.0.34", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", + "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=" + } + } + }, + "http-signature": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", + "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", + "requires": { + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" + } + }, + "https-browserify": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/https-browserify/-/https-browserify-1.0.0.tgz", + "integrity": "sha1-7AbBDgo0wPL68Zn3/X/Hj//QPHM=" + }, + "iconv-lite": { + "version": "0.4.23", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.23.tgz", + "integrity": "sha512-neyTUVFtahjf0mB3dZT77u+8O0QB89jFdnBkd5P1JgYPbPaia3gXXOVL2fq8VyU2gMMD7SaN7QukTB/pmXYvDA==", + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "icss-replace-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/icss-replace-symbols/-/icss-replace-symbols-1.1.0.tgz", + "integrity": "sha1-Bupvg2ead0njhs/h/oEq5dsiPe0=" + }, + "icss-utils": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/icss-utils/-/icss-utils-2.1.0.tgz", + "integrity": "sha1-g/Cg7DeL8yRheLbCrZE28TWxyWI=", + "requires": { + "postcss": "^6.0.1" + } + }, + "ieee754": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.12.tgz", + "integrity": "sha512-GguP+DRY+pJ3soyIiGPTvdiVXjZ+DbXOxGpXn3eMvNW4x4irjqXm4wHKscC+TfxSJ0yw/S1F24tqdMNsMZTiLA==" + }, + "ignore": { + "version": "3.3.10", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-3.3.10.tgz", + "integrity": "sha512-Pgs951kaMm5GXP7MOvxERINe3gsaVjUWFm+UZPSq9xYriQAksyhg0csnS0KXSNRD5NmNdapXEpjxG49+AKh/ug==" + }, + "import-lazy": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/import-lazy/-/import-lazy-2.1.0.tgz", + "integrity": "sha1-BWmOPUXIjo1+nZLLBYTnfwlvPkM=" + }, + "imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=" + }, + "indent-string": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-2.1.0.tgz", + "integrity": "sha1-ji1INIdCEhtKghi3oTfppSBJ3IA=", + "requires": { + "repeating": "^2.0.0" + } + }, + "indexes-of": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/indexes-of/-/indexes-of-1.0.1.tgz", + "integrity": "sha1-8w9xbI4r00bHtn0985FVZqfAVgc=" + }, + "indexof": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/indexof/-/indexof-0.0.1.tgz", + "integrity": "sha1-gtwzbSMrkGIXnQWrMpOmYFn9Q10=" + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" + }, + "ini": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.5.tgz", + "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" + }, + "inquirer": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-3.3.0.tgz", + "integrity": "sha512-h+xtnyk4EwKvFWHrUYsWErEVR+igKtLdchu+o0Z1RL7VU/jVMFbYir2bp6bAj8efFNxWqHX0dIss6fJQ+/+qeQ==", + "requires": { + "ansi-escapes": "^3.0.0", + "chalk": "^2.0.0", + "cli-cursor": "^2.1.0", + "cli-width": "^2.0.0", + "external-editor": "^2.0.4", + "figures": "^2.0.0", + "lodash": "^4.3.0", + "mute-stream": "0.0.7", + "run-async": "^2.2.0", + "rx-lite": "^4.0.8", + "rx-lite-aggregates": "^4.0.8", + "string-width": "^2.1.0", + "strip-ansi": "^4.0.0", + "through": "^2.3.6" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" + }, + "chalk": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", + "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "requires": { + "ansi-regex": "^3.0.0" + } + } + } + }, + "interpret": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.1.0.tgz", + "integrity": "sha1-ftGxQQxqDg94z5XTuEQMY/eLhhQ=" + }, + "invariant": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz", + "integrity": "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==", + "requires": { + "loose-envify": "^1.0.0" + } + }, + "invert-kv": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-1.0.0.tgz", + "integrity": "sha1-EEqOSqym09jNFXqO+L+rLXo//bY=" + }, + "is-absolute-url": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-absolute-url/-/is-absolute-url-2.1.0.tgz", + "integrity": "sha1-UFMN+4T8yap9vnhS6Do3uTufKqY=" + }, + "is-accessor-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=" + }, + "is-binary-path": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-1.0.1.tgz", + "integrity": "sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg=", + "requires": { + "binary-extensions": "^1.0.0" + } + }, + "is-buffer": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==" + }, + "is-builtin-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-builtin-module/-/is-builtin-module-1.0.0.tgz", + "integrity": "sha1-VAVy0096wxGfj3bDDLwbHgN6/74=", + "requires": { + "builtin-modules": "^1.0.0" + } + }, + "is-callable": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.3.tgz", + "integrity": "sha1-hut1OSgF3cM69xySoO7fdO52BLI=" + }, + "is-ci": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-1.1.0.tgz", + "integrity": "sha512-c7TnwxLePuqIlxHgr7xtxzycJPegNHFuIrBkwbf8hc58//+Op1CqFkyS+xnIMkwn9UsJIwc174BIjkyBmSpjKg==", + "requires": { + "ci-info": "^1.0.0" + } + }, + "is-data-descriptor": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-date-object": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.1.tgz", + "integrity": "sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY=" + }, + "is-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", + "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", + "requires": { + "is-accessor-descriptor": "^0.1.6", + "is-data-descriptor": "^0.1.4", + "kind-of": "^5.0.0" + }, + "dependencies": { + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==" + } + } + }, + "is-directory": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/is-directory/-/is-directory-0.3.1.tgz", + "integrity": "sha1-YTObbyR1/Hcv2cnYP1yFddwVSuE=" + }, + "is-dotfile": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/is-dotfile/-/is-dotfile-1.0.3.tgz", + "integrity": "sha1-pqLzL/0t+wT1yiXs0Pa4PPeYoeE=" + }, + "is-equal-shallow": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/is-equal-shallow/-/is-equal-shallow-0.1.3.tgz", + "integrity": "sha1-IjgJj8Ih3gvPpdnqxMRdY4qhxTQ=", + "requires": { + "is-primitive": "^2.0.0" + } + }, + "is-extendable": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", + "integrity": "sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=" + }, + "is-extglob": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-1.0.0.tgz", + "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=" + }, + "is-finite": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", + "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=" + }, + "is-glob": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-2.0.1.tgz", + "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", + "requires": { + "is-extglob": "^1.0.0" + } + }, + "is-installed-globally": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/is-installed-globally/-/is-installed-globally-0.1.0.tgz", + "integrity": "sha1-Df2Y9akRFxbdU13aZJL2e/PSWoA=", + "requires": { + "global-dirs": "^0.1.0", + "is-path-inside": "^1.0.0" + } + }, + "is-npm": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-npm/-/is-npm-1.0.0.tgz", + "integrity": "sha1-8vtjpl5JBbQGyGBydloaTceTufQ=" + }, + "is-number": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", + "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-obj": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", + "integrity": "sha1-PkcprB9f3gJc19g6iW2rn09n2w8=" + }, + "is-path-cwd": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-1.0.0.tgz", + "integrity": "sha1-0iXsIxMuie3Tj9p2dHLmLmXxEG0=" + }, + "is-path-in-cwd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-path-in-cwd/-/is-path-in-cwd-1.0.1.tgz", + "integrity": "sha512-FjV1RTW48E7CWM7eE/J2NJvAEEVektecDBVBE5Hh3nM1Jd0kvhHtX68Pr3xsDf857xt3Y4AkwVULK1Vku62aaQ==", + "requires": { + "is-path-inside": "^1.0.0" + } + }, + "is-path-inside": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-1.0.1.tgz", + "integrity": "sha1-jvW33lBDej/cprToZe96pVy0gDY=", + "requires": { + "path-is-inside": "^1.0.1" + } + }, + "is-plain-obj": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-1.1.0.tgz", + "integrity": "sha1-caUMhCnfync8kqOQpKA7OfzVHT4=" + }, + "is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "requires": { + "isobject": "^3.0.1" + } + }, + "is-posix-bracket": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-posix-bracket/-/is-posix-bracket-0.1.1.tgz", + "integrity": "sha1-MzTceXdDaOkvAW5vvAqI9c1ua8Q=" + }, + "is-primitive": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-primitive/-/is-primitive-2.0.0.tgz", + "integrity": "sha1-IHurkWOEmcB7Kt8kCkGochADRXU=" + }, + "is-promise": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz", + "integrity": "sha1-eaKp7OfwlugPNtKy87wWwf9L8/o=" + }, + "is-redirect": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-redirect/-/is-redirect-1.0.0.tgz", + "integrity": "sha1-HQPd7VO9jbDzDCbk+V02/HyH3CQ=" + }, + "is-regex": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.4.tgz", + "integrity": "sha1-VRdIm1RwkbCTDglWVM7SXul+lJE=", + "requires": { + "has": "^1.0.1" + } + }, + "is-resolvable": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-resolvable/-/is-resolvable-1.1.0.tgz", + "integrity": "sha512-qgDYXFSR5WvEfuS5dMj6oTMEbrrSaM0CrFk2Yiq/gXnBvD9pMa2jGXxyhGLfvhZpuMZe18CJpFxAt3CRs42NMg==" + }, + "is-retry-allowed": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-retry-allowed/-/is-retry-allowed-1.1.0.tgz", + "integrity": "sha1-EaBgVotnM5REAz0BJaYaINVk+zQ=" + }, + "is-root": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-root/-/is-root-1.0.0.tgz", + "integrity": "sha1-B7bCM7w5TNnQK6FclmvWZg1jQtU=" + }, + "is-stream": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", + "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=" + }, + "is-svg": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-svg/-/is-svg-2.1.0.tgz", + "integrity": "sha1-z2EJDaDZ77yrhyLeum8DIgjbsOk=", + "requires": { + "html-comment-regex": "^1.1.0" + } + }, + "is-symbol": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.1.tgz", + "integrity": "sha1-PMWfAAJRlLarLjjbrmaJJWtmBXI=" + }, + "is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=" + }, + "is-utf8": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", + "integrity": "sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI=" + }, + "is-windows": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", + "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==" + }, + "is-wsl": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-1.1.0.tgz", + "integrity": "sha1-HxbkqiKwTRM2tmGIpmrzxgDDpm0=" + }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=" + }, + "isomorphic-fetch": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/isomorphic-fetch/-/isomorphic-fetch-2.2.1.tgz", + "integrity": "sha1-YRrhrPFPXoH3KVB0coGf6XM1WKk=", + "requires": { + "node-fetch": "^1.0.1", + "whatwg-fetch": ">=0.10.0" + } + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=" + }, + "istanbul-api": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/istanbul-api/-/istanbul-api-1.3.1.tgz", + "integrity": "sha512-duj6AlLcsWNwUpfyfHt0nWIeRiZpuShnP40YTxOGQgtaN8fd6JYSxsvxUphTDy8V5MfDXo4s/xVCIIvVCO808g==", + "requires": { + "async": "^2.1.4", + "compare-versions": "^3.1.0", + "fileset": "^2.0.2", + "istanbul-lib-coverage": "^1.2.0", + "istanbul-lib-hook": "^1.2.0", + "istanbul-lib-instrument": "^1.10.1", + "istanbul-lib-report": "^1.1.4", + "istanbul-lib-source-maps": "^1.2.4", + "istanbul-reports": "^1.3.0", + "js-yaml": "^3.7.0", + "mkdirp": "^0.5.1", + "once": "^1.4.0" + }, + "dependencies": { + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "requires": { + "ms": "2.0.0" + } + }, + "istanbul-lib-source-maps": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-1.2.5.tgz", + "integrity": "sha512-8O2T/3VhrQHn0XcJbP1/GN7kXMiRAlPi+fj3uEHrjBD8Oz7Py0prSC25C09NuAZS6bgW1NNKAvCSHZXB0irSGA==", + "requires": { + "debug": "^3.1.0", + "istanbul-lib-coverage": "^1.2.0", + "mkdirp": "^0.5.1", + "rimraf": "^2.6.1", + "source-map": "^0.5.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + } + } + }, + "istanbul-lib-coverage": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-1.2.0.tgz", + "integrity": "sha512-GvgM/uXRwm+gLlvkWHTjDAvwynZkL9ns15calTrmhGgowlwJBbWMYzWbKqE2DT6JDP1AFXKa+Zi0EkqNCUqY0A==" + }, + "istanbul-lib-hook": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-hook/-/istanbul-lib-hook-1.2.1.tgz", + "integrity": "sha512-eLAMkPG9FU0v5L02lIkcj/2/Zlz9OuluaXikdr5iStk8FDbSwAixTK9TkYxbF0eNnzAJTwM2fkV2A1tpsIp4Jg==", + "requires": { + "append-transform": "^1.0.0" + } + }, + "istanbul-lib-instrument": { + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-1.10.1.tgz", + "integrity": "sha512-1dYuzkOCbuR5GRJqySuZdsmsNKPL3PTuyPevQfoCXJePT9C8y1ga75neU+Tuy9+yS3G/dgx8wgOmp2KLpgdoeQ==", + "requires": { + "babel-generator": "^6.18.0", + "babel-template": "^6.16.0", + "babel-traverse": "^6.18.0", + "babel-types": "^6.18.0", + "babylon": "^6.18.0", + "istanbul-lib-coverage": "^1.2.0", + "semver": "^5.3.0" + } + }, + "istanbul-lib-report": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-1.1.4.tgz", + "integrity": "sha512-Azqvq5tT0U09nrncK3q82e/Zjkxa4tkFZv7E6VcqP0QCPn6oNljDPfrZEC/umNXds2t7b8sRJfs6Kmpzt8m2kA==", + "requires": { + "istanbul-lib-coverage": "^1.2.0", + "mkdirp": "^0.5.1", + "path-parse": "^1.0.5", + "supports-color": "^3.1.2" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "istanbul-lib-source-maps": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-1.2.3.tgz", + "integrity": "sha512-fDa0hwU/5sDXwAklXgAoCJCOsFsBplVQ6WBldz5UwaqOzmDhUK4nfuR7/G//G2lERlblUNJB8P6e8cXq3a7MlA==", + "requires": { + "debug": "^3.1.0", + "istanbul-lib-coverage": "^1.1.2", + "mkdirp": "^0.5.1", + "rimraf": "^2.6.1", + "source-map": "^0.5.3" + }, + "dependencies": { + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "requires": { + "ms": "2.0.0" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + } + } + }, + "istanbul-reports": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-1.3.0.tgz", + "integrity": "sha512-y2Z2IMqE1gefWUaVjrBm0mSKvUkaBy9Vqz8iwr/r40Y9hBbIteH5wqHG/9DLTfJ9xUnUT2j7A3+VVJ6EaYBllA==", + "requires": { + "handlebars": "^4.0.3" + } + }, + "jest": { + "version": "20.0.4", + "resolved": "https://registry.npmjs.org/jest/-/jest-20.0.4.tgz", + "integrity": "sha1-PdJgwpidba1nix6cxNkZRPbWAqw=", + "requires": { + "jest-cli": "^20.0.4" + }, + "dependencies": { + "ansi-escapes": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-1.4.0.tgz", + "integrity": "sha1-06ioOzGapneTZisT52HHkRQiMG4=" + }, + "arr-diff": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-2.0.0.tgz", + "integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=", + "requires": { + "arr-flatten": "^1.0.1" + } + }, + "array-unique": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.2.1.tgz", + "integrity": "sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=" + }, + "braces": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/braces/-/braces-1.8.5.tgz", + "integrity": "sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=", + "requires": { + "expand-range": "^1.8.1", + "preserve": "^0.2.0", + "repeat-element": "^1.1.2" + } + }, + "callsites": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-2.0.0.tgz", + "integrity": "sha1-BuuE8A7qQT2oav/vrL/7Ngk7PFA=" + }, + "expand-brackets": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-0.1.5.tgz", + "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=", + "requires": { + "is-posix-bracket": "^0.1.0" + } + }, + "extglob": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-0.3.2.tgz", + "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=", + "requires": { + "is-extglob": "^1.0.0" + } + }, + "jest-cli": { + "version": "20.0.4", + "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-20.0.4.tgz", + "integrity": "sha1-5TKxnYiuW8bEF+iwWTpv6VSx3JM=", + "requires": { + "ansi-escapes": "^1.4.0", + "callsites": "^2.0.0", + "chalk": "^1.1.3", + "graceful-fs": "^4.1.11", + "is-ci": "^1.0.10", + "istanbul-api": "^1.1.1", + "istanbul-lib-coverage": "^1.0.1", + "istanbul-lib-instrument": "^1.4.2", + "istanbul-lib-source-maps": "^1.1.0", + "jest-changed-files": "^20.0.3", + "jest-config": "^20.0.4", + "jest-docblock": "^20.0.3", + "jest-environment-jsdom": "^20.0.3", + "jest-haste-map": "^20.0.4", + "jest-jasmine2": "^20.0.4", + "jest-message-util": "^20.0.3", + "jest-regex-util": "^20.0.3", + "jest-resolve-dependencies": "^20.0.3", + "jest-runtime": "^20.0.4", + "jest-snapshot": "^20.0.3", + "jest-util": "^20.0.3", + "micromatch": "^2.3.11", + "node-notifier": "^5.0.2", + "pify": "^2.3.0", + "slash": "^1.0.0", + "string-length": "^1.0.1", + "throat": "^3.0.0", + "which": "^1.2.12", + "worker-farm": "^1.3.1", + "yargs": "^7.0.2" + } + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "requires": { + "is-buffer": "^1.1.5" + } + }, + "micromatch": { + "version": "2.3.11", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-2.3.11.tgz", + "integrity": "sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=", + "requires": { + "arr-diff": "^2.0.0", + "array-unique": "^0.2.1", + "braces": "^1.8.2", + "expand-brackets": "^0.1.4", + "extglob": "^0.3.1", + "filename-regex": "^2.0.0", + "is-extglob": "^1.0.0", + "is-glob": "^2.0.1", + "kind-of": "^3.0.2", + "normalize-path": "^2.0.1", + "object.omit": "^2.0.0", + "parse-glob": "^3.0.4", + "regex-cache": "^0.4.2" + } + } + } + }, + "jest-changed-files": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-20.0.3.tgz", + "integrity": "sha1-k5TVzGXEOEBhSb7xv01Sto4D4/g=" + }, + "jest-config": { + "version": "20.0.4", + "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-20.0.4.tgz", + "integrity": "sha1-43kwqyIXyRNgXv8T5712PsSPruo=", + "requires": { + "chalk": "^1.1.3", + "glob": "^7.1.1", + "jest-environment-jsdom": "^20.0.3", + "jest-environment-node": "^20.0.3", + "jest-jasmine2": "^20.0.4", + "jest-matcher-utils": "^20.0.3", + "jest-regex-util": "^20.0.3", + "jest-resolve": "^20.0.4", + "jest-validate": "^20.0.3", + "pretty-format": "^20.0.3" + } + }, + "jest-diff": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-20.0.3.tgz", + "integrity": "sha1-gfKI/Z5nXw+yPHXxwrGURf5YZhc=", + "requires": { + "chalk": "^1.1.3", + "diff": "^3.2.0", + "jest-matcher-utils": "^20.0.3", + "pretty-format": "^20.0.3" + } + }, + "jest-docblock": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-20.0.3.tgz", + "integrity": "sha1-F76phDQswz2DxQ++FUXqDvqkRxI=" + }, + "jest-environment-jsdom": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-20.0.3.tgz", + "integrity": "sha1-BIqKwS7iJfcZBBdxODS7mZeH3pk=", + "requires": { + "jest-mock": "^20.0.3", + "jest-util": "^20.0.3", + "jsdom": "^9.12.0" + } + }, + "jest-environment-node": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-20.0.3.tgz", + "integrity": "sha1-1Ii8RhKvLCRumG6K52caCZFj1AM=", + "requires": { + "jest-mock": "^20.0.3", + "jest-util": "^20.0.3" + } + }, + "jest-haste-map": { + "version": "20.0.5", + "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-20.0.5.tgz", + "integrity": "sha512-0IKAQjUvuZjMCNi/0VNQQF74/H9KB67hsHJqGiwTWQC6XO5Azs7kLWm+6Q/dwuhvDUvABDOBMFK2/FwZ3sZ07Q==", + "requires": { + "fb-watchman": "^2.0.0", + "graceful-fs": "^4.1.11", + "jest-docblock": "^20.0.3", + "micromatch": "^2.3.11", + "sane": "~1.6.0", + "worker-farm": "^1.3.1" + }, + "dependencies": { + "arr-diff": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-2.0.0.tgz", + "integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=", + "requires": { + "arr-flatten": "^1.0.1" + } + }, + "array-unique": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.2.1.tgz", + "integrity": "sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=" + }, + "braces": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/braces/-/braces-1.8.5.tgz", + "integrity": "sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=", + "requires": { + "expand-range": "^1.8.1", + "preserve": "^0.2.0", + "repeat-element": "^1.1.2" + } + }, + "expand-brackets": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-0.1.5.tgz", + "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=", + "requires": { + "is-posix-bracket": "^0.1.0" + } + }, + "extglob": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-0.3.2.tgz", + "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=", + "requires": { + "is-extglob": "^1.0.0" + } + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "requires": { + "is-buffer": "^1.1.5" + } + }, + "micromatch": { + "version": "2.3.11", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-2.3.11.tgz", + "integrity": "sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=", + "requires": { + "arr-diff": "^2.0.0", + "array-unique": "^0.2.1", + "braces": "^1.8.2", + "expand-brackets": "^0.1.4", + "extglob": "^0.3.1", + "filename-regex": "^2.0.0", + "is-extglob": "^1.0.0", + "is-glob": "^2.0.1", + "kind-of": "^3.0.2", + "normalize-path": "^2.0.1", + "object.omit": "^2.0.0", + "parse-glob": "^3.0.4", + "regex-cache": "^0.4.2" + } + } + } + }, + "jest-jasmine2": { + "version": "20.0.4", + "resolved": "https://registry.npmjs.org/jest-jasmine2/-/jest-jasmine2-20.0.4.tgz", + "integrity": "sha1-/MWxQReA2RHQQpAu8YWehS5g1eE=", + "requires": { + "chalk": "^1.1.3", + "graceful-fs": "^4.1.11", + "jest-diff": "^20.0.3", + "jest-matcher-utils": "^20.0.3", + "jest-matchers": "^20.0.3", + "jest-message-util": "^20.0.3", + "jest-snapshot": "^20.0.3", + "once": "^1.4.0", + "p-map": "^1.1.1" + } + }, + "jest-matcher-utils": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-20.0.3.tgz", + "integrity": "sha1-s6a443yld4A7CDKpixZPRLeBVhI=", + "requires": { + "chalk": "^1.1.3", + "pretty-format": "^20.0.3" + } + }, + "jest-matchers": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/jest-matchers/-/jest-matchers-20.0.3.tgz", + "integrity": "sha1-ymnbHDLbWm9wf6XgQBq7VXAN/WA=", + "requires": { + "jest-diff": "^20.0.3", + "jest-matcher-utils": "^20.0.3", + "jest-message-util": "^20.0.3", + "jest-regex-util": "^20.0.3" + } + }, + "jest-message-util": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-20.0.3.tgz", + "integrity": "sha1-auwoRDBvyw5udNV5bBAG2W/dgxw=", + "requires": { + "chalk": "^1.1.3", + "micromatch": "^2.3.11", + "slash": "^1.0.0" + }, + "dependencies": { + "arr-diff": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-2.0.0.tgz", + "integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=", + "requires": { + "arr-flatten": "^1.0.1" + } + }, + "array-unique": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.2.1.tgz", + "integrity": "sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=" + }, + "braces": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/braces/-/braces-1.8.5.tgz", + "integrity": "sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=", + "requires": { + "expand-range": "^1.8.1", + "preserve": "^0.2.0", + "repeat-element": "^1.1.2" + } + }, + "expand-brackets": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-0.1.5.tgz", + "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=", + "requires": { + "is-posix-bracket": "^0.1.0" + } + }, + "extglob": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-0.3.2.tgz", + "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=", + "requires": { + "is-extglob": "^1.0.0" + } + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "requires": { + "is-buffer": "^1.1.5" + } + }, + "micromatch": { + "version": "2.3.11", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-2.3.11.tgz", + "integrity": "sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=", + "requires": { + "arr-diff": "^2.0.0", + "array-unique": "^0.2.1", + "braces": "^1.8.2", + "expand-brackets": "^0.1.4", + "extglob": "^0.3.1", + "filename-regex": "^2.0.0", + "is-extglob": "^1.0.0", + "is-glob": "^2.0.1", + "kind-of": "^3.0.2", + "normalize-path": "^2.0.1", + "object.omit": "^2.0.0", + "parse-glob": "^3.0.4", + "regex-cache": "^0.4.2" + } + } + } + }, + "jest-mock": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-20.0.3.tgz", + "integrity": "sha1-i8Bw6QQUqhVcEajWTIaaDVxx2lk=" + }, + "jest-regex-util": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-20.0.3.tgz", + "integrity": "sha1-hburXRM+RGJbGfr4xqpRItCF12I=" + }, + "jest-resolve": { + "version": "20.0.4", + "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-20.0.4.tgz", + "integrity": "sha1-lEiz6La6/BVHlETGSZBFt//ll6U=", + "requires": { + "browser-resolve": "^1.11.2", + "is-builtin-module": "^1.0.0", + "resolve": "^1.3.2" + } + }, + "jest-resolve-dependencies": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-20.0.3.tgz", + "integrity": "sha1-bhSntxevDyyzZnxUneQK8Bexcjo=", + "requires": { + "jest-regex-util": "^20.0.3" + } + }, + "jest-runtime": { + "version": "20.0.4", + "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-20.0.4.tgz", + "integrity": "sha1-osgCIZxCA/dU3xQE5JAYYWnRJNg=", + "requires": { + "babel-core": "^6.0.0", + "babel-jest": "^20.0.3", + "babel-plugin-istanbul": "^4.0.0", + "chalk": "^1.1.3", + "convert-source-map": "^1.4.0", + "graceful-fs": "^4.1.11", + "jest-config": "^20.0.4", + "jest-haste-map": "^20.0.4", + "jest-regex-util": "^20.0.3", + "jest-resolve": "^20.0.4", + "jest-util": "^20.0.3", + "json-stable-stringify": "^1.0.1", + "micromatch": "^2.3.11", + "strip-bom": "3.0.0", + "yargs": "^7.0.2" + }, + "dependencies": { + "arr-diff": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-2.0.0.tgz", + "integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=", + "requires": { + "arr-flatten": "^1.0.1" + } + }, + "array-unique": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.2.1.tgz", + "integrity": "sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=" + }, + "braces": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/braces/-/braces-1.8.5.tgz", + "integrity": "sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=", + "requires": { + "expand-range": "^1.8.1", + "preserve": "^0.2.0", + "repeat-element": "^1.1.2" + } + }, + "expand-brackets": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-0.1.5.tgz", + "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=", + "requires": { + "is-posix-bracket": "^0.1.0" + } + }, + "extglob": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-0.3.2.tgz", + "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=", + "requires": { + "is-extglob": "^1.0.0" + } + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "requires": { + "is-buffer": "^1.1.5" + } + }, + "micromatch": { + "version": "2.3.11", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-2.3.11.tgz", + "integrity": "sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=", + "requires": { + "arr-diff": "^2.0.0", + "array-unique": "^0.2.1", + "braces": "^1.8.2", + "expand-brackets": "^0.1.4", + "extglob": "^0.3.1", + "filename-regex": "^2.0.0", + "is-extglob": "^1.0.0", + "is-glob": "^2.0.1", + "kind-of": "^3.0.2", + "normalize-path": "^2.0.1", + "object.omit": "^2.0.0", + "parse-glob": "^3.0.4", + "regex-cache": "^0.4.2" + } + }, + "strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=" + } + } + }, + "jest-snapshot": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-20.0.3.tgz", + "integrity": "sha1-W4R+GtsaTZCFKn+fElCG4YfHZWY=", + "requires": { + "chalk": "^1.1.3", + "jest-diff": "^20.0.3", + "jest-matcher-utils": "^20.0.3", + "jest-util": "^20.0.3", + "natural-compare": "^1.4.0", + "pretty-format": "^20.0.3" + } + }, + "jest-util": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-20.0.3.tgz", + "integrity": "sha1-DAf32A2C9OWmfG+LnD/n9lz9Mq0=", + "requires": { + "chalk": "^1.1.3", + "graceful-fs": "^4.1.11", + "jest-message-util": "^20.0.3", + "jest-mock": "^20.0.3", + "jest-validate": "^20.0.3", + "leven": "^2.1.0", + "mkdirp": "^0.5.1" + } + }, + "jest-validate": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-20.0.3.tgz", + "integrity": "sha1-0M/R3k9XnymEhJJcKA+PHZTsPKs=", + "requires": { + "chalk": "^1.1.3", + "jest-matcher-utils": "^20.0.3", + "leven": "^2.1.0", + "pretty-format": "^20.0.3" + } + }, + "js-base64": { + "version": "2.4.5", + "resolved": "https://registry.npmjs.org/js-base64/-/js-base64-2.4.5.tgz", + "integrity": "sha512-aUnNwqMOXw3yvErjMPSQu6qIIzUmT1e5KcU1OZxRDU1g/am6mzBvcrmLAYwzmB59BHPrh5/tKaiF4OPhqRWESQ==" + }, + "js-tokens": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", + "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" + }, + "js-yaml": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.7.0.tgz", + "integrity": "sha1-XJZ93YN6m/3KXy3oQlOr6KHAO4A=", + "requires": { + "argparse": "^1.0.7", + "esprima": "^2.6.0" + } + }, + "jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", + "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=", + "optional": true + }, + "jsdom": { + "version": "9.12.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-9.12.0.tgz", + "integrity": "sha1-6MVG//ywbADUgzyoRBD+1/igl9Q=", + "requires": { + "abab": "^1.0.3", + "acorn": "^4.0.4", + "acorn-globals": "^3.1.0", + "array-equal": "^1.0.0", + "content-type-parser": "^1.0.1", + "cssom": ">= 0.3.2 < 0.4.0", + "cssstyle": ">= 0.2.37 < 0.3.0", + "escodegen": "^1.6.1", + "html-encoding-sniffer": "^1.0.1", + "nwmatcher": ">= 1.3.9 < 2.0.0", + "parse5": "^1.5.1", + "request": "^2.79.0", + "sax": "^1.2.1", + "symbol-tree": "^3.2.1", + "tough-cookie": "^2.3.2", + "webidl-conversions": "^4.0.0", + "whatwg-encoding": "^1.0.1", + "whatwg-url": "^4.3.0", + "xml-name-validator": "^2.0.1" + }, + "dependencies": { + "acorn": { + "version": "4.0.13", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-4.0.13.tgz", + "integrity": "sha1-EFSVrlNh1pe9GVyCUZLhrX8lN4c=" + } + } + }, + "jsesc": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-1.3.0.tgz", + "integrity": "sha1-RsP+yMGJKxKwgz25vHYiF226s0s=" + }, + "json-loader": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/json-loader/-/json-loader-0.5.7.tgz", + "integrity": "sha512-QLPs8Dj7lnf3e3QYS1zkCo+4ZwqOiF9d/nZnYozTISxXWCfNs9yuky5rJw4/W34s7POaNlbZmQGaB5NiXCbP4w==" + }, + "json-schema": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", + "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=" + }, + "json-schema-traverse": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz", + "integrity": "sha1-NJptRMU6Ud6JtAgFxdXlm0F9M0A=" + }, + "json-stable-stringify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify/-/json-stable-stringify-1.0.1.tgz", + "integrity": "sha1-mnWdOcXy/1A/1TAGRu1EX4jE+a8=", + "requires": { + "jsonify": "~0.0.0" + } + }, + "json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=" + }, + "json5": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-0.5.1.tgz", + "integrity": "sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE=" + }, + "jsonfile": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-3.0.1.tgz", + "integrity": "sha1-pezG9l9T9mLEQVx2daAzHQmS7GY=", + "requires": { + "graceful-fs": "^4.1.6" + } + }, + "jsonify": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/jsonify/-/jsonify-0.0.0.tgz", + "integrity": "sha1-LHS27kHZPKUbe1qu6PUDYx0lKnM=" + }, + "jsprim": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", + "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", + "requires": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.2.3", + "verror": "1.10.0" + } + }, + "jsx-ast-utils": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-1.4.1.tgz", + "integrity": "sha1-OGchPo3Xm/Ho8jAMDPwe+xgsDfE=" + }, + "kind-of": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==" + }, + "klaw": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/klaw/-/klaw-1.3.1.tgz", + "integrity": "sha1-QIhDO0azsbolnXh4XY6W9zugJDk=", + "requires": { + "graceful-fs": "^4.1.9" + } + }, + "latest-version": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/latest-version/-/latest-version-3.1.0.tgz", + "integrity": "sha1-ogU4P+oyKzO1rjsYq+4NwvNW7hU=", + "requires": { + "package-json": "^4.0.0" + } + }, + "lazy-cache": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/lazy-cache/-/lazy-cache-1.0.4.tgz", + "integrity": "sha1-odePw6UEdMuAhF07O24dpJpEbo4=" + }, + "lcid": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/lcid/-/lcid-1.0.0.tgz", + "integrity": "sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU=", + "requires": { + "invert-kv": "^1.0.0" + } + }, + "leven": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/leven/-/leven-2.1.0.tgz", + "integrity": "sha1-wuep93IJTe6dNCAq6KzORoeHVYA=" + }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "requires": { + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" + } + }, + "load-json-file": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", + "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", + "requires": { + "graceful-fs": "^4.1.2", + "parse-json": "^2.2.0", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0", + "strip-bom": "^2.0.0" + } + }, + "loader-fs-cache": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/loader-fs-cache/-/loader-fs-cache-1.0.1.tgz", + "integrity": "sha1-VuC/CL2XCLJqdltoUJhAyN7J/bw=", + "requires": { + "find-cache-dir": "^0.1.1", + "mkdirp": "0.5.1" + }, + "dependencies": { + "find-cache-dir": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-0.1.1.tgz", + "integrity": "sha1-yN765XyKUqinhPnjHFfHQumToLk=", + "requires": { + "commondir": "^1.0.1", + "mkdirp": "^0.5.1", + "pkg-dir": "^1.0.0" + } + }, + "find-up": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz", + "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", + "requires": { + "path-exists": "^2.0.0", + "pinkie-promise": "^2.0.0" + } + }, + "path-exists": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz", + "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", + "requires": { + "pinkie-promise": "^2.0.0" + } + }, + "pkg-dir": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-1.0.0.tgz", + "integrity": "sha1-ektQio1bstYp1EcFb/TpyTFM89Q=", + "requires": { + "find-up": "^1.0.0" + } + } + } + }, + "loader-runner": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-2.3.0.tgz", + "integrity": "sha1-9IKuqC1UPgeSFwDVpG7yb9rGuKI=" + }, + "loader-utils": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.1.0.tgz", + "integrity": "sha1-yYrvSIvM7aL/teLeZG1qdUQp9c0=", + "requires": { + "big.js": "^3.1.3", + "emojis-list": "^2.0.0", + "json5": "^0.5.0" + } + }, + "locate-path": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", + "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", + "requires": { + "p-locate": "^2.0.0", + "path-exists": "^3.0.0" + } + }, + "lodash": { + "version": "4.17.10", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.10.tgz", + "integrity": "sha512-UejweD1pDoXu+AD825lWwp4ZGtSwgnpZxb3JDViD7StjQz+Nb/6l093lx4OQ0foGWNRoc19mWy7BzL+UAK2iVg==" + }, + "lodash._reinterpolate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/lodash._reinterpolate/-/lodash._reinterpolate-3.0.0.tgz", + "integrity": "sha1-DM8tiRZq8Ds2Y8eWU4t1rG4RTZ0=" + }, + "lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha1-soqmKIorn8ZRA1x3EfZathkDMaY=" + }, + "lodash.cond": { + "version": "4.5.2", + "resolved": "https://registry.npmjs.org/lodash.cond/-/lodash.cond-4.5.2.tgz", + "integrity": "sha1-9HGh2khr5g9quVXRcRVSPdHSVdU=" + }, + "lodash.debounce": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", + "integrity": "sha1-gteb/zCmfEAF/9XiUVMArZyk168=" + }, + "lodash.defaults": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", + "integrity": "sha1-0JF4cW/+pN3p5ft7N/bwgCJ0WAw=" + }, + "lodash.memoize": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", + "integrity": "sha1-vMbEmkKihA7Zl/Mj6tpezRguC/4=" + }, + "lodash.template": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/lodash.template/-/lodash.template-4.4.0.tgz", + "integrity": "sha1-5zoDhcg1VZF0bgILmWecaQ5o+6A=", + "requires": { + "lodash._reinterpolate": "~3.0.0", + "lodash.templatesettings": "^4.0.0" + } + }, + "lodash.templatesettings": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/lodash.templatesettings/-/lodash.templatesettings-4.1.0.tgz", + "integrity": "sha1-K01OlbpEDZFf8IvImeRVNmZxMxY=", + "requires": { + "lodash._reinterpolate": "~3.0.0" + } + }, + "lodash.uniq": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.uniq/-/lodash.uniq-4.5.0.tgz", + "integrity": "sha1-0CJTc662Uq3BvILklFM5qEJ1R3M=" + }, + "longest": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/longest/-/longest-1.0.1.tgz", + "integrity": "sha1-MKCy2jj3N3DoKUoNIuZiXtd9AJc=" + }, + "loose-envify": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.3.1.tgz", + "integrity": "sha1-0aitM/qc4OcT1l/dCsi3SNR4yEg=", + "requires": { + "js-tokens": "^3.0.0" + } + }, + "loud-rejection": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/loud-rejection/-/loud-rejection-1.6.0.tgz", + "integrity": "sha1-W0b4AUft7leIcPCG0Eghz5mOVR8=", + "requires": { + "currently-unhandled": "^0.4.1", + "signal-exit": "^3.0.0" + } + }, + "lower-case": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/lower-case/-/lower-case-1.1.4.tgz", + "integrity": "sha1-miyr0bno4K6ZOkv31YdcOcQujqw=" + }, + "lowercase-keys": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-1.0.1.tgz", + "integrity": "sha512-G2Lj61tXDnVFFOi8VZds+SoQjtQC3dgokKdDG2mTm1tx4m50NUHBOZSBwQQHyy0V12A0JTG4icfZQH+xPyh8VA==" + }, + "lru-cache": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.3.tgz", + "integrity": "sha512-fFEhvcgzuIoJVUF8fYr5KR0YqxD238zgObTps31YdADwPPAp82a4M8TrckkWyx7ekNlf9aBcVn81cFwwXngrJA==", + "requires": { + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" + } + }, + "make-dir": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.3.0.tgz", + "integrity": "sha512-2w31R7SJtieJJnQtGc7RVL2StM2vGYVfqUOvUDxH6bC6aJTxPxTF0GnIgCyu7tjockiUWAYQRbxa7vKn34s5sQ==", + "requires": { + "pify": "^3.0.0" + }, + "dependencies": { + "pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=" + } + } + }, + "makeerror": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.11.tgz", + "integrity": "sha1-4BpckQnyr3lmDk6LlYd5AYT1qWw=", + "requires": { + "tmpl": "1.0.x" + } + }, + "map-cache": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", + "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=" + }, + "map-obj": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz", + "integrity": "sha1-2TPOuSBdgr3PSIb2dCvcK03qFG0=" + }, + "map-visit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/map-visit/-/map-visit-1.0.0.tgz", + "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=", + "requires": { + "object-visit": "^1.0.0" + } + }, + "math-expression-evaluator": { + "version": "1.2.17", + "resolved": "https://registry.npmjs.org/math-expression-evaluator/-/math-expression-evaluator-1.2.17.tgz", + "integrity": "sha1-3oGf282E3M2PrlnGrreWFbnSZqw=" + }, + "math-random": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/math-random/-/math-random-1.0.1.tgz", + "integrity": "sha1-izqsWIuKZuSXXjzepn97sylgH6w=" + }, + "md5.js": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.4.tgz", + "integrity": "sha1-6b296UogpawYsENA/Fdk1bCdkB0=", + "requires": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1" + } + }, + "mem": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/mem/-/mem-1.1.0.tgz", + "integrity": "sha1-Xt1StIXKHZAP5kiVUFOZoN+kX3Y=", + "requires": { + "mimic-fn": "^1.0.0" + } + }, + "memory-fs": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/memory-fs/-/memory-fs-0.4.1.tgz", + "integrity": "sha1-OpoguEYlI+RHz7x+i7gO1me/xVI=", + "requires": { + "errno": "^0.1.3", + "readable-stream": "^2.0.1" + } + }, + "meow": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/meow/-/meow-3.7.0.tgz", + "integrity": "sha1-cstmi0JSKCkKu/qFaJJYcwioAfs=", + "requires": { + "camelcase-keys": "^2.0.0", + "decamelize": "^1.1.2", + "loud-rejection": "^1.0.0", + "map-obj": "^1.0.1", + "minimist": "^1.1.3", + "normalize-package-data": "^2.3.4", + "object-assign": "^4.0.1", + "read-pkg-up": "^1.0.1", + "redent": "^1.0.0", + "trim-newlines": "^1.0.0" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=" + } + } + }, + "merge": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/merge/-/merge-1.2.0.tgz", + "integrity": "sha1-dTHjnUlJwoGma4xabgJl6LBYlNo=" + }, + "micromatch": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz", + "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==", + "requires": { + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "braces": "^2.3.1", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "extglob": "^2.0.4", + "fragment-cache": "^0.2.1", + "kind-of": "^6.0.2", + "nanomatch": "^1.2.9", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.2" + } + }, + "miller-rabin": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/miller-rabin/-/miller-rabin-4.0.1.tgz", + "integrity": "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA==", + "requires": { + "bn.js": "^4.0.0", + "brorand": "^1.0.1" + } + }, + "mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==" + }, + "mime-db": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.33.0.tgz", + "integrity": "sha512-BHJ/EKruNIqJf/QahvxwQZXKygOQ256myeN/Ew+THcAa5q+PjyTTMMeNQC4DZw5AwfvelsUrA6B67NKMqXDbzQ==" + }, + "mime-types": { + "version": "2.1.18", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.18.tgz", + "integrity": "sha512-lc/aahn+t4/SWV/qcmumYjymLsWfN3ELhpmVuUFjgsORruuZPVSwAQryq+HHGvO/SI2KVX26bx+En+zhM8g8hQ==", + "requires": { + "mime-db": "~1.33.0" + } + }, + "mimic-fn": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz", + "integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==" + }, + "minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==" + }, + "minimalistic-crypto-utils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz", + "integrity": "sha1-9sAMHAsIIkblxNmd+4x8CDsrWCo=" + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=" + }, + "mixin-deep": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.1.tgz", + "integrity": "sha512-8ZItLHeEgaqEvd5lYBXfm4EZSFCX29Jb9K+lAHhDKzReKBQKj3R+7NOF6tjqYi9t4oI8VUfaWITJQm86wnXGNQ==", + "requires": { + "for-in": "^1.0.2", + "is-extendable": "^1.0.1" + }, + "dependencies": { + "is-extendable": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", + "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", + "requires": { + "is-plain-object": "^2.0.4" + } + } + } + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "requires": { + "minimist": "0.0.8" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + }, + "mute-stream": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.7.tgz", + "integrity": "sha1-MHXOk7whuPq0PhvE2n6BFe0ee6s=" + }, + "nan": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.10.0.tgz", + "integrity": "sha512-bAdJv7fBLhWC+/Bls0Oza+mvTaNQtP+1RyhhhvD95pgUJz6XM5IzgmxOkItJ9tkoCiplvAnXI1tNmmUD/eScyA==", + "optional": true + }, + "nanomatch": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz", + "integrity": "sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA==", + "requires": { + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "fragment-cache": "^0.2.1", + "is-windows": "^1.0.2", + "kind-of": "^6.0.2", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + } + }, + "natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=" + }, + "neo-async": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.5.1.tgz", + "integrity": "sha512-3KL3fvuRkZ7s4IFOMfztb7zJp3QaVWnBeGoJlgB38XnCRPj/0tLzzLG5IB8NYOHbJ8g8UGrgZv44GLDk6CxTxA==" + }, + "next-tick": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.0.0.tgz", + "integrity": "sha1-yobR/ogoFpsBICCOPchCS524NCw=" + }, + "no-case": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/no-case/-/no-case-2.3.2.tgz", + "integrity": "sha512-rmTZ9kz+f3rCvK2TD1Ue/oZlns7OGoIWP4fc3llxxRXlOkHKoWPPWJOfFYpITabSow43QJbRIoHQXtt10VldyQ==", + "requires": { + "lower-case": "^1.1.1" + } + }, + "node-fetch": { + "version": "1.7.3", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-1.7.3.tgz", + "integrity": "sha512-NhZ4CsKx7cYm2vSrBAr2PvFOe6sWDf0UYLRqA6svUYg7+/TSfVAu49jYC4BvQ4Sms9SZgdqGBgroqfDhJdTyKQ==", + "requires": { + "encoding": "^0.1.11", + "is-stream": "^1.0.1" + } + }, + "node-int64": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", + "integrity": "sha1-h6kGXNs1XTGC2PlM4RGIuCXGijs=" + }, + "node-libs-browser": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/node-libs-browser/-/node-libs-browser-2.1.0.tgz", + "integrity": "sha512-5AzFzdoIMb89hBGMZglEegffzgRg+ZFoUmisQ8HI4j1KDdpx13J0taNp2y9xPbur6W61gepGDDotGBVQ7mfUCg==", + "requires": { + "assert": "^1.1.1", + "browserify-zlib": "^0.2.0", + "buffer": "^4.3.0", + "console-browserify": "^1.1.0", + "constants-browserify": "^1.0.0", + "crypto-browserify": "^3.11.0", + "domain-browser": "^1.1.1", + "events": "^1.0.0", + "https-browserify": "^1.0.0", + "os-browserify": "^0.3.0", + "path-browserify": "0.0.0", + "process": "^0.11.10", + "punycode": "^1.2.4", + "querystring-es3": "^0.2.0", + "readable-stream": "^2.3.3", + "stream-browserify": "^2.0.1", + "stream-http": "^2.7.2", + "string_decoder": "^1.0.0", + "timers-browserify": "^2.0.4", + "tty-browserify": "0.0.0", + "url": "^0.11.0", + "util": "^0.10.3", + "vm-browserify": "0.0.4" + }, + "dependencies": { + "punycode": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", + "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=" + } + } + }, + "node-notifier": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/node-notifier/-/node-notifier-5.2.1.tgz", + "integrity": "sha512-MIBs+AAd6dJ2SklbbE8RUDRlIVhU8MaNLh1A9SUZDUHPiZkWLFde6UNwG41yQHZEToHgJMXqyVZ9UcS/ReOVTg==", + "requires": { + "growly": "^1.3.0", + "semver": "^5.4.1", + "shellwords": "^0.1.1", + "which": "^1.3.0" + } + }, + "normalize-package-data": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.4.0.tgz", + "integrity": "sha512-9jjUFbTPfEy3R/ad/2oNbKtW9Hgovl5O1FvFWKkKblNXoN/Oou6+9+KKohPK13Yc3/TyunyWhJp6gvRNR/PPAw==", + "requires": { + "hosted-git-info": "^2.1.4", + "is-builtin-module": "^1.0.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" + } + }, + "normalize-path": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz", + "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", + "requires": { + "remove-trailing-separator": "^1.0.1" + } + }, + "normalize-range": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/normalize-range/-/normalize-range-0.1.2.tgz", + "integrity": "sha1-LRDAa9/TEuqXd2laTShDlFa3WUI=" + }, + "normalize-url": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-1.9.1.tgz", + "integrity": "sha1-LMDWazHqIwNkWENuNiDYWVTGbDw=", + "requires": { + "object-assign": "^4.0.1", + "prepend-http": "^1.0.0", + "query-string": "^4.1.0", + "sort-keys": "^1.0.0" + } + }, + "npm-run-path": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz", + "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", + "requires": { + "path-key": "^2.0.0" + } + }, + "nth-check": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-1.0.1.tgz", + "integrity": "sha1-mSms32KPwsQQmN6rgqxYDPFJquQ=", + "requires": { + "boolbase": "~1.0.0" + } + }, + "num2fraction": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/num2fraction/-/num2fraction-1.2.2.tgz", + "integrity": "sha1-b2gragJ6Tp3fpFZM0lidHU5mnt4=" + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=" + }, + "nwmatcher": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/nwmatcher/-/nwmatcher-1.4.4.tgz", + "integrity": "sha512-3iuY4N5dhgMpCUrOVnuAdGrgxVqV2cJpM+XNccjR2DKOB1RUP0aA+wGXEiNziG/UKboFyGBIoKOaNlJxx8bciQ==" + }, + "oauth-sign": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.8.2.tgz", + "integrity": "sha1-Rqarfwrq2N6unsBWV4C31O/rnUM=" + }, + "object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=" + }, + "object-copy": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/object-copy/-/object-copy-0.1.0.tgz", + "integrity": "sha1-fn2Fi3gb18mRpBupde04EnVOmYw=", + "requires": { + "copy-descriptor": "^0.1.0", + "define-property": "^0.2.5", + "kind-of": "^3.0.3" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "object-hash": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-1.3.0.tgz", + "integrity": "sha512-05KzQ70lSeGSrZJQXE5wNDiTkBJDlUT/myi6RX9dVIvz7a7Qh4oH93BQdiPMn27nldYvVQCKMUaM83AfizZlsQ==" + }, + "object-keys": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.0.12.tgz", + "integrity": "sha512-FTMyFUm2wBcGHnH2eXmz7tC6IwlqQZ6mVZ+6dm6vZ4IQIHjs6FdNsQBuKGPuUUUY6NfJw2PshC08Tn6LzLDOag==" + }, + "object-visit": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/object-visit/-/object-visit-1.0.1.tgz", + "integrity": "sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=", + "requires": { + "isobject": "^3.0.0" + } + }, + "object.omit": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/object.omit/-/object.omit-2.0.1.tgz", + "integrity": "sha1-Gpx0SCnznbuFjHbKNXmuKlTr0fo=", + "requires": { + "for-own": "^0.1.4", + "is-extendable": "^0.1.1" + } + }, + "object.pick": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz", + "integrity": "sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=", + "requires": { + "isobject": "^3.0.1" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "requires": { + "wrappy": "1" + } + }, + "onetime": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-2.0.1.tgz", + "integrity": "sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ=", + "requires": { + "mimic-fn": "^1.0.0" + } + }, + "opn": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/opn/-/opn-5.2.0.tgz", + "integrity": "sha512-Jd/GpzPyHF4P2/aNOVmS3lfMSWV9J7cOhCG1s08XCEAsPkB7lp6ddiU0J7XzyQRDUh8BqJ7PchfINjR8jyofRQ==", + "requires": { + "is-wsl": "^1.1.0" + } + }, + "optimist": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/optimist/-/optimist-0.6.1.tgz", + "integrity": "sha1-2j6nRob6IaGaERwybpDrFaAZZoY=", + "requires": { + "minimist": "~0.0.1", + "wordwrap": "~0.0.2" + }, + "dependencies": { + "wordwrap": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.3.tgz", + "integrity": "sha1-o9XabNXAvAAI03I0u68b7WMFkQc=" + } + } + }, + "optionator": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", + "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", + "requires": { + "deep-is": "~0.1.3", + "fast-levenshtein": "~2.0.4", + "levn": "~0.3.0", + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2", + "wordwrap": "~1.0.0" + } + }, + "os-browserify": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/os-browserify/-/os-browserify-0.3.0.tgz", + "integrity": "sha1-hUNzx/XCMVkU/Jv8a9gjj92h7Cc=" + }, + "os-homedir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", + "integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M=" + }, + "os-locale": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-1.4.0.tgz", + "integrity": "sha1-IPnxeuKe00XoveWDsT0gCYA8FNk=", + "requires": { + "lcid": "^1.0.0" + } + }, + "os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=" + }, + "p-finally": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=" + }, + "p-limit": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", + "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", + "requires": { + "p-try": "^1.0.0" + } + }, + "p-locate": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", + "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", + "requires": { + "p-limit": "^1.1.0" + } + }, + "p-map": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-1.2.0.tgz", + "integrity": "sha512-r6zKACMNhjPJMTl8KcFH4li//gkrXWfbD6feV8l6doRHlzljFWGJ2AP6iKaCJXyZmAUMOPtvbW7EXkbWO/pLEA==" + }, + "p-try": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", + "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=" + }, + "package-json": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/package-json/-/package-json-4.0.1.tgz", + "integrity": "sha1-iGmgQBJTZhxMTKPabCEh7VVfXu0=", + "requires": { + "got": "^6.7.1", + "registry-auth-token": "^3.0.1", + "registry-url": "^3.0.3", + "semver": "^5.1.0" + } + }, + "pako": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.6.tgz", + "integrity": "sha512-lQe48YPsMJAig+yngZ87Lus+NF+3mtu7DVOBu6b/gHO1YpKwIj5AWjZ/TOS7i46HD/UixzWb1zeWDZfGZ3iYcg==" + }, + "param-case": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/param-case/-/param-case-2.1.1.tgz", + "integrity": "sha1-35T9jPZTHs915r75oIWPvHK+Ikc=", + "requires": { + "no-case": "^2.2.0" + } + }, + "parse-asn1": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.1.tgz", + "integrity": "sha512-KPx7flKXg775zZpnp9SxJlz00gTd4BmJ2yJufSc44gMCRrRQ7NSzAcSJQfifuOLgW6bEi+ftrALtsgALeB2Adw==", + "requires": { + "asn1.js": "^4.0.0", + "browserify-aes": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.0", + "pbkdf2": "^3.0.3" + } + }, + "parse-glob": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/parse-glob/-/parse-glob-3.0.4.tgz", + "integrity": "sha1-ssN2z7EfNVE7rdFz7wu246OIORw=", + "requires": { + "glob-base": "^0.3.0", + "is-dotfile": "^1.0.0", + "is-extglob": "^1.0.0", + "is-glob": "^2.0.0" + } + }, + "parse-json": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-2.2.0.tgz", + "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", + "requires": { + "error-ex": "^1.2.0" + } + }, + "parse-passwd": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/parse-passwd/-/parse-passwd-1.0.0.tgz", + "integrity": "sha1-bVuTSkVpk7I9N/QKOC1vFmao5cY=" + }, + "parse5": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-1.5.1.tgz", + "integrity": "sha1-m387DeMr543CQBsXVzzK8Pb1nZQ=" + }, + "pascalcase": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/pascalcase/-/pascalcase-0.1.1.tgz", + "integrity": "sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=" + }, + "path-browserify": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-0.0.0.tgz", + "integrity": "sha1-oLhwcpquIUAFt9UDLsLLuw+0RRo=" + }, + "path-dirname": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/path-dirname/-/path-dirname-1.0.2.tgz", + "integrity": "sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA=" + }, + "path-exists": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=" + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" + }, + "path-is-inside": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/path-is-inside/-/path-is-inside-1.0.2.tgz", + "integrity": "sha1-NlQX3t5EQw0cEa9hAn+s8HS9/FM=" + }, + "path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=" + }, + "path-parse": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.5.tgz", + "integrity": "sha1-PBrfhx6pzWyUMbbqK9dKD/BVxME=" + }, + "path-to-regexp": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-1.7.0.tgz", + "integrity": "sha1-Wf3g9DW62suhA6hOnTvGTpa5k30=", + "requires": { + "isarray": "0.0.1" + }, + "dependencies": { + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=" + } + } + }, + "path-type": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-1.1.0.tgz", + "integrity": "sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE=", + "requires": { + "graceful-fs": "^4.1.2", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" + } + }, + "pbkdf2": { + "version": "3.0.16", + "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.0.16.tgz", + "integrity": "sha512-y4CXP3thSxqf7c0qmOF+9UeOTrifiVTIM+u7NWlq+PRsHbr7r7dpCmvzrZxa96JJUNi0Y5w9VqG5ZNeCVMoDcA==", + "requires": { + "create-hash": "^1.1.2", + "create-hmac": "^1.1.4", + "ripemd160": "^2.0.1", + "safe-buffer": "^5.0.1", + "sha.js": "^2.4.8" + } + }, + "performance-now": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", + "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=" + }, + "pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=" + }, + "pinkie": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", + "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=" + }, + "pinkie-promise": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", + "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", + "requires": { + "pinkie": "^2.0.0" + } + }, + "pkg-dir": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-2.0.0.tgz", + "integrity": "sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s=", + "requires": { + "find-up": "^2.1.0" + } + }, + "pluralize": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-7.0.0.tgz", + "integrity": "sha512-ARhBOdzS3e41FbkW/XWrTEtukqqLoK5+Z/4UeDaLuSW+39JPeFgs4gCGqsrJHVZX0fUrx//4OF0K1CUGwlIFow==" + }, + "posix-character-classes": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz", + "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=" + }, + "postcss": { + "version": "6.0.23", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-6.0.23.tgz", + "integrity": "sha512-soOk1h6J3VMTZtVeVpv15/Hpdl2cBLX3CAw4TAbkpTJiNPk9YP/zWcD1ND+xEtvyuuvKzbxliTOIyvkSeSJ6ag==", + "requires": { + "chalk": "^2.4.1", + "source-map": "^0.6.1", + "supports-color": "^5.4.0" + }, + "dependencies": { + "chalk": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", + "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + } + } + }, + "postcss-calc": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/postcss-calc/-/postcss-calc-5.3.1.tgz", + "integrity": "sha1-d7rnypKK2FcW4v2kLyYb98HWW14=", + "requires": { + "postcss": "^5.0.2", + "postcss-message-helpers": "^2.0.0", + "reduce-css-calc": "^1.2.6" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-colormin": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/postcss-colormin/-/postcss-colormin-2.2.2.tgz", + "integrity": "sha1-ZjFBfV8OkJo9fsJrJMio0eT5bks=", + "requires": { + "colormin": "^1.0.5", + "postcss": "^5.0.13", + "postcss-value-parser": "^3.2.3" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-convert-values": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/postcss-convert-values/-/postcss-convert-values-2.6.1.tgz", + "integrity": "sha1-u9hZPFwf0uPRwyK7kl3K6Nrk1i0=", + "requires": { + "postcss": "^5.0.11", + "postcss-value-parser": "^3.1.2" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-discard-comments": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/postcss-discard-comments/-/postcss-discard-comments-2.0.4.tgz", + "integrity": "sha1-vv6J+v1bPazlzM5Rt2uBUUvgDj0=", + "requires": { + "postcss": "^5.0.14" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-discard-duplicates": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/postcss-discard-duplicates/-/postcss-discard-duplicates-2.1.0.tgz", + "integrity": "sha1-uavye4isGIFYpesSq8riAmO5GTI=", + "requires": { + "postcss": "^5.0.4" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-discard-empty": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/postcss-discard-empty/-/postcss-discard-empty-2.1.0.tgz", + "integrity": "sha1-0rS9nVztXr2Nyt52QMfXzX9PkrU=", + "requires": { + "postcss": "^5.0.14" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-discard-overridden": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/postcss-discard-overridden/-/postcss-discard-overridden-0.1.1.tgz", + "integrity": "sha1-ix6vVU9ob7KIzYdMVWZ7CqNmjVg=", + "requires": { + "postcss": "^5.0.16" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-discard-unused": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/postcss-discard-unused/-/postcss-discard-unused-2.2.3.tgz", + "integrity": "sha1-vOMLLMWR/8Y0Mitfs0ZLbZNPRDM=", + "requires": { + "postcss": "^5.0.14", + "uniqs": "^2.0.0" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-filter-plugins": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/postcss-filter-plugins/-/postcss-filter-plugins-2.0.3.tgz", + "integrity": "sha512-T53GVFsdinJhgwm7rg1BzbeBRomOg9y5MBVhGcsV0CxurUdVj1UlPdKtn7aqYA/c/QVkzKMjq2bSV5dKG5+AwQ==", + "requires": { + "postcss": "^5.0.4" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-flexbugs-fixes": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/postcss-flexbugs-fixes/-/postcss-flexbugs-fixes-3.2.0.tgz", + "integrity": "sha512-0AuD9HG1Ey3/3nqPWu9yqf7rL0KCPu5VgjDsjf5mzEcuo9H/z8nco/fljKgjsOUrZypa95MI0kS4xBZeBzz2lw==", + "requires": { + "postcss": "^6.0.1" + } + }, + "postcss-load-config": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-1.2.0.tgz", + "integrity": "sha1-U56a/J3chiASHr+djDZz4M5Q0oo=", + "requires": { + "cosmiconfig": "^2.1.0", + "object-assign": "^4.1.0", + "postcss-load-options": "^1.2.0", + "postcss-load-plugins": "^2.3.0" + } + }, + "postcss-load-options": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postcss-load-options/-/postcss-load-options-1.2.0.tgz", + "integrity": "sha1-sJixVZ3awt8EvAuzdfmaXP4rbYw=", + "requires": { + "cosmiconfig": "^2.1.0", + "object-assign": "^4.1.0" + } + }, + "postcss-load-plugins": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/postcss-load-plugins/-/postcss-load-plugins-2.3.0.tgz", + "integrity": "sha1-dFdoEWWZrKLwCfrUJrABdQSdjZI=", + "requires": { + "cosmiconfig": "^2.1.1", + "object-assign": "^4.1.0" + } + }, + "postcss-loader": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/postcss-loader/-/postcss-loader-2.0.8.tgz", + "integrity": "sha512-KtXBiQ/r/WYW8LxTSJK7h8wLqvCMSub/BqmRnud/Mu8RzwflW9cmXxwsMwbn15TNv287Hcufdb3ZSs7xHKnG8Q==", + "requires": { + "loader-utils": "^1.1.0", + "postcss": "^6.0.0", + "postcss-load-config": "^1.2.0", + "schema-utils": "^0.3.0" + } + }, + "postcss-merge-idents": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/postcss-merge-idents/-/postcss-merge-idents-2.1.7.tgz", + "integrity": "sha1-TFUwMTwI4dWzu/PSu8dH4njuonA=", + "requires": { + "has": "^1.0.1", + "postcss": "^5.0.10", + "postcss-value-parser": "^3.1.1" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-merge-longhand": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/postcss-merge-longhand/-/postcss-merge-longhand-2.0.2.tgz", + "integrity": "sha1-I9kM0Sewp3mUkVMyc5A0oaTz1lg=", + "requires": { + "postcss": "^5.0.4" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-merge-rules": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/postcss-merge-rules/-/postcss-merge-rules-2.1.2.tgz", + "integrity": "sha1-0d9d+qexrMO+VT8OnhDofGG19yE=", + "requires": { + "browserslist": "^1.5.2", + "caniuse-api": "^1.5.2", + "postcss": "^5.0.4", + "postcss-selector-parser": "^2.2.2", + "vendors": "^1.0.0" + }, + "dependencies": { + "browserslist": { + "version": "1.7.7", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-1.7.7.tgz", + "integrity": "sha1-C9dnBCWL6CmyOYu1Dkti0aFmsLk=", + "requires": { + "caniuse-db": "^1.0.30000639", + "electron-to-chromium": "^1.2.7" + } + }, + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-message-helpers": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postcss-message-helpers/-/postcss-message-helpers-2.0.0.tgz", + "integrity": "sha1-pPL0+rbk/gAvCu0ABHjN9S+bpg4=" + }, + "postcss-minify-font-values": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/postcss-minify-font-values/-/postcss-minify-font-values-1.0.5.tgz", + "integrity": "sha1-S1jttWZB66fIR0qzUmyv17vey2k=", + "requires": { + "object-assign": "^4.0.1", + "postcss": "^5.0.4", + "postcss-value-parser": "^3.0.2" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-minify-gradients": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/postcss-minify-gradients/-/postcss-minify-gradients-1.0.5.tgz", + "integrity": "sha1-Xb2hE3NwP4PPtKPqOIHY11/15uE=", + "requires": { + "postcss": "^5.0.12", + "postcss-value-parser": "^3.3.0" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-minify-params": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/postcss-minify-params/-/postcss-minify-params-1.2.2.tgz", + "integrity": "sha1-rSzgcTc7lDs9kwo/pZo1jCjW8fM=", + "requires": { + "alphanum-sort": "^1.0.1", + "postcss": "^5.0.2", + "postcss-value-parser": "^3.0.2", + "uniqs": "^2.0.0" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-minify-selectors": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/postcss-minify-selectors/-/postcss-minify-selectors-2.1.1.tgz", + "integrity": "sha1-ssapjAByz5G5MtGkllCBFDEXNb8=", + "requires": { + "alphanum-sort": "^1.0.2", + "has": "^1.0.1", + "postcss": "^5.0.14", + "postcss-selector-parser": "^2.0.0" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-modules-extract-imports": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/postcss-modules-extract-imports/-/postcss-modules-extract-imports-1.1.0.tgz", + "integrity": "sha1-thTJcgvmgW6u41+zpfqh26agXds=", + "requires": { + "postcss": "^6.0.1" + } + }, + "postcss-modules-local-by-default": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postcss-modules-local-by-default/-/postcss-modules-local-by-default-1.2.0.tgz", + "integrity": "sha1-99gMOYxaOT+nlkRmvRlQCn1hwGk=", + "requires": { + "css-selector-tokenizer": "^0.7.0", + "postcss": "^6.0.1" + } + }, + "postcss-modules-scope": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/postcss-modules-scope/-/postcss-modules-scope-1.1.0.tgz", + "integrity": "sha1-1upkmUx5+XtipytCb75gVqGUu5A=", + "requires": { + "css-selector-tokenizer": "^0.7.0", + "postcss": "^6.0.1" + } + }, + "postcss-modules-values": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/postcss-modules-values/-/postcss-modules-values-1.3.0.tgz", + "integrity": "sha1-7P+p1+GSUYOJ9CrQ6D9yrsRW6iA=", + "requires": { + "icss-replace-symbols": "^1.1.0", + "postcss": "^6.0.1" + } + }, + "postcss-normalize-charset": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/postcss-normalize-charset/-/postcss-normalize-charset-1.1.1.tgz", + "integrity": "sha1-757nEhLX/nWceO0WL2HtYrXLk/E=", + "requires": { + "postcss": "^5.0.5" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-normalize-url": { + "version": "3.0.8", + "resolved": "https://registry.npmjs.org/postcss-normalize-url/-/postcss-normalize-url-3.0.8.tgz", + "integrity": "sha1-EI90s/L82viRov+j6kWSJ5/HgiI=", + "requires": { + "is-absolute-url": "^2.0.0", + "normalize-url": "^1.4.0", + "postcss": "^5.0.14", + "postcss-value-parser": "^3.2.3" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-ordered-values": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/postcss-ordered-values/-/postcss-ordered-values-2.2.3.tgz", + "integrity": "sha1-7sbCpntsQSqNsgQud/6NpD+VwR0=", + "requires": { + "postcss": "^5.0.4", + "postcss-value-parser": "^3.0.1" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-reduce-idents": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/postcss-reduce-idents/-/postcss-reduce-idents-2.4.0.tgz", + "integrity": "sha1-wsbSDMlYKE9qv75j92Cb9AkFmtM=", + "requires": { + "postcss": "^5.0.4", + "postcss-value-parser": "^3.0.2" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-reduce-initial": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/postcss-reduce-initial/-/postcss-reduce-initial-1.0.1.tgz", + "integrity": "sha1-aPgGlfBF0IJjqHmtJA343WT2ROo=", + "requires": { + "postcss": "^5.0.4" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-reduce-transforms": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/postcss-reduce-transforms/-/postcss-reduce-transforms-1.0.4.tgz", + "integrity": "sha1-/3b02CEkN7McKYpC0uFEQCV3GuE=", + "requires": { + "has": "^1.0.1", + "postcss": "^5.0.8", + "postcss-value-parser": "^3.0.1" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-selector-parser": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-2.2.3.tgz", + "integrity": "sha1-+UN3iGBsPJrO4W/+jYsWKX8nu5A=", + "requires": { + "flatten": "^1.0.2", + "indexes-of": "^1.0.1", + "uniq": "^1.0.1" + } + }, + "postcss-svgo": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/postcss-svgo/-/postcss-svgo-2.1.6.tgz", + "integrity": "sha1-tt8YqmE7Zm4TPwittSGcJoSsEI0=", + "requires": { + "is-svg": "^2.0.0", + "postcss": "^5.0.14", + "postcss-value-parser": "^3.2.3", + "svgo": "^0.7.0" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-unique-selectors": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/postcss-unique-selectors/-/postcss-unique-selectors-2.0.2.tgz", + "integrity": "sha1-mB1X0p3csz57Hf4f1DuGSfkzyh0=", + "requires": { + "alphanum-sort": "^1.0.1", + "postcss": "^5.0.4", + "uniqs": "^2.0.0" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "postcss-value-parser": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-3.3.0.tgz", + "integrity": "sha1-h/OPnxj3dKSrTIojL1xc6IcqnRU=" + }, + "postcss-zindex": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/postcss-zindex/-/postcss-zindex-2.2.0.tgz", + "integrity": "sha1-0hCd3AVbka9n/EyzsCWUZjnSryI=", + "requires": { + "has": "^1.0.1", + "postcss": "^5.0.4", + "uniqs": "^2.0.0" + }, + "dependencies": { + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=" + }, + "postcss": { + "version": "5.2.18", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.18.tgz", + "integrity": "sha512-zrUjRRe1bpXKsX1qAJNJjqZViErVuyEkMTRrwu4ud4sbTtIBRmtaYDrHmcGgmrbsW3MHfmtIf+vJumgQn+PrXg==", + "requires": { + "chalk": "^1.1.3", + "js-base64": "^2.1.9", + "source-map": "^0.5.6", + "supports-color": "^3.2.3" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "supports-color": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", + "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", + "requires": { + "has-flag": "^1.0.0" + } + } + } + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=" + }, + "prepend-http": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", + "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" + }, + "preserve": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/preserve/-/preserve-0.2.0.tgz", + "integrity": "sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks=" + }, + "pretty-bytes": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-4.0.2.tgz", + "integrity": "sha1-sr+C5zUNZcbDOqlaqlpPYyf2HNk=" + }, + "pretty-error": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/pretty-error/-/pretty-error-2.1.1.tgz", + "integrity": "sha1-X0+HyPkeWuPzuoerTPXgOxoX8aM=", + "requires": { + "renderkid": "^2.0.1", + "utila": "~0.4" + } + }, + "pretty-format": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-20.0.3.tgz", + "integrity": "sha1-Ag41ClYKH+GpjcO+tsz/s4beixQ=", + "requires": { + "ansi-regex": "^2.1.1", + "ansi-styles": "^3.0.0" + } + }, + "private": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/private/-/private-0.1.8.tgz", + "integrity": "sha512-VvivMrbvd2nKkiG38qjULzlc+4Vx4wm/whI9pQD35YrARNnhxeiRktSOhSukRLFNlzg6Br/cJPet5J/u19r/mg==" + }, + "process": { + "version": "0.11.10", + "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", + "integrity": "sha1-czIwDoQBYb2j5podHZGn1LwW8YI=" + }, + "process-nextick-args": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz", + "integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==" + }, + "progress": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.0.tgz", + "integrity": "sha1-ihvjZr+Pwj2yvSPxDG/pILQ4nR8=" + }, + "promise": { + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/promise/-/promise-7.3.1.tgz", + "integrity": "sha512-nolQXZ/4L+bP/UGlkfaIujX9BKxGwmQ9OT4mOt5yvy8iK1h3wqTEJCijzGANTCCl9nWjY41juyAn2K3Q1hLLTg==", + "requires": { + "asap": "~2.0.3" + } + }, + "prop-types": { + "version": "15.6.2", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.6.2.tgz", + "integrity": "sha512-3pboPvLiWD7dkI3qf3KbUe6hKFKa52w+AE0VCqECtf+QHAKgOL37tTaNCnuX1nAAQ4ZhyP+kYVKf8rLmJ/feDQ==", + "requires": { + "loose-envify": "^1.3.1", + "object-assign": "^4.1.1" + } + }, + "prr": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz", + "integrity": "sha1-0/wRS6BplaRexok/SEzrHXj19HY=" + }, + "pseudomap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", + "integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM=" + }, + "psl": { + "version": "1.1.28", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.1.28.tgz", + "integrity": "sha512-+AqO1Ae+N/4r7Rvchrdm432afjT9hqJRyBN3DQv9At0tPz4hIFSGKbq64fN9dVoCow4oggIIax5/iONx0r9hZw==" + }, + "public-encrypt": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/public-encrypt/-/public-encrypt-4.0.2.tgz", + "integrity": "sha512-4kJ5Esocg8X3h8YgJsKAuoesBgB7mqH3eowiDzMUPKiRDDE7E/BqqZD1hnTByIaAFiwAw246YEltSq7tdrOH0Q==", + "requires": { + "bn.js": "^4.1.0", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "parse-asn1": "^5.0.0", + "randombytes": "^2.0.1" + } + }, + "punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" + }, + "q": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/q/-/q-1.5.1.tgz", + "integrity": "sha1-fjL3W0E4EpHQRhHxvxQQmsAGUdc=" + }, + "qs": { + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz", + "integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==" + }, + "query-string": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/query-string/-/query-string-4.3.4.tgz", + "integrity": "sha1-u7aTucqRXCMlFbIosaArYJBD2+s=", + "requires": { + "object-assign": "^4.1.0", + "strict-uri-encode": "^1.0.0" + } + }, + "querystring": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz", + "integrity": "sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA=" + }, + "querystring-es3": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/querystring-es3/-/querystring-es3-0.2.1.tgz", + "integrity": "sha1-nsYfeQSYdXB9aUFFlv2Qek1xHnM=" + }, + "raf": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/raf/-/raf-3.4.0.tgz", + "integrity": "sha512-pDP/NMRAXoTfrhCfyfSEwJAKLaxBU9eApMeBPB1TkDouZmvPerIClV8lTAd+uF8ZiTaVl69e1FCxQrAd/VTjGw==", + "requires": { + "performance-now": "^2.1.0" + } + }, + "randomatic": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/randomatic/-/randomatic-3.0.0.tgz", + "integrity": "sha512-VdxFOIEY3mNO5PtSRkkle/hPJDHvQhK21oa73K4yAc9qmp6N429gAyF1gZMOTMeS0/AYzaV/2Trcef+NaIonSA==", + "requires": { + "is-number": "^4.0.0", + "kind-of": "^6.0.0", + "math-random": "^1.0.1" + }, + "dependencies": { + "is-number": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-4.0.0.tgz", + "integrity": "sha512-rSklcAIlf1OmFdyAqbnWTLVelsQ58uvZ66S/ZyawjWqIviTWCjg2PzVGw8WUA+nNuPTqb4wgA+NszrJ+08LlgQ==" + } + } + }, + "randombytes": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.0.6.tgz", + "integrity": "sha512-CIQ5OFxf4Jou6uOKe9t1AOgqpeU5fd70A8NPdHSGeYXqXsPe6peOwI0cUl88RWZ6sP1vPMV3avd/R6cZ5/sP1A==", + "requires": { + "safe-buffer": "^5.1.0" + } + }, + "randomfill": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/randomfill/-/randomfill-1.0.4.tgz", + "integrity": "sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw==", + "requires": { + "randombytes": "^2.0.5", + "safe-buffer": "^5.1.0" + } + }, + "rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "requires": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=" + } + } + }, + "react": { + "version": "16.4.1", + "resolved": "https://registry.npmjs.org/react/-/react-16.4.1.tgz", + "integrity": "sha512-3GEs0giKp6E0Oh/Y9ZC60CmYgUPnp7voH9fbjWsvXtYFb4EWtgQub0ADSq0sJR0BbHc4FThLLtzlcFaFXIorwg==", + "requires": { + "fbjs": "^0.8.16", + "loose-envify": "^1.1.0", + "object-assign": "^4.1.1", + "prop-types": "^15.6.0" + } + }, + "react-dev-utils": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/react-dev-utils/-/react-dev-utils-5.0.1.tgz", + "integrity": "sha512-+y92rG6pmXt3cpcg/NGmG4w/W309tWNSmyyPL8hCMxuCSg2UP/hUg3npACj2UZc8UKVSXexyLrCnxowizGoAsw==", + "requires": { + "address": "1.0.3", + "babel-code-frame": "6.26.0", + "chalk": "1.1.3", + "cross-spawn": "5.1.0", + "detect-port-alt": "1.1.6", + "escape-string-regexp": "1.0.5", + "filesize": "3.5.11", + "global-modules": "1.0.0", + "gzip-size": "3.0.0", + "inquirer": "3.3.0", + "is-root": "1.0.0", + "opn": "5.2.0", + "react-error-overlay": "^4.0.0", + "recursive-readdir": "2.2.1", + "shell-quote": "1.6.1", + "strip-ansi": "3.0.1", + "text-table": "0.2.0" + }, + "dependencies": { + "sockjs-client": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/sockjs-client/-/sockjs-client-1.1.5.tgz", + "integrity": "sha1-G7fA9yIsQPQq3xT0RCy9Eml3GoM=", + "requires": { + "debug": "^2.6.6", + "inherits": "^2.0.1" + } + } + } + }, + "react-dom": { + "version": "16.4.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-16.4.1.tgz", + "integrity": "sha512-1Gin+wghF/7gl4Cqcvr1DxFX2Osz7ugxSwl6gBqCMpdrxHjIFUS7GYxrFftZ9Ln44FHw0JxCFD9YtZsrbR5/4A==", + "requires": { + "fbjs": "^0.8.16", + "loose-envify": "^1.1.0", + "object-assign": "^4.1.1", + "prop-types": "^15.6.0" + } + }, + "react-error-overlay": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/react-error-overlay/-/react-error-overlay-4.0.0.tgz", + "integrity": "sha512-FlsPxavEyMuR6TjVbSSywovXSEyOg6ZDj5+Z8nbsRl9EkOzAhEIcS+GLoQDC5fz/t9suhUXWmUrOBrgeUvrMxw==" + }, + "react-scripts": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/react-scripts/-/react-scripts-1.1.4.tgz", + "integrity": "sha512-UVZIujEIT9BGbx+NGvyfS92eOrNIIpqqFi1FP7a0O9l94A/XV7bhPk70SfDKaXZouCX81tFdXo0948DjhCEgGw==", + "requires": { + "autoprefixer": "7.1.6", + "babel-core": "6.26.0", + "babel-eslint": "7.2.3", + "babel-jest": "20.0.3", + "babel-loader": "7.1.2", + "babel-preset-react-app": "^3.1.1", + "babel-runtime": "6.26.0", + "case-sensitive-paths-webpack-plugin": "2.1.1", + "chalk": "1.1.3", + "css-loader": "0.28.7", + "dotenv": "4.0.0", + "dotenv-expand": "4.2.0", + "eslint": "4.10.0", + "eslint-config-react-app": "^2.1.0", + "eslint-loader": "1.9.0", + "eslint-plugin-flowtype": "2.39.1", + "eslint-plugin-import": "2.8.0", + "eslint-plugin-jsx-a11y": "5.1.1", + "eslint-plugin-react": "7.4.0", + "extract-text-webpack-plugin": "3.0.2", + "file-loader": "1.1.5", + "fs-extra": "3.0.1", + "fsevents": "^1.1.3", + "html-webpack-plugin": "2.29.0", + "jest": "20.0.4", + "object-assign": "4.1.1", + "postcss-flexbugs-fixes": "3.2.0", + "postcss-loader": "2.0.8", + "promise": "8.0.1", + "raf": "3.4.0", + "react-dev-utils": "^5.0.1", + "resolve": "1.6.0", + "style-loader": "0.19.0", + "sw-precache-webpack-plugin": "0.11.4", + "url-loader": "0.6.2", + "webpack": "3.8.1", + "webpack-manifest-plugin": "1.3.2", + "whatwg-fetch": "2.0.3" + }, + "dependencies": { + "eslint-plugin-react": { + "version": "7.4.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.4.0.tgz", + "integrity": "sha512-tvjU9u3VqmW2vVuYnE8Qptq+6ji4JltjOjJ9u7VAOxVYkUkyBZWRvNYKbDv5fN+L6wiA+4we9+qQahZ0m63XEA==", + "requires": { + "doctrine": "^2.0.0", + "has": "^1.0.1", + "jsx-ast-utils": "^2.0.0", + "prop-types": "^15.5.10" + } + }, + "jsx-ast-utils": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-2.0.1.tgz", + "integrity": "sha1-6AGxs5mF4g//yHtA43SAgOLcrH8=", + "requires": { + "array-includes": "^3.0.3" + } + }, + "promise": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/promise/-/promise-8.0.1.tgz", + "integrity": "sha1-5F1osAoXZHttpxG/he1u1HII9FA=", + "requires": { + "asap": "~2.0.3" + } + }, + "webpack-dev-server": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-3.1.5.tgz", + "integrity": "sha512-LVHg+EPwZLHIlfvokSTgtJqO/vI5CQi89fASb5JEDtVMDjY0yuIEqPPdMiKaBJIB/Ab7v/UN/sYZ7WsZvntQKw==", + "requires": { + "array-includes": "^3.0.3", + "chokidar": "^2.0.0", + "opn": "^5.1.0", + "strip-ansi": "^3.0.0", + "supports-color": "^5.1.0" + } + }, + "whatwg-fetch": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-2.0.3.tgz", + "integrity": "sha1-nITsLc9oGH/wC8ZOEnS0QhduHIQ=" + } + } + }, + "read-pkg": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-1.1.0.tgz", + "integrity": "sha1-9f+qXs0pyzHAR0vKfXVra7KePyg=", + "requires": { + "load-json-file": "^1.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^1.0.0" + } + }, + "read-pkg-up": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-1.0.1.tgz", + "integrity": "sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI=", + "requires": { + "find-up": "^1.0.0", + "read-pkg": "^1.0.0" + }, + "dependencies": { + "find-up": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz", + "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", + "requires": { + "path-exists": "^2.0.0", + "pinkie-promise": "^2.0.0" + } + }, + "path-exists": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz", + "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", + "requires": { + "pinkie-promise": "^2.0.0" + } + } + } + }, + "readable-stream": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "readdirp": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-2.1.0.tgz", + "integrity": "sha1-TtCtBg3zBzMAxIRANz9y0cxkLXg=", + "requires": { + "graceful-fs": "^4.1.2", + "minimatch": "^3.0.2", + "readable-stream": "^2.0.2", + "set-immediate-shim": "^1.0.1" + } + }, + "recursive-readdir": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/recursive-readdir/-/recursive-readdir-2.2.1.tgz", + "integrity": "sha1-kO8jHQd4xc4JPJpI105cVCLROpk=", + "requires": { + "minimatch": "3.0.3" + }, + "dependencies": { + "minimatch": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.3.tgz", + "integrity": "sha1-Kk5AkLlrLbBqnX3wEFWmKnfJt3Q=", + "requires": { + "brace-expansion": "^1.0.0" + } + } + } + }, + "redent": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/redent/-/redent-1.0.0.tgz", + "integrity": "sha1-z5Fqsf1fHxbfsggi3W7H9zDCr94=", + "requires": { + "indent-string": "^2.1.0", + "strip-indent": "^1.0.1" + } + }, + "reduce-css-calc": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/reduce-css-calc/-/reduce-css-calc-1.3.0.tgz", + "integrity": "sha1-dHyRTgSWFKTJz7umKYca0dKSdxY=", + "requires": { + "balanced-match": "^0.4.2", + "math-expression-evaluator": "^1.2.14", + "reduce-function-call": "^1.0.1" + }, + "dependencies": { + "balanced-match": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-0.4.2.tgz", + "integrity": "sha1-yz8+PHMtwPAe5wtAPzAuYddwmDg=" + } + } + }, + "reduce-function-call": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/reduce-function-call/-/reduce-function-call-1.0.2.tgz", + "integrity": "sha1-WiAL+S4ON3UXUv5FsKszD9S2vpk=", + "requires": { + "balanced-match": "^0.4.2" + }, + "dependencies": { + "balanced-match": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-0.4.2.tgz", + "integrity": "sha1-yz8+PHMtwPAe5wtAPzAuYddwmDg=" + } + } + }, + "regenerate": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.4.0.tgz", + "integrity": "sha512-1G6jJVDWrt0rK99kBjvEtziZNCICAuvIPkSiUFIQxVP06RCVpq3dmDo2oi6ABpYaDYaTRr67BEhL8r1wgEZZKg==" + }, + "regenerator-runtime": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", + "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==" + }, + "regenerator-transform": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/regenerator-transform/-/regenerator-transform-0.10.1.tgz", + "integrity": "sha512-PJepbvDbuK1xgIgnau7Y90cwaAmO/LCLMI2mPvaXq2heGMR3aWW5/BQvYrhJ8jgmQjXewXvBjzfqKcVOmhjZ6Q==", + "requires": { + "babel-runtime": "^6.18.0", + "babel-types": "^6.19.0", + "private": "^0.1.6" + } + }, + "regex-cache": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/regex-cache/-/regex-cache-0.4.4.tgz", + "integrity": "sha512-nVIZwtCjkC9YgvWkpM55B5rBhBYRZhAaJbgcFYXXsHnbZ9UZI9nnVWYZpBlCqv9ho2eZryPnWrZGsOdPwVWXWQ==", + "requires": { + "is-equal-shallow": "^0.1.3" + } + }, + "regex-not": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/regex-not/-/regex-not-1.0.2.tgz", + "integrity": "sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A==", + "requires": { + "extend-shallow": "^3.0.2", + "safe-regex": "^1.1.0" + } + }, + "regexpu-core": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-2.0.0.tgz", + "integrity": "sha1-SdA4g3uNz4v6W5pCE5k45uoq4kA=", + "requires": { + "regenerate": "^1.2.1", + "regjsgen": "^0.2.0", + "regjsparser": "^0.1.4" + } + }, + "registry-auth-token": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", + "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "requires": { + "rc": "^1.1.6", + "safe-buffer": "^5.0.1" + } + }, + "registry-url": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/registry-url/-/registry-url-3.1.0.tgz", + "integrity": "sha1-PU74cPc93h138M+aOBQyRE4XSUI=", + "requires": { + "rc": "^1.0.1" + } + }, + "regjsgen": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/regjsgen/-/regjsgen-0.2.0.tgz", + "integrity": "sha1-bAFq3qxVT3WCP+N6wFuS1aTtsfc=" + }, + "regjsparser": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.1.5.tgz", + "integrity": "sha1-fuj4Tcb6eS0/0K4ijSS9lJ6tIFw=", + "requires": { + "jsesc": "~0.5.0" + }, + "dependencies": { + "jsesc": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz", + "integrity": "sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=" + } + } + }, + "relateurl": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/relateurl/-/relateurl-0.2.7.tgz", + "integrity": "sha1-VNvzd+UUQKypCkzSdGANP/LYiKk=" + }, + "remove-trailing-separator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz", + "integrity": "sha1-wkvOKig62tW8P1jg1IJJuSN52O8=" + }, + "renderkid": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/renderkid/-/renderkid-2.0.1.tgz", + "integrity": "sha1-iYyr/Ivt5Le5ETWj/9Mj5YwNsxk=", + "requires": { + "css-select": "^1.1.0", + "dom-converter": "~0.1", + "htmlparser2": "~3.3.0", + "strip-ansi": "^3.0.0", + "utila": "~0.3" + }, + "dependencies": { + "utila": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/utila/-/utila-0.3.3.tgz", + "integrity": "sha1-1+jn1+MJEHCSsF+NloiCTWM6QiY=" + } + } + }, + "repeat-element": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/repeat-element/-/repeat-element-1.1.2.tgz", + "integrity": "sha1-7wiaF40Ug7quTZPrmLT55OEdmQo=" + }, + "repeat-string": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=" + }, + "repeating": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", + "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", + "requires": { + "is-finite": "^1.0.0" + } + }, + "request": { + "version": "2.87.0", + "resolved": "https://registry.npmjs.org/request/-/request-2.87.0.tgz", + "integrity": "sha512-fcogkm7Az5bsS6Sl0sibkbhcKsnyon/jV1kF3ajGmF0c8HrttdKTPRT9hieOaQHA5HEq6r8OyWOo/o781C1tNw==", + "requires": { + "aws-sign2": "~0.7.0", + "aws4": "^1.6.0", + "caseless": "~0.12.0", + "combined-stream": "~1.0.5", + "extend": "~3.0.1", + "forever-agent": "~0.6.1", + "form-data": "~2.3.1", + "har-validator": "~5.0.3", + "http-signature": "~1.2.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.17", + "oauth-sign": "~0.8.2", + "performance-now": "^2.1.0", + "qs": "~6.5.1", + "safe-buffer": "^5.1.1", + "tough-cookie": "~2.3.3", + "tunnel-agent": "^0.6.0", + "uuid": "^3.1.0" + }, + "dependencies": { + "punycode": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", + "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=" + }, + "tough-cookie": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.3.4.tgz", + "integrity": "sha512-TZ6TTfI5NtZnuyy/Kecv+CnoROnyXn2DN97LontgQpCwsX2XyLYCC0ENhYkehSOwAp8rTQKc/NUIF7BkQ5rKLA==", + "requires": { + "punycode": "^1.4.1" + } + } + } + }, + "require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=" + }, + "require-from-string": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-1.2.1.tgz", + "integrity": "sha1-UpyczvJzgK3+yaL5ZbZJu+5jZBg=" + }, + "require-main-filename": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-1.0.1.tgz", + "integrity": "sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE=" + }, + "require-uncached": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/require-uncached/-/require-uncached-1.0.3.tgz", + "integrity": "sha1-Tg1W1slmL9MeQwEcS5WqSZVUIdM=", + "requires": { + "caller-path": "^0.1.0", + "resolve-from": "^1.0.0" + } + }, + "resolve": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.6.0.tgz", + "integrity": "sha512-mw7JQNu5ExIkcw4LPih0owX/TZXjD/ZUF/ZQ/pDnkw3ZKhDcZZw5klmBlj6gVMwjQ3Pz5Jgu7F3d0jcDVuEWdw==", + "requires": { + "path-parse": "^1.0.5" + } + }, + "resolve-dir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-1.0.1.tgz", + "integrity": "sha1-eaQGRMNivoLybv/nOcm7U4IEb0M=", + "requires": { + "expand-tilde": "^2.0.0", + "global-modules": "^1.0.0" + } + }, + "resolve-from": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-1.0.1.tgz", + "integrity": "sha1-Jsv+k10a7uq7Kbw/5a6wHpPUQiY=" + }, + "resolve-url": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz", + "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=" + }, + "restore-cursor": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-2.0.0.tgz", + "integrity": "sha1-n37ih/gv0ybU/RYpI9YhKe7g368=", + "requires": { + "onetime": "^2.0.0", + "signal-exit": "^3.0.2" + } + }, + "ret": { + "version": "0.1.15", + "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", + "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==" + }, + "right-align": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/right-align/-/right-align-0.1.3.tgz", + "integrity": "sha1-YTObci/mo1FWiSENJOFMlhSGE+8=", + "requires": { + "align-text": "^0.1.1" + } + }, + "rimraf": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.2.tgz", + "integrity": "sha512-lreewLK/BlghmxtfH36YYVg1i8IAce4TI7oao75I1g245+6BctqTVQiBP3YUJ9C6DQOXJmkYR9X9fCLtCOJc5w==", + "requires": { + "glob": "^7.0.5" + } + }, + "ripemd160": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.2.tgz", + "integrity": "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA==", + "requires": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1" + } + }, + "run-async": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.3.0.tgz", + "integrity": "sha1-A3GrSuC91yDUFm19/aZP96RFpsA=", + "requires": { + "is-promise": "^2.1.0" + } + }, + "rx-lite": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/rx-lite/-/rx-lite-4.0.8.tgz", + "integrity": "sha1-Cx4Rr4vESDbwSmQH6S2kJGe3lEQ=" + }, + "rx-lite-aggregates": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/rx-lite-aggregates/-/rx-lite-aggregates-4.0.8.tgz", + "integrity": "sha1-dTuHqJoRyVRnxKwWJsTvxOBcZ74=", + "requires": { + "rx-lite": "*" + } + }, + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, + "safe-regex": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", + "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", + "requires": { + "ret": "~0.1.10" + } + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "sane": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/sane/-/sane-1.6.0.tgz", + "integrity": "sha1-lhDEUjB6E10pwf3+JUcDQYDEZ3U=", + "requires": { + "anymatch": "^1.3.0", + "exec-sh": "^0.2.0", + "fb-watchman": "^1.8.0", + "minimatch": "^3.0.2", + "minimist": "^1.1.1", + "walker": "~1.0.5", + "watch": "~0.10.0" + }, + "dependencies": { + "bser": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bser/-/bser-1.0.2.tgz", + "integrity": "sha1-OBEWlwsqbe6lZG3RXdcnhES1YWk=", + "requires": { + "node-int64": "^0.4.0" + } + }, + "fb-watchman": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-1.9.2.tgz", + "integrity": "sha1-okz0eCf4LTj7Waaa1wt247auc4M=", + "requires": { + "bser": "1.0.2" + } + }, + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=" + } + } + }, + "sax": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", + "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==" + }, + "schema-utils": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-0.3.0.tgz", + "integrity": "sha1-9YdyIs4+kx7a4DnxfrNxbnE3+M8=", + "requires": { + "ajv": "^5.0.0" + } + }, + "semver": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.5.0.tgz", + "integrity": "sha512-4SJ3dm0WAwWy/NVeioZh5AntkdJoWKxHxcmyP622fOkgHa4z3R0TdBJICINyaSDE6uNwVc8gZr+ZinwZAH4xIA==" + }, + "semver-diff": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/semver-diff/-/semver-diff-2.1.0.tgz", + "integrity": "sha1-S7uEN8jTfksM8aaP1ybsbWRdbTY=", + "requires": { + "semver": "^5.0.3" + } + }, + "serviceworker-cache-polyfill": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/serviceworker-cache-polyfill/-/serviceworker-cache-polyfill-4.0.0.tgz", + "integrity": "sha1-3hnuc77yGrPAdAo3sz22JGS6ves=" + }, + "set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=" + }, + "set-immediate-shim": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/set-immediate-shim/-/set-immediate-shim-1.0.1.tgz", + "integrity": "sha1-SysbJ+uAip+NzEgaWOXlb1mfP2E=" + }, + "set-value": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.0.tgz", + "integrity": "sha512-hw0yxk9GT/Hr5yJEYnHNKYXkIA8mVJgd9ditYZCe16ZczcaELYYcfvaXesNACk2O8O0nTiPQcQhGUQj8JLzeeg==", + "requires": { + "extend-shallow": "^2.0.1", + "is-extendable": "^0.1.1", + "is-plain-object": "^2.0.3", + "split-string": "^3.0.1" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "setimmediate": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", + "integrity": "sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU=" + }, + "sha.js": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", + "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==", + "requires": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "requires": { + "shebang-regex": "^1.0.0" + } + }, + "shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=" + }, + "shell-quote": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.6.1.tgz", + "integrity": "sha1-9HgZSczkAmlxJ0MOo7PFR29IF2c=", + "requires": { + "array-filter": "~0.0.0", + "array-map": "~0.0.0", + "array-reduce": "~0.0.0", + "jsonify": "~0.0.0" + } + }, + "shellwords": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/shellwords/-/shellwords-0.1.1.tgz", + "integrity": "sha512-vFwSUfQvqybiICwZY5+DAWIPLKsWO31Q91JSKl3UYv+K5c2QRPzn0qzec6QPu1Qc9eHYItiP3NdJqNVqetYAww==" + }, + "signal-exit": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", + "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=" + }, + "slash": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-1.0.0.tgz", + "integrity": "sha1-xB8vbDn8FtHNF61LXYlhFK5HDVU=" + }, + "slice-ansi": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-1.0.0.tgz", + "integrity": "sha512-POqxBK6Lb3q6s047D/XsDVNPnF9Dl8JSaqe9h9lURl0OdNqy/ujDrOiIHtsqXMGbWWTIomRzAMaTyawAU//Reg==", + "requires": { + "is-fullwidth-code-point": "^2.0.0" + } + }, + "snapdragon": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz", + "integrity": "sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg==", + "requires": { + "base": "^0.11.1", + "debug": "^2.2.0", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "map-cache": "^0.2.2", + "source-map": "^0.5.6", + "source-map-resolve": "^0.5.0", + "use": "^3.1.0" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "requires": { + "is-extendable": "^0.1.0" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + } + } + }, + "snapdragon-node": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/snapdragon-node/-/snapdragon-node-2.1.1.tgz", + "integrity": "sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw==", + "requires": { + "define-property": "^1.0.0", + "isobject": "^3.0.0", + "snapdragon-util": "^3.0.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "snapdragon-util": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/snapdragon-util/-/snapdragon-util-3.0.1.tgz", + "integrity": "sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ==", + "requires": { + "kind-of": "^3.2.0" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "sort-keys": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/sort-keys/-/sort-keys-1.1.2.tgz", + "integrity": "sha1-RBttTTRnmPG05J6JIK37oOVD+a0=", + "requires": { + "is-plain-obj": "^1.0.0" + } + }, + "source-list-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/source-list-map/-/source-list-map-2.0.0.tgz", + "integrity": "sha512-I2UmuJSRr/T8jisiROLU3A3ltr+swpniSmNPI4Ml3ZCX6tVnDsuZzK7F2hl5jTqbZBWCEKlj5HRQiPExXLgE8A==" + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==" + }, + "source-map-resolve": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.2.tgz", + "integrity": "sha512-MjqsvNwyz1s0k81Goz/9vRBe9SZdB09Bdw+/zYyO+3CuPk6fouTaxscHkgtE8jKvf01kVfl8riHzERQ/kefaSA==", + "requires": { + "atob": "^2.1.1", + "decode-uri-component": "^0.2.0", + "resolve-url": "^0.2.1", + "source-map-url": "^0.4.0", + "urix": "^0.1.0" + } + }, + "source-map-support": { + "version": "0.4.18", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.4.18.tgz", + "integrity": "sha512-try0/JqxPLF9nOjvSta7tVondkP5dwgyLDjVoyMDlmjugT2lRZ1OfsrYTkCd2hkDnJTKRbO/Rl3orm8vlsUzbA==", + "requires": { + "source-map": "^0.5.6" + }, + "dependencies": { + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + } + } + }, + "source-map-url": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/source-map-url/-/source-map-url-0.4.0.tgz", + "integrity": "sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=" + }, + "spdx-correct": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.0.0.tgz", + "integrity": "sha512-N19o9z5cEyc8yQQPukRCZ9EUmb4HUpnrmaL/fxS2pBo2jbfcFRVuFZ/oFC+vZz0MNNk0h80iMn5/S6qGZOL5+g==", + "requires": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-exceptions": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.1.0.tgz", + "integrity": "sha512-4K1NsmrlCU1JJgUrtgEeTVyfx8VaYea9J9LvARxhbHtVtohPs/gFGG5yy49beySjlIMhhXZ4QqujIZEfS4l6Cg==" + }, + "spdx-expression-parse": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.0.tgz", + "integrity": "sha512-Yg6D3XpRD4kkOmTpdgbUiEJFKghJH03fiC1OPll5h/0sO6neh2jqRDVHOQ4o/LMea0tgCkbMgea5ip/e+MkWyg==", + "requires": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-license-ids": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.0.tgz", + "integrity": "sha512-2+EPwgbnmOIl8HjGBXXMd9NAu02vLjOO1nWw4kmeRDFyHn+M/ETfHxQUK0oXg8ctgVnl9t3rosNVsZ1jG61nDA==" + }, + "split-string": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/split-string/-/split-string-3.1.0.tgz", + "integrity": "sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==", + "requires": { + "extend-shallow": "^3.0.0" + } + }, + "sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=" + }, + "sshpk": { + "version": "1.14.2", + "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.14.2.tgz", + "integrity": "sha1-xvxhZIo9nE52T9P8306hBeSSupg=", + "requires": { + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "safer-buffer": "^2.0.2", + "tweetnacl": "~0.14.0" + } + }, + "static-extend": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz", + "integrity": "sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY=", + "requires": { + "define-property": "^0.2.5", + "object-copy": "^0.1.0" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "requires": { + "is-descriptor": "^0.1.0" + } + } + } + }, + "stream-browserify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-2.0.1.tgz", + "integrity": "sha1-ZiZu5fm9uZQKTkUUyvtDu3Hlyds=", + "requires": { + "inherits": "~2.0.1", + "readable-stream": "^2.0.2" + } + }, + "stream-http": { + "version": "2.8.3", + "resolved": "https://registry.npmjs.org/stream-http/-/stream-http-2.8.3.tgz", + "integrity": "sha512-+TSkfINHDo4J+ZobQLWiMouQYB+UVYFttRA94FpEzzJ7ZdqcL4uUUQ7WkdkI4DSozGmgBUE/a47L+38PenXhUw==", + "requires": { + "builtin-status-codes": "^3.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.3.6", + "to-arraybuffer": "^1.0.0", + "xtend": "^4.0.0" + } + }, + "strict-uri-encode": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/strict-uri-encode/-/strict-uri-encode-1.1.0.tgz", + "integrity": "sha1-J5siXfHVgrH1TmWt3UNS4Y+qBxM=" + }, + "string-length": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/string-length/-/string-length-1.0.1.tgz", + "integrity": "sha1-VpcPscOFWOnnC3KL894mmsRa36w=", + "requires": { + "strip-ansi": "^3.0.0" + } + }, + "string-width": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", + "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", + "requires": { + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^4.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "requires": { + "ansi-regex": "^3.0.0" + } + } + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "strip-bom": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz", + "integrity": "sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4=", + "requires": { + "is-utf8": "^0.2.0" + } + }, + "strip-eof": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", + "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=" + }, + "strip-indent": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-1.0.1.tgz", + "integrity": "sha1-DHlipq3vp7vUrDZkYKY4VSrhoKI=", + "requires": { + "get-stdin": "^4.0.1" + } + }, + "strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=" + }, + "style-loader": { + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/style-loader/-/style-loader-0.19.0.tgz", + "integrity": "sha512-9mx9sC9nX1dgP96MZOODpGC6l1RzQBITI2D5WJhu+wnbrSYVKLGuy14XJSLVQih/0GFrPpjelt+s//VcZQ2Evw==", + "requires": { + "loader-utils": "^1.0.2", + "schema-utils": "^0.3.0" + } + }, + "supports-color": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.4.0.tgz", + "integrity": "sha512-zjaXglF5nnWpsq470jSv6P9DwPvgLkuapYmfDm3JWOm0vkNTVF2tI4UrN2r6jH1qM/uc/WtxYY1hYoA2dOKj5w==", + "requires": { + "has-flag": "^3.0.0" + } + }, + "svgo": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/svgo/-/svgo-0.7.2.tgz", + "integrity": "sha1-n1dyQTlSE1xv779Ar+ak+qiLS7U=", + "requires": { + "coa": "~1.0.1", + "colors": "~1.1.2", + "csso": "~2.3.1", + "js-yaml": "~3.7.0", + "mkdirp": "~0.5.1", + "sax": "~1.2.1", + "whet.extend": "~0.9.9" + } + }, + "sw-precache": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/sw-precache/-/sw-precache-5.2.1.tgz", + "integrity": "sha512-8FAy+BP/FXE+ILfiVTt+GQJ6UEf4CVHD9OfhzH0JX+3zoy2uFk7Vn9EfXASOtVmmIVbL3jE/W8Z66VgPSZcMhw==", + "requires": { + "dom-urls": "^1.1.0", + "es6-promise": "^4.0.5", + "glob": "^7.1.1", + "lodash.defaults": "^4.2.0", + "lodash.template": "^4.4.0", + "meow": "^3.7.0", + "mkdirp": "^0.5.1", + "pretty-bytes": "^4.0.2", + "sw-toolbox": "^3.4.0", + "update-notifier": "^2.3.0" + } + }, + "sw-precache-webpack-plugin": { + "version": "0.11.4", + "resolved": "https://registry.npmjs.org/sw-precache-webpack-plugin/-/sw-precache-webpack-plugin-0.11.4.tgz", + "integrity": "sha1-ppUBflTu1XVVFJOlGdwdqNotxeA=", + "requires": { + "del": "^2.2.2", + "sw-precache": "^5.1.1", + "uglify-js": "^3.0.13" + } + }, + "sw-toolbox": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/sw-toolbox/-/sw-toolbox-3.6.0.tgz", + "integrity": "sha1-Jt8dHHA0hljk3qKIQxkUm3sxg7U=", + "requires": { + "path-to-regexp": "^1.0.1", + "serviceworker-cache-polyfill": "^4.0.0" + } + }, + "symbol-tree": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.2.tgz", + "integrity": "sha1-rifbOPZgp64uHDt9G8KQgZuFGeY=" + }, + "table": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/table/-/table-4.0.3.tgz", + "integrity": "sha512-S7rnFITmBH1EnyKcvxBh1LjYeQMmnZtCXSEbHcH6S0NoKit24ZuFO/T1vDcLdYsLQkM188PVVhQmzKIuThNkKg==", + "requires": { + "ajv": "^6.0.1", + "ajv-keywords": "^3.0.0", + "chalk": "^2.1.0", + "lodash": "^4.17.4", + "slice-ansi": "1.0.0", + "string-width": "^2.1.1" + }, + "dependencies": { + "ajv": { + "version": "6.5.1", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.5.1.tgz", + "integrity": "sha512-pgZos1vgOHDiC7gKNbZW8eKvCnNXARv2oqrGQT7Hzbq5Azp7aZG6DJzADnkuSq7RH6qkXp4J/m68yPX/2uBHyQ==", + "requires": { + "fast-deep-equal": "^2.0.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.1" + } + }, + "chalk": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", + "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "fast-deep-equal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", + "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=" + }, + "json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" + } + } + }, + "tapable": { + "version": "0.2.8", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-0.2.8.tgz", + "integrity": "sha1-mTcqXJmb8t8WCvwNdL7U9HlIzSI=" + }, + "term-size": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/term-size/-/term-size-1.2.0.tgz", + "integrity": "sha1-RYuDiH8oj8Vtb/+/rSYuJmOO+mk=", + "requires": { + "execa": "^0.7.0" + } + }, + "test-exclude": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-4.2.1.tgz", + "integrity": "sha512-qpqlP/8Zl+sosLxBcVKl9vYy26T9NPalxSzzCP/OY6K7j938ui2oKgo+kRZYfxAeIpLqpbVnsHq1tyV70E4lWQ==", + "requires": { + "arrify": "^1.0.1", + "micromatch": "^3.1.8", + "object-assign": "^4.1.0", + "read-pkg-up": "^1.0.1", + "require-main-filename": "^1.0.1" + } + }, + "text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=" + }, + "throat": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/throat/-/throat-3.2.0.tgz", + "integrity": "sha512-/EY8VpvlqJ+sFtLPeOgc8Pl7kQVOWv0woD87KTXVHPIAE842FGT+rokxIhe8xIUP1cfgrkt0as0vDLjDiMtr8w==" + }, + "through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=" + }, + "timed-out": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/timed-out/-/timed-out-4.0.1.tgz", + "integrity": "sha1-8y6srFoXW+ol1/q1Zas+2HQe9W8=" + }, + "timers-browserify": { + "version": "2.0.10", + "resolved": "https://registry.npmjs.org/timers-browserify/-/timers-browserify-2.0.10.tgz", + "integrity": "sha512-YvC1SV1XdOUaL6gx5CoGroT3Gu49pK9+TZ38ErPldOWW4j49GI1HKs9DV+KGq/w6y+LZ72W1c8cKz2vzY+qpzg==", + "requires": { + "setimmediate": "^1.0.4" + } + }, + "tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "requires": { + "os-tmpdir": "~1.0.2" + } + }, + "tmpl": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.4.tgz", + "integrity": "sha1-I2QN17QtAEM5ERQIIOXPRA5SHdE=" + }, + "to-arraybuffer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz", + "integrity": "sha1-fSKbH8xjfkZsoIEYCDanqr/4P0M=" + }, + "to-fast-properties": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-1.0.3.tgz", + "integrity": "sha1-uDVx+k2MJbguIxsG46MFXeTKGkc=" + }, + "to-object-path": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/to-object-path/-/to-object-path-0.3.0.tgz", + "integrity": "sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=", + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "to-regex": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/to-regex/-/to-regex-3.0.2.tgz", + "integrity": "sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw==", + "requires": { + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "regex-not": "^1.0.2", + "safe-regex": "^1.1.0" + } + }, + "to-regex-range": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-2.1.1.tgz", + "integrity": "sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=", + "requires": { + "is-number": "^3.0.0", + "repeat-string": "^1.6.1" + } + }, + "toposort": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/toposort/-/toposort-1.0.7.tgz", + "integrity": "sha1-LmhELZ9k7HILjMieZEOsbKqVACk=" + }, + "tough-cookie": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.4.3.tgz", + "integrity": "sha512-Q5srk/4vDM54WJsJio3XNn6K2sCG+CQ8G5Wz6bZhRZoAe/+TxjWB/GlFAnYEbkYVlON9FMk/fE3h2RLpPXo4lQ==", + "requires": { + "psl": "^1.1.24", + "punycode": "^1.4.1" + }, + "dependencies": { + "punycode": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", + "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=" + } + } + }, + "tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o=" + }, + "trim-newlines": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-1.0.0.tgz", + "integrity": "sha1-WIeWa7WCpFA6QetST301ARgVphM=" + }, + "trim-right": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", + "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=" + }, + "tty-browserify": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.0.tgz", + "integrity": "sha1-oVe6QC2iTpv5V/mqadUk7tQpAaY=" + }, + "tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", + "requires": { + "safe-buffer": "^5.0.1" + } + }, + "tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=", + "optional": true + }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "requires": { + "prelude-ls": "~1.1.2" + } + }, + "typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=" + }, + "ua-parser-js": { + "version": "0.7.18", + "resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.18.tgz", + "integrity": "sha512-LtzwHlVHwFGTptfNSgezHp7WUlwiqb0gA9AALRbKaERfxwJoiX0A73QbTToxteIAuIaFshhgIZfqK8s7clqgnA==" + }, + "uglify-js": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.4.2.tgz", + "integrity": "sha512-/kVQDzwiE9Vy7Y63eMkMozF4jIt0C2+xHctF9YpqNWdE/NLOuMurshkpoYGUlAbeYhACPv0HJPIHJul0Ak4/uw==", + "requires": { + "commander": "~2.15.0", + "source-map": "~0.6.1" + }, + "dependencies": { + "commander": { + "version": "2.15.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.15.1.tgz", + "integrity": "sha512-VlfT9F3V0v+jr4yxPc5gg9s62/fIVWsd2Bk2iD435um1NlGMYdVCq+MjcXnhYq2icNOizHr1kK+5TI6H0Hy0ag==" + } + } + }, + "uglify-to-browserify": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz", + "integrity": "sha1-bgkk1r2mta/jSeOabWMoUKD4grc=", + "optional": true + }, + "uglifyjs-webpack-plugin": { + "version": "0.4.6", + "resolved": "https://registry.npmjs.org/uglifyjs-webpack-plugin/-/uglifyjs-webpack-plugin-0.4.6.tgz", + "integrity": "sha1-uVH0q7a9YX5m9j64kUmOORdj4wk=", + "requires": { + "source-map": "^0.5.6", + "uglify-js": "^2.8.29", + "webpack-sources": "^1.0.1" + }, + "dependencies": { + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "uglify-js": { + "version": "2.8.29", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-2.8.29.tgz", + "integrity": "sha1-KcVzMUgFe7Th913zW3qcty5qWd0=", + "requires": { + "source-map": "~0.5.1", + "uglify-to-browserify": "~1.0.0", + "yargs": "~3.10.0" + } + }, + "yargs": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-3.10.0.tgz", + "integrity": "sha1-9+572FfdfB0tOMDnTvvWgdFDH9E=", + "requires": { + "camelcase": "^1.0.2", + "cliui": "^2.1.0", + "decamelize": "^1.0.0", + "window-size": "0.1.0" + } + } + } + }, + "union-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.0.tgz", + "integrity": "sha1-XHHDTLW61dzr4+oM0IIHulqhrqQ=", + "requires": { + "arr-union": "^3.1.0", + "get-value": "^2.0.6", + "is-extendable": "^0.1.1", + "set-value": "^0.4.3" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "requires": { + "is-extendable": "^0.1.0" + } + }, + "set-value": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-0.4.3.tgz", + "integrity": "sha1-fbCPnT0i3H945Trzw79GZuzfzPE=", + "requires": { + "extend-shallow": "^2.0.1", + "is-extendable": "^0.1.1", + "is-plain-object": "^2.0.1", + "to-object-path": "^0.3.0" + } + } + } + }, + "uniq": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/uniq/-/uniq-1.0.1.tgz", + "integrity": "sha1-sxxa6CVIRKOoKBVBzisEuGWnNP8=" + }, + "uniqs": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/uniqs/-/uniqs-2.0.0.tgz", + "integrity": "sha1-/+3ks2slKQaW5uFl1KWe25mOawI=" + }, + "unique-string": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unique-string/-/unique-string-1.0.0.tgz", + "integrity": "sha1-nhBXzKhRq7kzmPizOuGHuZyuwRo=", + "requires": { + "crypto-random-string": "^1.0.0" + } + }, + "universalify": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==" + }, + "unset-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unset-value/-/unset-value-1.0.0.tgz", + "integrity": "sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=", + "requires": { + "has-value": "^0.3.1", + "isobject": "^3.0.0" + }, + "dependencies": { + "has-value": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/has-value/-/has-value-0.3.1.tgz", + "integrity": "sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=", + "requires": { + "get-value": "^2.0.3", + "has-values": "^0.1.4", + "isobject": "^2.0.0" + }, + "dependencies": { + "isobject": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", + "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", + "requires": { + "isarray": "1.0.0" + } + } + } + }, + "has-values": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/has-values/-/has-values-0.1.4.tgz", + "integrity": "sha1-bWHeldkd/Km5oCCJrThL/49it3E=" + } + } + }, + "unzip-response": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/unzip-response/-/unzip-response-2.0.1.tgz", + "integrity": "sha1-0vD3N9FrBhXnKmk17QQhRXLVb5c=" + }, + "upath": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/upath/-/upath-1.1.0.tgz", + "integrity": "sha512-bzpH/oBhoS/QI/YtbkqCg6VEiPYjSZtrHQM6/QnJS6OL9pKUFLqb3aFh4Scvwm45+7iAgiMkLhSbaZxUqmrprw==" + }, + "update-notifier": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/update-notifier/-/update-notifier-2.5.0.tgz", + "integrity": "sha512-gwMdhgJHGuj/+wHJJs9e6PcCszpxR1b236igrOkUofGhqJuG+amlIKwApH1IW1WWl7ovZxsX49lMBWLxSdm5Dw==", + "requires": { + "boxen": "^1.2.1", + "chalk": "^2.0.1", + "configstore": "^3.0.0", + "import-lazy": "^2.1.0", + "is-ci": "^1.0.10", + "is-installed-globally": "^0.1.0", + "is-npm": "^1.0.0", + "latest-version": "^3.0.0", + "semver-diff": "^2.0.0", + "xdg-basedir": "^3.0.0" + }, + "dependencies": { + "chalk": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", + "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + } + } + }, + "upper-case": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/upper-case/-/upper-case-1.1.3.tgz", + "integrity": "sha1-9rRQHC7EzdJrp4vnIilh3ndiFZg=" + }, + "uri-js": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz", + "integrity": "sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==", + "requires": { + "punycode": "^2.1.0" + } + }, + "urijs": { + "version": "1.19.1", + "resolved": "https://registry.npmjs.org/urijs/-/urijs-1.19.1.tgz", + "integrity": "sha512-xVrGVi94ueCJNrBSTjWqjvtgvl3cyOTThp2zaMaFNGp3F542TR6sM3f2o8RqZl+AwteClSVmoCyt0ka4RjQOQg==" + }, + "urix": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/urix/-/urix-0.1.0.tgz", + "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=" + }, + "url": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/url/-/url-0.11.0.tgz", + "integrity": "sha1-ODjpfPxgUh63PFJajlW/3Z4uKPE=", + "requires": { + "punycode": "1.3.2", + "querystring": "0.2.0" + }, + "dependencies": { + "punycode": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz", + "integrity": "sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0=" + } + } + }, + "url-loader": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/url-loader/-/url-loader-0.6.2.tgz", + "integrity": "sha512-h3qf9TNn53BpuXTTcpC+UehiRrl0Cv45Yr/xWayApjw6G8Bg2dGke7rIwDQ39piciWCWrC+WiqLjOh3SUp9n0Q==", + "requires": { + "loader-utils": "^1.0.2", + "mime": "^1.4.1", + "schema-utils": "^0.3.0" + } + }, + "url-parse-lax": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/url-parse-lax/-/url-parse-lax-1.0.0.tgz", + "integrity": "sha1-evjzA2Rem9eaJy56FKxovAYJ2nM=", + "requires": { + "prepend-http": "^1.0.1" + } + }, + "use": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/use/-/use-3.1.0.tgz", + "integrity": "sha512-6UJEQM/L+mzC3ZJNM56Q4DFGLX/evKGRg15UJHGB9X5j5Z3AFbgZvjUh2yq/UJUY4U5dh7Fal++XbNg1uzpRAw==", + "requires": { + "kind-of": "^6.0.2" + } + }, + "util": { + "version": "0.10.4", + "resolved": "https://registry.npmjs.org/util/-/util-0.10.4.tgz", + "integrity": "sha512-0Pm9hTQ3se5ll1XihRic3FDIku70C+iHUdT/W926rSgHV5QgXsYbKZN8MSC3tJtSkhuROzvsQjAaFENRXr+19A==", + "requires": { + "inherits": "2.0.3" + } + }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" + }, + "utila": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/utila/-/utila-0.4.0.tgz", + "integrity": "sha1-ihagXURWV6Oupe7MWxKk+lN5dyw=" + }, + "uuid": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.2.tgz", + "integrity": "sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==" + }, + "validate-npm-package-license": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.3.tgz", + "integrity": "sha512-63ZOUnL4SIXj4L0NixR3L1lcjO38crAbgrTpl28t8jjrfuiOBL5Iygm+60qPs/KsZGzPNg6Smnc/oY16QTjF0g==", + "requires": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "vendors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/vendors/-/vendors-1.0.2.tgz", + "integrity": "sha512-w/hry/368nO21AN9QljsaIhb9ZiZtZARoVH5f3CsFbawdLdayCgKRPup7CggujvySMxx0I91NOyxdVENohprLQ==" + }, + "verror": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", + "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", + "requires": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + } + }, + "vm-browserify": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-0.0.4.tgz", + "integrity": "sha1-XX6kW7755Kb/ZflUOOCofDV9WnM=", + "requires": { + "indexof": "0.0.1" + } + }, + "walker": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.7.tgz", + "integrity": "sha1-L3+bj9ENZ3JisYqITijRlhjgKPs=", + "requires": { + "makeerror": "1.0.x" + } + }, + "watch": { + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/watch/-/watch-0.10.0.tgz", + "integrity": "sha1-d3mLLaD5kQ1ZXxrOWwwiWFIfIdw=" + }, + "watchpack": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-1.6.0.tgz", + "integrity": "sha512-i6dHe3EyLjMmDlU1/bGQpEw25XSjkJULPuAVKCbNRefQVq48yXKUpwg538F7AZTf9kyr57zj++pQFltUa5H7yA==", + "requires": { + "chokidar": "^2.0.2", + "graceful-fs": "^4.1.2", + "neo-async": "^2.5.0" + } + }, + "webidl-conversions": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-4.0.2.tgz", + "integrity": "sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg==" + }, + "webpack": { + "version": "3.8.1", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-3.8.1.tgz", + "integrity": "sha512-5ZXLWWsMqHKFr5y0N3Eo5IIisxeEeRAajNq4mELb/WELOR7srdbQk2N5XiyNy2A/AgvlR3AmeBCZJW8lHrolbw==", + "requires": { + "acorn": "^5.0.0", + "acorn-dynamic-import": "^2.0.0", + "ajv": "^5.1.5", + "ajv-keywords": "^2.0.0", + "async": "^2.1.2", + "enhanced-resolve": "^3.4.0", + "escope": "^3.6.0", + "interpret": "^1.0.0", + "json-loader": "^0.5.4", + "json5": "^0.5.1", + "loader-runner": "^2.3.0", + "loader-utils": "^1.1.0", + "memory-fs": "~0.4.1", + "mkdirp": "~0.5.0", + "node-libs-browser": "^2.0.0", + "source-map": "^0.5.3", + "supports-color": "^4.2.1", + "tapable": "^0.2.7", + "uglifyjs-webpack-plugin": "^0.4.6", + "watchpack": "^1.4.0", + "webpack-sources": "^1.0.1", + "yargs": "^8.0.2" + }, + "dependencies": { + "ajv-keywords": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-2.1.1.tgz", + "integrity": "sha1-YXmX/F9gV2iUxDX5QNgZ4TW4B2I=" + }, + "camelcase": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-4.1.0.tgz", + "integrity": "sha1-1UVjW+HjPFQmScaRc+Xeas+uNN0=" + }, + "cliui": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz", + "integrity": "sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0=", + "requires": { + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wrap-ansi": "^2.0.0" + }, + "dependencies": { + "string-width": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", + "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + } + } + }, + "has-flag": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-2.0.0.tgz", + "integrity": "sha1-6CB68cx7MNRGzHC3NLXovhj4jVE=" + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", + "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "load-json-file": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-2.0.0.tgz", + "integrity": "sha1-eUfkIUmvgNaWy/eXvKq8/h/inKg=", + "requires": { + "graceful-fs": "^4.1.2", + "parse-json": "^2.2.0", + "pify": "^2.0.0", + "strip-bom": "^3.0.0" + } + }, + "os-locale": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-2.1.0.tgz", + "integrity": "sha512-3sslG3zJbEYcaC4YVAvDorjGxc7tv6KVATnLPZONiljsUncvihe9BQoVCEs0RZ1kmf4Hk9OBqlZfJZWI4GanKA==", + "requires": { + "execa": "^0.7.0", + "lcid": "^1.0.0", + "mem": "^1.1.0" + } + }, + "path-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-2.0.0.tgz", + "integrity": "sha1-8BLMuEFbcJb8LaoQVMPXI4lZTHM=", + "requires": { + "pify": "^2.0.0" + } + }, + "read-pkg": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-2.0.0.tgz", + "integrity": "sha1-jvHAYjxqbbDcZxPEv6xGMysjaPg=", + "requires": { + "load-json-file": "^2.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^2.0.0" + } + }, + "read-pkg-up": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-2.0.0.tgz", + "integrity": "sha1-a3KoBImE4MQeeVEP1en6mbO1Sb4=", + "requires": { + "find-up": "^2.0.0", + "read-pkg": "^2.0.0" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" + }, + "strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=" + }, + "supports-color": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-4.5.0.tgz", + "integrity": "sha1-vnoN5ITexcXN34s9WRJQRJEvY1s=", + "requires": { + "has-flag": "^2.0.0" + } + }, + "which-module": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", + "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=" + }, + "yargs": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-8.0.2.tgz", + "integrity": "sha1-YpmpBVsc78lp/355wdkY3Osiw2A=", + "requires": { + "camelcase": "^4.1.0", + "cliui": "^3.2.0", + "decamelize": "^1.1.1", + "get-caller-file": "^1.0.1", + "os-locale": "^2.0.0", + "read-pkg-up": "^2.0.0", + "require-directory": "^2.1.1", + "require-main-filename": "^1.0.1", + "set-blocking": "^2.0.0", + "string-width": "^2.0.0", + "which-module": "^2.0.0", + "y18n": "^3.2.1", + "yargs-parser": "^7.0.0" + } + }, + "yargs-parser": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-7.0.0.tgz", + "integrity": "sha1-jQrELxbqVd69MyyvTEA4s+P139k=", + "requires": { + "camelcase": "^4.1.0" + } + } + } + }, + "webpack-manifest-plugin": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/webpack-manifest-plugin/-/webpack-manifest-plugin-1.3.2.tgz", + "integrity": "sha512-MX60Bv2G83Zks9pi3oLOmRgnPAnwrlMn+lftMrWBm199VQjk46/xgzBi9lPfpZldw2+EI2S+OevuLIaDuxCWRw==", + "requires": { + "fs-extra": "^0.30.0", + "lodash": ">=3.5 <5" + }, + "dependencies": { + "fs-extra": { + "version": "0.30.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-0.30.0.tgz", + "integrity": "sha1-8jP/zAjU2n1DLapEl3aYnbHfk/A=", + "requires": { + "graceful-fs": "^4.1.2", + "jsonfile": "^2.1.0", + "klaw": "^1.0.0", + "path-is-absolute": "^1.0.0", + "rimraf": "^2.2.8" + } + }, + "jsonfile": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-2.4.0.tgz", + "integrity": "sha1-NzaitCi4e72gzIO1P6PWM6NcKug=", + "requires": { + "graceful-fs": "^4.1.6" + } + } + } + }, + "webpack-sources": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-1.1.0.tgz", + "integrity": "sha512-aqYp18kPphgoO5c/+NaUvEeACtZjMESmDChuD3NBciVpah3XpMEU9VAAtIaB1BsfJWWTSdv8Vv1m3T0aRk2dUw==", + "requires": { + "source-list-map": "^2.0.0", + "source-map": "~0.6.1" + } + }, + "whatwg-encoding": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-1.0.3.tgz", + "integrity": "sha512-jLBwwKUhi8WtBfsMQlL4bUUcT8sMkAtQinscJAe/M4KHCkHuUJAF6vuB0tueNIw4c8ziO6AkRmgY+jL3a0iiPw==", + "requires": { + "iconv-lite": "0.4.19" + }, + "dependencies": { + "iconv-lite": { + "version": "0.4.19", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.19.tgz", + "integrity": "sha512-oTZqweIP51xaGPI4uPa56/Pri/480R+mo7SeU+YETByQNhDG55ycFyNLIgta9vXhILrxXDmF7ZGhqZIcuN0gJQ==" + } + } + }, + "whatwg-fetch": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-2.0.4.tgz", + "integrity": "sha512-dcQ1GWpOD/eEQ97k66aiEVpNnapVj90/+R+SXTPYGHpYBBypfKJEQjLrvMZ7YXbKm21gXd4NcuxUTjiv1YtLng==" + }, + "whatwg-url": { + "version": "4.8.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-4.8.0.tgz", + "integrity": "sha1-0pgaqRSMHgCkHFphMRZqtGg7vMA=", + "requires": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + }, + "dependencies": { + "webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE=" + } + } + }, + "whet.extend": { + "version": "0.9.9", + "resolved": "https://registry.npmjs.org/whet.extend/-/whet.extend-0.9.9.tgz", + "integrity": "sha1-+HfVv2SMl+WqVC+twW1qJZucEaE=" + }, + "which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "requires": { + "isexe": "^2.0.0" + } + }, + "which-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-1.0.0.tgz", + "integrity": "sha1-u6Y8qGGUiZT/MHc2CJ47lgJsKk8=" + }, + "widest-line": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-2.0.0.tgz", + "integrity": "sha1-AUKk6KJD+IgsAjOqDgKBqnYVInM=", + "requires": { + "string-width": "^2.1.1" + } + }, + "window-size": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/window-size/-/window-size-0.1.0.tgz", + "integrity": "sha1-VDjNLqk7IC76Ohn+iIeu58lPnJ0=" + }, + "wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=" + }, + "worker-farm": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/worker-farm/-/worker-farm-1.6.0.tgz", + "integrity": "sha512-6w+3tHbM87WnSWnENBUvA2pxJPLhQUg5LKwUQHq3r+XPhIM+Gh2R5ycbwPCyuGbNg+lPgdcnQUhuC02kJCvffQ==", + "requires": { + "errno": "~0.1.7" + } + }, + "wrap-ansi": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", + "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=", + "requires": { + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1" + }, + "dependencies": { + "is-fullwidth-code-point": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", + "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "string-width": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", + "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + } + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + }, + "write": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/write/-/write-0.2.1.tgz", + "integrity": "sha1-X8A4KOJkzqP+kUVUdvejxWbLB1c=", + "requires": { + "mkdirp": "^0.5.1" + } + }, + "write-file-atomic": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", + "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "requires": { + "graceful-fs": "^4.1.11", + "imurmurhash": "^0.1.4", + "signal-exit": "^3.0.2" + } + }, + "xdg-basedir": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-3.0.0.tgz", + "integrity": "sha1-SWsswQnsqNus/i3HK2A8F8WHCtQ=" + }, + "xml-name-validator": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-2.0.1.tgz", + "integrity": "sha1-TYuPHszTQZqjYgYb7O9RXh5VljU=" + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=" + }, + "y18n": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-3.2.1.tgz", + "integrity": "sha1-bRX7qITAhnnA136I53WegR4H+kE=" + }, + "yallist": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", + "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=" + }, + "yargs": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-7.1.0.tgz", + "integrity": "sha1-a6MY6xaWFyf10oT46gA+jWFU0Mg=", + "requires": { + "camelcase": "^3.0.0", + "cliui": "^3.2.0", + "decamelize": "^1.1.1", + "get-caller-file": "^1.0.1", + "os-locale": "^1.4.0", + "read-pkg-up": "^1.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^1.0.1", + "set-blocking": "^2.0.0", + "string-width": "^1.0.2", + "which-module": "^1.0.0", + "y18n": "^3.2.1", + "yargs-parser": "^5.0.0" + }, + "dependencies": { + "camelcase": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-3.0.0.tgz", + "integrity": "sha1-MvxLn82vhF/N9+c7uXysImHwqwo=" + }, + "cliui": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz", + "integrity": "sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0=", + "requires": { + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wrap-ansi": "^2.0.0" + } + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", + "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "string-width": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", + "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + } + } + }, + "yargs-parser": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-5.0.0.tgz", + "integrity": "sha1-J17PDX/+Bcd+ZOfIbkzZS/DhIoo=", + "requires": { + "camelcase": "^3.0.0" + }, + "dependencies": { + "camelcase": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-3.0.0.tgz", + "integrity": "sha1-MvxLn82vhF/N9+c7uXysImHwqwo=" + } + } + } + } +} diff --git a/spring-security-react/src/main/webapp/WEB-INF/view/react/package.json b/spring-security-react/src/main/webapp/WEB-INF/view/react/package.json new file mode 100644 index 0000000000..859d9a6f83 --- /dev/null +++ b/spring-security-react/src/main/webapp/WEB-INF/view/react/package.json @@ -0,0 +1,20 @@ +{ + "name": "react", + "version": "0.1.0", + "private": true, + "dependencies": { + "prop-types": "^15.6.2", + "react": "^16.4.1", + "react-dom": "^16.4.1", + "react-scripts": "1.1.4" + }, + "scripts": { + "start": "react-scripts start", + "build": "react-scripts build", + "test": "react-scripts test --env=jsdom", + "eject": "react-scripts eject" + }, + "devDependencies": { + "eslint-plugin-react": "^7.9.1" + } +} diff --git a/spring-security-react/src/main/webapp/WEB-INF/view/react/public/favicon.ico b/spring-security-react/src/main/webapp/WEB-INF/view/react/public/favicon.ico new file mode 100644 index 0000000000..a11777cc47 Binary files /dev/null and b/spring-security-react/src/main/webapp/WEB-INF/view/react/public/favicon.ico differ diff --git a/spring-security-react/src/main/webapp/WEB-INF/view/react/public/index.html b/spring-security-react/src/main/webapp/WEB-INF/view/react/public/index.html new file mode 100644 index 0000000000..0c3f78d7b3 --- /dev/null +++ b/spring-security-react/src/main/webapp/WEB-INF/view/react/public/index.html @@ -0,0 +1,30 @@ + + + + + + + + + + Spring Login - React App + + + + +
    +
    +
    + + + diff --git a/spring-security-react/src/main/webapp/WEB-INF/view/react/public/manifest.json b/spring-security-react/src/main/webapp/WEB-INF/view/react/public/manifest.json new file mode 100644 index 0000000000..ef19ec243e --- /dev/null +++ b/spring-security-react/src/main/webapp/WEB-INF/view/react/public/manifest.json @@ -0,0 +1,15 @@ +{ + "short_name": "React App", + "name": "Create React App Sample", + "icons": [ + { + "src": "favicon.ico", + "sizes": "64x64 32x32 24x24 16x16", + "type": "image/x-icon" + } + ], + "start_url": "./index.html", + "display": "standalone", + "theme_color": "#000000", + "background_color": "#ffffff" +} diff --git a/spring-security-react/src/main/webapp/WEB-INF/view/react/src/Form.js b/spring-security-react/src/main/webapp/WEB-INF/view/react/src/Form.js new file mode 100644 index 0000000000..0fded264ac --- /dev/null +++ b/spring-security-react/src/main/webapp/WEB-INF/view/react/src/Form.js @@ -0,0 +1,81 @@ +import React, { Component } from 'react' +import PropTypes from 'prop-types' +import Input from './Input' + +class Form extends Component { + + constructor(props){ + super(props) + if(props.error){ + this.state = { failure: 'wrong username or password!', errcount: 0 } + }else{ + this.state = { errcount: 0 } + } + } + + handleSubmit = (event) => { + event.preventDefault() + if(!this.state.errcount) { + const data = new FormData(this.form) + fetch(this.form.action, { + method: this.form.method, + body: new URLSearchParams(data) + }).then(v => { + if(v.redirected) window.location = v.url + }) + .catch(e => console.warn(e)) + } + } + + handleError = (field, errmsg) => { + if(!field) return + + if(errmsg){ + this.setState((prevState) => ({ + failure: '', + errcount: prevState.errcount + 1, + errmsgs: {...prevState.errmsgs, [field]: errmsg} + })) + } else { + this.setState((prevState) => ({ + failure: '', + errcount: prevState.errcount===1? 0 : prevState.errcount-1, + errmsgs: {...prevState.errmsgs, [field]: ''} + })) + } + } + + renderError = () => { + if(this.state.errcount || this.state.failure) { + const errmsg = this.state.failure || Object.values(this.state.errmsgs).find(v=>v) + console.log(`error: ${errmsg}`) + return
    {errmsg}
    + } + } + + render() { + const inputs = this.props.inputs.map( + ({name, placeholder, type, value, className}, index) => ( + + ) + ) + const errors = this.renderError() + return ( +
    {this.form=fm}} > + {inputs} + {errors} +
    + ) + } +} + +Form.propTypes = { + name: PropTypes.string, + action: PropTypes.string, + method: PropTypes.string, + inputs: PropTypes.array, + error: PropTypes.string +} + +export default Form \ No newline at end of file diff --git a/spring-security-react/src/main/webapp/WEB-INF/view/react/src/Input.js b/spring-security-react/src/main/webapp/WEB-INF/view/react/src/Input.js new file mode 100644 index 0000000000..caa2f2a499 --- /dev/null +++ b/spring-security-react/src/main/webapp/WEB-INF/view/react/src/Input.js @@ -0,0 +1,57 @@ +import React, { Component } from 'react' +import PropTypes from 'prop-types' + +class Input extends Component { + + constructor(props){ + super(props) + this.state = { + value: props.value? props.value : '', + className: props.className? props.className : '', + error: false + } + } + + inputChange = (event) => { + const value = event.target.value, name = event.target.name + //switch(name) { + // case 'username': this.validate(name, value, /^([a-zA-Z0-9.]{4,})$/, 'invalid username') + // break; + // case 'password': this.validate(name, value, /^(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z]).{6,}$/, 'insecure password') + // break; + // default: + // console.warn(`unknown field ${name}`) + //} + this.setState({ value: value }) + } + + validate = (name, value, validRegex, warnmsg) => { + const invalid = !value || !validRegex.test(value) + if(!this.state.error && invalid) { + this.setState({ className: 'input-error', error: true }) + this.handleError(name, warnmsg) + }else if(this.state.error && !invalid) { + this.setState({ className: '', error: false }) + this.handleError(name) + } + } + + render (){ + const {handleError, ...opts} = this.props + this.handleError = handleError + return ( + + ) + } +} + +Input.propTypes = { + name: PropTypes.string, + placeholder: PropTypes.string, + type: PropTypes.string, + className: PropTypes.string, + handleError: PropTypes.func, + value: PropTypes.string +} + +export default Input diff --git a/spring-security-react/src/main/webapp/WEB-INF/view/react/src/index.css b/spring-security-react/src/main/webapp/WEB-INF/view/react/src/index.css new file mode 100644 index 0000000000..c840272252 --- /dev/null +++ b/spring-security-react/src/main/webapp/WEB-INF/view/react/src/index.css @@ -0,0 +1,61 @@ +body { + font-family: "Open Sans", "Roboto", arial, sans-serif; + background: #e9e9e9; +} + +#root { + position: absolute; + top: 50%; + right: 0; + left: 0; + margin-right: auto; + margin-left: auto; + transform: translateY(-50%); + overflow: hidden; + display: flex; + align-items: center; + justify-content: center; + width: 100%; + height: 110%; + border-radius: .19rem; + box-shadow: 0px .19rem .41rem rgba(0,0,0,.25); +} + +form { + height: 100%; + padding: 1.5rem; + background: #fafafa; +} + +input { + background-color: transparent; + border-top: 0; + border-right: 0; + border-left: 0; + border-radius: 0; + color: #111; + font-size: 1rem; + padding: .3rem .5rem; + margin-bottom: 1rem; + display: block; +} + +.input-error { + border-color: #FF0000; +} + +.error { + color: #FF0000; + padding: .2rem; +} + +.btn { + padding: .5rem 1.5rem; + font-size: .85rem; + font-weight: 600; + text-transform: uppercase; + color: #fff; + background: #111; + border-radius: .25rem; + margin: 0; +} diff --git a/spring-security-react/src/main/webapp/WEB-INF/view/react/src/index.js b/spring-security-react/src/main/webapp/WEB-INF/view/react/src/index.js new file mode 100644 index 0000000000..4a125c565d --- /dev/null +++ b/spring-security-react/src/main/webapp/WEB-INF/view/react/src/index.js @@ -0,0 +1,25 @@ +import React from 'react' +import ReactDOM from 'react-dom' +import './index.css' +import Form from './Form' + +const inputs = [{ + name: "username", + placeholder: "username", + type: "text" +},{ + name: "password", + placeholder: "password", + type: "password" +},{ + type: "submit", + value: "Submit", + className: "btn" +}] + +const props = {name: 'loginForm', method: 'POST', action: '/perform_login', inputs: inputs} + +const params = new URLSearchParams(window.location.search) + +ReactDOM.render(
    , document.getElementById('container')) + diff --git a/spring-security-react/src/main/webapp/WEB-INF/view/react/src/registerServiceWorker.js b/spring-security-react/src/main/webapp/WEB-INF/view/react/src/registerServiceWorker.js new file mode 100644 index 0000000000..a3e6c0cfc1 --- /dev/null +++ b/spring-security-react/src/main/webapp/WEB-INF/view/react/src/registerServiceWorker.js @@ -0,0 +1,117 @@ +// In production, we register a service worker to serve assets from local cache. + +// This lets the app load faster on subsequent visits in production, and gives +// it offline capabilities. However, it also means that developers (and users) +// will only see deployed updates on the "N+1" visit to a page, since previously +// cached resources are updated in the background. + +// To learn more about the benefits of this model, read https://goo.gl/KwvDNy. +// This link also includes instructions on opting out of this behavior. + +const isLocalhost = Boolean( + window.location.hostname === 'localhost' || + // [::1] is the IPv6 localhost address. + window.location.hostname === '[::1]' || + // 127.0.0.1/8 is considered localhost for IPv4. + window.location.hostname.match( + /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ + ) +); + +export default function register() { + if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { + // The URL constructor is available in all browsers that support SW. + const publicUrl = new URL(process.env.PUBLIC_URL, window.location); + if (publicUrl.origin !== window.location.origin) { + // Our service worker won't work if PUBLIC_URL is on a different origin + // from what our page is served on. This might happen if a CDN is used to + // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374 + return; + } + + window.addEventListener('load', () => { + const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; + + if (isLocalhost) { + // This is running on localhost. Lets check if a service worker still exists or not. + checkValidServiceWorker(swUrl); + + // Add some additional logging to localhost, pointing developers to the + // service worker/PWA documentation. + navigator.serviceWorker.ready.then(() => { + console.log( + 'This web app is being served cache-first by a service ' + + 'worker. To learn more, visit https://goo.gl/SC7cgQ' + ); + }); + } else { + // Is not local host. Just register service worker + registerValidSW(swUrl); + } + }); + } +} + +function registerValidSW(swUrl) { + navigator.serviceWorker + .register(swUrl) + .then(registration => { + registration.onupdatefound = () => { + const installingWorker = registration.installing; + installingWorker.onstatechange = () => { + if (installingWorker.state === 'installed') { + if (navigator.serviceWorker.controller) { + // At this point, the old content will have been purged and + // the fresh content will have been added to the cache. + // It's the perfect time to display a "New content is + // available; please refresh." message in your web app. + console.log('New content is available; please refresh.'); + } else { + // At this point, everything has been precached. + // It's the perfect time to display a + // "Content is cached for offline use." message. + console.log('Content is cached for offline use.'); + } + } + }; + }; + }) + .catch(error => { + console.error('Error during service worker registration:', error); + }); +} + +function checkValidServiceWorker(swUrl) { + // Check if the service worker can be found. If it can't reload the page. + fetch(swUrl) + .then(response => { + // Ensure service worker exists, and that we really are getting a JS file. + if ( + response.status === 404 || + response.headers.get('content-type').indexOf('javascript') === -1 + ) { + // No service worker found. Probably a different app. Reload the page. + navigator.serviceWorker.ready.then(registration => { + registration.unregister().then(() => { + window.location.reload(); + }); + }); + } else { + // Service worker found. Proceed as normal. + registerValidSW(swUrl); + } + }) + .catch(() => { + console.log( + 'No internet connection found. App is running in offline mode.' + ); + }); +} + +export function unregister() { + if ('serviceWorker' in navigator) { + navigator.serviceWorker.ready.then(registration => { + registration.unregister(); + }); + } +} diff --git a/spring-security-react/src/main/webapp/WEB-INF/web.xml b/spring-security-react/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..eef48ec9b3 --- /dev/null +++ b/spring-security-react/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,57 @@ + + + + Spring MVC Application + + + + contextClass + + org.springframework.web.context.support.AnnotationConfigWebApplicationContext + + + + contextConfigLocation + org.baeldung.spring + + + + org.springframework.web.context.ContextLoaderListener + + + + + mvc + org.springframework.web.servlet.DispatcherServlet + 1 + + + mvc + / + + + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + springSecurityFilterChain + /* + + + + 403 + /accessDenied + + + + + + + + + \ No newline at end of file diff --git a/spring-security-rest-basic-auth/pom.xml b/spring-security-rest-basic-auth/pom.xml index bed3cd033d..61a144db0c 100644 --- a/spring-security-rest-basic-auth/pom.xml +++ b/spring-security-rest-basic-auth/pom.xml @@ -1,19 +1,19 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + com.baeldung spring-security-rest-basic-auth 0.2-SNAPSHOT - spring-security-rest-basic-auth war - com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring - + com.baeldung + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 + @@ -22,12 +22,12 @@ org.springframework.security spring-security-web - ${org.springframework.security.version} + ${spring.version} org.springframework.security spring-security-config - ${org.springframework.security.version} + ${spring.version} @@ -35,7 +35,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -46,49 +46,49 @@ org.springframework spring-context - ${org.springframework.version} + ${spring.version} org.springframework spring-jdbc - ${org.springframework.version} + ${spring.version} org.springframework spring-beans - ${org.springframework.version} + ${spring.version} org.springframework spring-aop - ${org.springframework.version} + ${spring.version} org.springframework spring-tx - ${org.springframework.version} + ${spring.version} org.springframework spring-expression - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} org.springframework spring-oxm - ${org.springframework.version} + ${spring.version} @@ -96,7 +96,7 @@ com.fasterxml.jackson.core jackson-databind - ${jackson.version} + ${jackson-databind.version} @@ -166,7 +166,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -270,34 +270,21 @@ - - 4.3.6.RELEASE - 4.2.1.RELEASE - - - 5.2.5.Final - 5.1.40 4.4.5 4.5.3 - 5.3.3.Final 1.2 3.1.0 - 2.8.5 19.0 - 3.5 - - 2.9.0 2.6 1.6.1 - \ No newline at end of file diff --git a/spring-security-rest-basic-auth/src/main/java/org/baeldung/filter/CustomWebSecurityConfigurerAdapter.java b/spring-security-rest-basic-auth/src/main/java/org/baeldung/filter/CustomWebSecurityConfigurerAdapter.java index 2ff0e30f94..7ca2a80c52 100644 --- a/spring-security-rest-basic-auth/src/main/java/org/baeldung/filter/CustomWebSecurityConfigurerAdapter.java +++ b/spring-security-rest-basic-auth/src/main/java/org/baeldung/filter/CustomWebSecurityConfigurerAdapter.java @@ -2,11 +2,14 @@ package org.baeldung.filter; import org.baeldung.security.RestAuthenticationEntryPoint; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; @Configuration @@ -20,7 +23,7 @@ public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAda auth .inMemoryAuthentication() .withUser("user1") - .password("user1Pass") + .password(passwordEncoder().encode("user1Pass")) .authorities("ROLE_USER"); } @@ -38,4 +41,9 @@ public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAda http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class); } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } } diff --git a/spring-security-rest-basic-auth/src/main/java/org/baeldung/spring/WebConfig.java b/spring-security-rest-basic-auth/src/main/java/org/baeldung/spring/WebConfig.java index 8c3d677af6..2305a7b6c2 100644 --- a/spring-security-rest-basic-auth/src/main/java/org/baeldung/spring/WebConfig.java +++ b/spring-security-rest-basic-auth/src/main/java/org/baeldung/spring/WebConfig.java @@ -7,12 +7,13 @@ import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @EnableWebMvc @ComponentScan("org.baeldung.web") -public class WebConfig extends WebMvcConfigurerAdapter { +public class WebConfig implements WebMvcConfigurer { public WebConfig() { super(); @@ -22,7 +23,6 @@ public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(final List> converters) { - super.configureMessageConverters(converters); converters.add(new MappingJackson2HttpMessageConverter()); } diff --git a/spring-security-rest-basic-auth/src/main/resources/logback.xml b/spring-security-rest-basic-auth/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-security-rest-basic-auth/src/main/resources/logback.xml +++ b/spring-security-rest-basic-auth/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-security-rest-basic-auth/src/main/resources/webSecurityConfig.xml b/spring-security-rest-basic-auth/src/main/resources/webSecurityConfig.xml index 6dea965d8b..a93dc841b6 100644 --- a/spring-security-rest-basic-auth/src/main/resources/webSecurityConfig.xml +++ b/spring-security-rest-basic-auth/src/main/resources/webSecurityConfig.xml @@ -2,25 +2,27 @@ - + - + + + \ No newline at end of file diff --git a/spring-security-rest-basic-auth/src/main/webapp/WEB-INF/api-servlet.xml b/spring-security-rest-basic-auth/src/main/webapp/WEB-INF/api-servlet.xml index 4ba9642448..1dbff70b83 100644 --- a/spring-security-rest-basic-auth/src/main/webapp/WEB-INF/api-servlet.xml +++ b/spring-security-rest-basic-auth/src/main/webapp/WEB-INF/api-servlet.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" > \ No newline at end of file diff --git a/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/RestClientLiveManualTest.java b/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/RestClientLiveManualTest.java index c27e306c08..104129b663 100644 --- a/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/RestClientLiveManualTest.java +++ b/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/RestClientLiveManualTest.java @@ -8,6 +8,9 @@ import java.io.IOException; import java.security.GeneralSecurityException; import java.security.cert.X509Certificate; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLPeerUnverifiedException; + import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; @@ -16,6 +19,7 @@ import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; import org.junit.Ignore; import org.junit.Test; diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index cfa3ad4b99..66ad087bf6 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -1,18 +1,18 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + com.baeldung spring-security-rest-custom 0.1-SNAPSHOT - spring-security-rest-custom war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -201,8 +201,6 @@ 19.0 3.5 1.2 - 4.4.5 - 4.5.2 1.6.1 diff --git a/spring-security-rest-custom/src/main/resources/logback.xml b/spring-security-rest-custom/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-security-rest-custom/src/main/resources/logback.xml +++ b/spring-security-rest-custom/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index e29012a3a5..5bde78db7e 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -1,19 +1,19 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + com.baeldung spring-security-rest 0.1-SNAPSHOT - spring-security-rest war - com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring - + com.baeldung + parent-spring-4 + 0.0.1-SNAPSHOT + ../parent-spring-4 + @@ -35,7 +35,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -46,43 +46,43 @@ org.springframework spring-context - ${org.springframework.version} + ${spring.version} org.springframework spring-jdbc - ${org.springframework.version} + ${spring.version} org.springframework spring-beans - ${org.springframework.version} + ${spring.version} org.springframework spring-aop - ${org.springframework.version} + ${spring.version} org.springframework spring-tx - ${org.springframework.version} + ${spring.version} org.springframework spring-expression - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} @@ -138,7 +138,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -275,25 +275,17 @@ - - - 4.3.4.RELEASE - 4.2.0.RELEASE + 4.2.6.RELEASE 0.21.0.RELEASE - - 5.2.5.Final - 5.1.40 - - 5.3.3.Final 3.1.0 1.1.0.Final 1.2 @@ -310,15 +302,9 @@ 2.7.0 - 4.4.5 - 4.5.2 - - 2.9.0 - 2.6 1.6.1 - diff --git a/spring-security-rest/src/main/resources/logback.xml b/spring-security-rest/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-security-rest/src/main/resources/logback.xml +++ b/spring-security-rest/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-security-sso/pom.xml b/spring-security-sso/pom.xml index 938636ff18..764e899640 100644 --- a/spring-security-sso/pom.xml +++ b/spring-security-sso/pom.xml @@ -9,10 +9,10 @@ pom - parent-boot-5 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-2 @@ -22,7 +22,9 @@ - 3.0.1 - - + 3.1.0 + 2.3.3.RELEASE + 2.0.1.RELEASE + + \ No newline at end of file diff --git a/spring-security-sso/spring-security-sso-auth-server/pom.xml b/spring-security-sso/spring-security-sso-auth-server/pom.xml index 0d0086beb0..1d57248b30 100644 --- a/spring-security-sso/spring-security-sso-auth-server/pom.xml +++ b/spring-security-sso/spring-security-sso-auth-server/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 + spring-security-sso-auth-server - spring-security-sso-auth-server war @@ -21,6 +22,7 @@ org.springframework.security.oauth spring-security-oauth2 + ${oauth.version} diff --git a/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthServerConfig.java b/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthServerConfig.java index 20cde21073..07057c3875 100644 --- a/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthServerConfig.java +++ b/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthServerConfig.java @@ -2,19 +2,20 @@ package org.baeldung.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; -import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; + @Configuration @EnableAuthorizationServer public class AuthServerConfig extends AuthorizationServerConfigurerAdapter { - @Autowired - private AuthenticationManager authenticationManager; - + + @Autowired + private BCryptPasswordEncoder passwordEncoder; + @Override public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.tokenKeyAccess("permitAll()") @@ -25,17 +26,14 @@ public class AuthServerConfig extends AuthorizationServerConfigurerAdapter { public void configure(final ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("SampleClientId") - .secret("secret") + .secret(passwordEncoder.encode("secret")) .authorizedGrantTypes("authorization_code") .scopes("user_info") .autoApprove(true) + .redirectUris("http://localhost:8082/ui/login","http://localhost:8083/ui2/login","http://localhost:8082/login") // .accessTokenValiditySeconds(3600) ; // 1 hour } - @Override - public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception { - endpoints.authenticationManager(authenticationManager); - } } diff --git a/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthorizationServerApplication.java b/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthorizationServerApplication.java index 5b0b39b444..b74d2f144c 100644 --- a/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthorizationServerApplication.java +++ b/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthorizationServerApplication.java @@ -2,7 +2,7 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; @SpringBootApplication diff --git a/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/SecurityConfig.java index a568c22eec..5cebf4f4d2 100644 --- a/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/SecurityConfig.java +++ b/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/SecurityConfig.java @@ -1,18 +1,17 @@ package org.baeldung.config; -import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.core.annotation.Order; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration +@Order(1) public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Autowired - private AuthenticationManager authenticationManager; - + @Override protected void configure(HttpSecurity http) throws Exception { // @formatter:off http.requestMatchers() @@ -28,11 +27,14 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // @formatter:off - auth.parentAuthenticationManager(authenticationManager) - .inMemoryAuthentication() + auth.inMemoryAuthentication() .withUser("john") - .password("123") + .password(passwordEncoder().encode("123")) .roles("USER"); } // @formatter:on + @Bean + public BCryptPasswordEncoder passwordEncoder(){ + return new BCryptPasswordEncoder(); + } } diff --git a/spring-security-sso/spring-security-sso-auth-server/src/main/resources/application.properties b/spring-security-sso/spring-security-sso-auth-server/src/main/resources/application.properties index 32a0993b04..066123118f 100644 --- a/spring-security-sso/spring-security-sso-auth-server/src/main/resources/application.properties +++ b/spring-security-sso/spring-security-sso-auth-server/src/main/resources/application.properties @@ -1,4 +1,3 @@ server.port=8081 -server.context-path=/auth -security.basic.enabled=false +server.servlet.context-path=/auth #logging.level.org.springframework=DEBUG \ No newline at end of file diff --git a/spring-security-sso/spring-security-sso-auth-server/src/main/resources/logback.xml b/spring-security-sso/spring-security-sso-auth-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-sso/spring-security-sso-auth-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-sso/spring-security-sso-ui-2/pom.xml b/spring-security-sso/spring-security-sso-ui-2/pom.xml index a2323a044d..afe7b59822 100644 --- a/spring-security-sso/spring-security-sso-ui-2/pom.xml +++ b/spring-security-sso/spring-security-sso-ui-2/pom.xml @@ -1,8 +1,8 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - spring-security-sso-ui-2 + spring-security-sso-ui-2 spring-security-sso-ui-2 war @@ -25,8 +25,9 @@ - org.springframework.security.oauth - spring-security-oauth2 + org.springframework.security.oauth.boot + spring-security-oauth2-autoconfigure + ${oauth-auto.version} 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 a222224c59..0c20853aed 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,7 +2,7 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import org.springframework.web.context.request.RequestContextListener; 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 f9119e20f5..de81ada9e0 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 @@ -5,6 +5,7 @@ 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-security-sso/spring-security-sso-ui-2/src/main/resources/application.yml b/spring-security-sso/spring-security-sso-ui-2/src/main/resources/application.yml index 6b0d3db5ad..97c8de7839 100644 --- a/spring-security-sso/spring-security-sso-ui-2/src/main/resources/application.yml +++ b/spring-security-sso/spring-security-sso-ui-2/src/main/resources/application.yml @@ -1,6 +1,7 @@ server: port: 8083 - context-path: /ui2 + servlet: + context-path: /ui2 session: cookie: name: UI2SESSION diff --git a/spring-security-sso/spring-security-sso-ui-2/src/main/resources/logback.xml b/spring-security-sso/spring-security-sso-ui-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-sso/spring-security-sso-ui-2/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-sso/spring-security-sso-ui/pom.xml b/spring-security-sso/spring-security-sso-ui/pom.xml index dbb167b61c..deb0e081be 100644 --- a/spring-security-sso/spring-security-sso-ui/pom.xml +++ b/spring-security-sso/spring-security-sso-ui/pom.xml @@ -1,8 +1,8 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - spring-security-sso-ui + spring-security-sso-ui spring-security-sso-ui war @@ -23,11 +23,13 @@ org.springframework.boot spring-boot-starter-security - + - org.springframework.security.oauth - spring-security-oauth2 + org.springframework.security.oauth.boot + spring-security-oauth2-autoconfigure + ${oauth-auto.version} + org.springframework.boot diff --git a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java index e186046e83..07d875d805 100644 --- a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java @@ -2,7 +2,7 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import org.springframework.web.context.request.RequestContextListener; diff --git a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java index f9119e20f5..de81ada9e0 100644 --- a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java +++ b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java @@ -5,6 +5,7 @@ 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-security-sso/spring-security-sso-ui/src/main/resources/application.yml b/spring-security-sso/spring-security-sso-ui/src/main/resources/application.yml index bb4bd92033..d1d9ea6ebc 100644 --- a/spring-security-sso/spring-security-sso-ui/src/main/resources/application.yml +++ b/spring-security-sso/spring-security-sso-ui/src/main/resources/application.yml @@ -1,6 +1,7 @@ server: port: 8082 - context-path: /ui + servlet: + context-path: /ui session: cookie: name: UISESSION diff --git a/spring-security-sso/spring-security-sso-ui/src/main/resources/logback.xml b/spring-security-sso/spring-security-sso-ui/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-sso/spring-security-sso-ui/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-stormpath/pom.xml b/spring-security-stormpath/pom.xml index 17973165ea..5c5783eec5 100644 --- a/spring-security-stormpath/pom.xml +++ b/spring-security-stormpath/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung spring-security-stormpath @@ -7,14 +7,6 @@ 1.0-SNAPSHOT spring-security-stormpath http://maven.apache.org - - - parent-boot-5 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-5 - - abhinabkanrar@gmail.com @@ -24,6 +16,13 @@ + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-1 + + org.springframework.boot @@ -69,10 +68,4 @@ - - UTF-8 - UTF-8 - 1.8 - - diff --git a/spring-security-stormpath/src/main/resources/logback.xml b/spring-security-stormpath/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-stormpath/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-thymeleaf/README.MD b/spring-security-thymeleaf/README.MD index 36007bce62..c5deeb9946 100644 --- a/spring-security-thymeleaf/README.MD +++ b/spring-security-thymeleaf/README.MD @@ -4,3 +4,4 @@ Jira BAEL-1556 ### Relevant Articles: - [Spring Security with Thymeleaf](http://www.baeldung.com/spring-security-thymeleaf) +- [Working with Select and Option in Thymeleaf](http://www.baeldung.com/thymeleaf-select-option) diff --git a/spring-security-thymeleaf/pom.xml b/spring-security-thymeleaf/pom.xml index aa36e5f59a..5b7715bdeb 100644 --- a/spring-security-thymeleaf/pom.xml +++ b/spring-security-thymeleaf/pom.xml @@ -1,7 +1,8 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + com.baeldung spring-security-thymeleaf 0.0.1-SNAPSHOT @@ -10,10 +11,10 @@ Spring Security with Thymeleaf tutorial - parent-boot-5 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-2 @@ -55,10 +56,4 @@ - - UTF-8 - UTF-8 - 1.8 - - diff --git a/spring-security-thymeleaf/src/main/java/com/baeldung/springsecuritythymeleaf/SecurityConfiguration.java b/spring-security-thymeleaf/src/main/java/com/baeldung/springsecuritythymeleaf/SecurityConfiguration.java index 687c0c2e39..0a4344db4d 100644 --- a/spring-security-thymeleaf/src/main/java/com/baeldung/springsecuritythymeleaf/SecurityConfiguration.java +++ b/spring-security-thymeleaf/src/main/java/com/baeldung/springsecuritythymeleaf/SecurityConfiguration.java @@ -1,11 +1,13 @@ package com.baeldung.springsecuritythymeleaf; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @@ -33,11 +35,16 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user") - .password("password") + .password(passwordEncoder().encode("password")) .roles("USER") .and() .withUser("admin") - .password("admin") + .password(passwordEncoder().encode("admin")) .roles("ADMIN"); } + + @Bean + public BCryptPasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } } diff --git a/spring-security-thymeleaf/src/main/resources/logback.xml b/spring-security-thymeleaf/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-thymeleaf/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/SpringSecurityThymeleafApplicationIntegrationTest.java b/spring-security-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/SpringSecurityThymeleafApplicationIntegrationTest.java new file mode 100644 index 0000000000..c852d05e73 --- /dev/null +++ b/spring-security-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/SpringSecurityThymeleafApplicationIntegrationTest.java @@ -0,0 +1,27 @@ +package com.baeldung.springsecuritythymeleaf; + +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringSecurityThymeleafApplicationIntegrationTest { + + @Autowired + ViewController viewController; + @Autowired + WebApplicationContext wac; + + @Test + public void whenConfigured_thenLoadsContext() { + assertNotNull(viewController); + assertNotNull(wac); + } + +} diff --git a/spring-security-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/SpringSecurityThymeleafApplicationTests.java b/spring-security-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/SpringSecurityThymeleafApplicationTests.java deleted file mode 100644 index dea254dd31..0000000000 --- a/spring-security-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/SpringSecurityThymeleafApplicationTests.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.springsecuritythymeleaf; - -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.context.WebApplicationContext; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class SpringSecurityThymeleafApplicationTests { - - @Autowired - ViewController viewController; - @Autowired - WebApplicationContext wac; - - @Test - public void whenConfigured_thenLoadsContext() { - assertNotNull(viewController); - assertNotNull(wac); - } - -} diff --git a/spring-security-x509/keystore/Makefile b/spring-security-x509/keystore/Makefile index 5321be9de3..63498fea76 100644 --- a/spring-security-x509/keystore/Makefile +++ b/spring-security-x509/keystore/Makefile @@ -85,4 +85,4 @@ add-client: clean: # Remove generated artifacts - find . ! -name Makefile -type f -exec rm -f {} \; + find . \( -name "$(CLIENTNAME)*" -o -name "$(HOSTNAME)*" -o -name "$(KEYSTORE)" -o -name "$(TRUSTSTORE)" -o -name ca.crt \) -type f -exec rm -f {} \; diff --git a/spring-security-x509/pom.xml b/spring-security-x509/pom.xml index 89fed39920..0cee3b3129 100644 --- a/spring-security-x509/pom.xml +++ b/spring-security-x509/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.baeldung spring-security-x509 @@ -9,10 +8,10 @@ pom - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-security-x509/spring-security-x509-basic-auth/pom.xml b/spring-security-x509/spring-security-x509-basic-auth/pom.xml index 67a7e29e6f..67f2b4fbcd 100644 --- a/spring-security-x509/spring-security-x509-basic-auth/pom.xml +++ b/spring-security-x509/spring-security-x509-basic-auth/pom.xml @@ -1,14 +1,12 @@ - + 4.0.0 - basic-secured-server + spring-security-x509-basic-auth 0.0.1-SNAPSHOT jar - - basic-secured-server + Spring Security x.509 Basic Authentication Spring x.509 Authentication Demo @@ -30,6 +28,7 @@ **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java diff --git a/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/logback.xml b/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-x509/spring-security-x509-client-auth/pom.xml b/spring-security-x509/spring-security-x509-client-auth/pom.xml index 7dd919973d..5cb4001a94 100644 --- a/spring-security-x509/spring-security-x509-client-auth/pom.xml +++ b/spring-security-x509/spring-security-x509-client-auth/pom.xml @@ -1,14 +1,12 @@ - + 4.0.0 - client-auth-server + spring-security-x509-client-auth 0.0.1-SNAPSHOT jar - - client-auth-server + Spring Security x.509 Client Authentication Spring x.509 Client Authentication Demo @@ -30,6 +28,7 @@ **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java @@ -57,6 +56,7 @@ **/*IntegrationTest.java + **/*IntTest.java diff --git a/spring-security-x509/spring-security-x509-client-auth/src/main/resources/logback.xml b/spring-security-x509/spring-security-x509-client-auth/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-x509/spring-security-x509-client-auth/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-session/README.md b/spring-session/README.md index 0d802a4715..30f70996cf 100644 --- a/spring-session/README.md +++ b/spring-session/README.md @@ -4,3 +4,4 @@ ### Relevant Articles: - [Introduction to Spring Session](http://www.baeldung.com/spring-session) +- [Spring Session with JDBC](http://www.baeldung.com/spring-session-jdbc) diff --git a/spring-session/pom.xml b/spring-session/pom.xml index c1c872ca74..28dde40272 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -1,35 +1,23 @@ - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + org.baeldung spring-session 1.0.0-SNAPSHOT - jar + + spring-session + pom - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 - - - org.springframework.boot - spring-boot-starter-data-redis - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.session - spring-session - - - org.springframework.boot - spring-boot-starter-web - - + + spring-session-jdbc + spring-session-redis + \ No newline at end of file diff --git a/spring-session/spring-session-jdbc/README.MD b/spring-session/spring-session-jdbc/README.MD new file mode 100644 index 0000000000..9293dfc953 --- /dev/null +++ b/spring-session/spring-session-jdbc/README.MD @@ -0,0 +1,6 @@ +This module is for Spring Session with JDBC tutorial. +Jira BAEL-1911 + +### Relevant Articles: + +- [Spring Session with JDBC](http://www.baeldung.com/spring-session-jdbc) diff --git a/spring-session/spring-session-jdbc/pom.xml b/spring-session/spring-session-jdbc/pom.xml new file mode 100644 index 0000000000..ce6b5f5908 --- /dev/null +++ b/spring-session/spring-session-jdbc/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + com.baeldung + spring-session-jdbc + 0.0.1-SNAPSHOT + jar + spring-session-jdbc + Spring Session with JDBC tutorial + + + 1.4.197 + + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.session + spring-session-jdbc + + + com.h2database + h2 + ${h2.version} + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + \ No newline at end of file diff --git a/spring-session/spring-session-jdbc/src/main/java/com/baeldung/springsessionjdbc/SpringSessionJdbcApplication.java b/spring-session/spring-session-jdbc/src/main/java/com/baeldung/springsessionjdbc/SpringSessionJdbcApplication.java new file mode 100644 index 0000000000..a3bc17aa49 --- /dev/null +++ b/spring-session/spring-session-jdbc/src/main/java/com/baeldung/springsessionjdbc/SpringSessionJdbcApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.springsessionjdbc; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringSessionJdbcApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringSessionJdbcApplication.class, args); + } +} diff --git a/spring-session/spring-session-jdbc/src/main/java/com/baeldung/springsessionjdbc/controller/SpringSessionJdbcController.java b/spring-session/spring-session-jdbc/src/main/java/com/baeldung/springsessionjdbc/controller/SpringSessionJdbcController.java new file mode 100644 index 0000000000..509a5f292b --- /dev/null +++ b/spring-session/spring-session-jdbc/src/main/java/com/baeldung/springsessionjdbc/controller/SpringSessionJdbcController.java @@ -0,0 +1,45 @@ +package com.baeldung.springsessionjdbc.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import java.util.ArrayList; +import java.util.List; + +@Controller +public class SpringSessionJdbcController { + + @GetMapping("/") + public String index(Model model, HttpSession session) { + List favoriteColors = getFavColors(session); + model.addAttribute("favoriteColors", favoriteColors); + model.addAttribute("sessionId", session.getId()); + return "index"; + } + + @PostMapping("/saveColor") + public String saveMessage(@RequestParam("color") String color, HttpServletRequest request) { + List favoriteColors = getFavColors(request.getSession()); + if (!StringUtils.isEmpty(color)) { + favoriteColors.add(color); + request + .getSession() + .setAttribute("favoriteColors", favoriteColors); + } + return "redirect:/"; + } + + private List getFavColors(HttpSession session) { + List favoriteColors = (List) session.getAttribute("favoriteColors"); + if (favoriteColors == null) { + favoriteColors = new ArrayList<>(); + } + return favoriteColors; + } +} diff --git a/spring-session/spring-session-jdbc/src/main/resources/application.properties b/spring-session/spring-session-jdbc/src/main/resources/application.properties new file mode 100644 index 0000000000..119638de31 --- /dev/null +++ b/spring-session/spring-session-jdbc/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.session.store-type=jdbc +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console \ No newline at end of file diff --git a/spring-session/spring-session-jdbc/src/main/resources/logback.xml b/spring-session/spring-session-jdbc/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-session/spring-session-jdbc/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-session/spring-session-jdbc/src/test/java/com/baeldung/springsessionjdbc/SpringSessionJdbcIntegrationTest.java b/spring-session/spring-session-jdbc/src/test/java/com/baeldung/springsessionjdbc/SpringSessionJdbcIntegrationTest.java new file mode 100644 index 0000000000..2dcc0b3af8 --- /dev/null +++ b/spring-session/spring-session-jdbc/src/test/java/com/baeldung/springsessionjdbc/SpringSessionJdbcIntegrationTest.java @@ -0,0 +1,91 @@ +package com.baeldung.springsessionjdbc; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +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.boot.web.server.LocalServerPort; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectInputStream; +import java.sql.*; +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class SpringSessionJdbcIntegrationTest { + + @LocalServerPort + private int port; + + @Autowired + private TestRestTemplate testRestTemplate; + + @Before + public void setup() throws ClassNotFoundException { + Class.forName("org.h2.Driver"); + } + + @Test + public void givenApiHasStarted_whenH2DbIsQueried_thenSessionTablesAreEmpty() throws SQLException { + Assert.assertEquals(0, getSessionIdsFromDatabase().size()); + Assert.assertEquals(0, getSessionAttributeBytesFromDatabase().size()); + } + + @Test + public void givenGetInvoked_whenH2DbIsQueried_thenOneSessionIsCreated() throws SQLException { + assertThat(this.testRestTemplate.getForObject("http://localhost:" + port + "/", String.class)).isNotEmpty(); + Assert.assertEquals(1, getSessionIdsFromDatabase().size()); + } + + @Test + public void givenPostInvoked_whenH2DbIsQueried_thenSessionAttributeIsRetrieved() throws ClassNotFoundException, SQLException, IOException { + MultiValueMap map = new LinkedMultiValueMap<>(); + map.add("color", "red"); + this.testRestTemplate.postForObject("http://localhost:" + port + "/saveColor", map, String.class); + List queryResponse = getSessionAttributeBytesFromDatabase(); + Assert.assertEquals(1, queryResponse.size()); + ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(queryResponse.get(0))); + List obj = (List) in.readObject(); //Deserialize byte[] to object + Assert.assertEquals("red", obj.get(0)); + } + + private List getSessionIdsFromDatabase() throws SQLException { + List result = new ArrayList<>(); + ResultSet rs = getResultSet("SELECT * FROM SPRING_SESSION"); + while (rs.next()) { + result.add(rs.getString("SESSION_ID")); + } + return result; + } + + private List getSessionAttributeBytesFromDatabase() throws SQLException { + List result = new ArrayList<>(); + ResultSet rs = getResultSet("SELECT * FROM SPRING_SESSION_ATTRIBUTES"); + while (rs.next()) { + result.add(rs.getBytes("ATTRIBUTE_BYTES")); + } + return result; + } + + private ResultSet getResultSet(String sql) throws SQLException { + Connection conn = DriverManager.getConnection("jdbc:h2:mem:testdb", "sa", ""); + Statement stat = conn.createStatement(); + return stat.executeQuery(sql); + } + +} diff --git a/spring-session/spring-session-redis/README.md b/spring-session/spring-session-redis/README.md new file mode 100644 index 0000000000..0d802a4715 --- /dev/null +++ b/spring-session/spring-session-redis/README.md @@ -0,0 +1,6 @@ +========= + +## Spring Session Examples + +### Relevant Articles: +- [Introduction to Spring Session](http://www.baeldung.com/spring-session) diff --git a/spring-session/spring-session-redis/pom.xml b/spring-session/spring-session-redis/pom.xml new file mode 100644 index 0000000000..00da656226 --- /dev/null +++ b/spring-session/spring-session-redis/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + spring-session-redis + 1.0.0-SNAPSHOT + jar + + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-1 + + + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.session + spring-session + + + org.springframework.boot + spring-boot-starter-web + + + com.github.kstyrc + embedded-redis + ${embedded-redis.version} + + + + + 0.6 + + + \ No newline at end of file diff --git a/spring-session/src/main/java/com/baeldung/spring/session/SecurityConfig.java b/spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SecurityConfig.java similarity index 100% rename from spring-session/src/main/java/com/baeldung/spring/session/SecurityConfig.java rename to spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SecurityConfig.java diff --git a/spring-session/src/main/java/com/baeldung/spring/session/SessionConfig.java b/spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SessionConfig.java similarity index 100% rename from spring-session/src/main/java/com/baeldung/spring/session/SessionConfig.java rename to spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SessionConfig.java diff --git a/spring-session/src/main/java/com/baeldung/spring/session/SessionController.java b/spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SessionController.java similarity index 100% rename from spring-session/src/main/java/com/baeldung/spring/session/SessionController.java rename to spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SessionController.java diff --git a/spring-session/src/main/java/com/baeldung/spring/session/SessionWebApplication.java b/spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SessionWebApplication.java similarity index 100% rename from spring-session/src/main/java/com/baeldung/spring/session/SessionWebApplication.java rename to spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SessionWebApplication.java diff --git a/spring-session/spring-session-redis/src/main/resources/application.properties b/spring-session/spring-session-redis/src/main/resources/application.properties new file mode 100644 index 0000000000..49886b3b70 --- /dev/null +++ b/spring-session/spring-session-redis/src/main/resources/application.properties @@ -0,0 +1,2 @@ +spring.redis.host=localhost +spring.redis.port=6379 \ No newline at end of file diff --git a/spring-session/spring-session-redis/src/main/resources/logback.xml b/spring-session/spring-session-redis/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-session/spring-session-redis/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-session/spring-session-redis/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java b/spring-session/spring-session-redis/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java new file mode 100644 index 0000000000..f739aeb3ab --- /dev/null +++ b/spring-session/spring-session-redis/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java @@ -0,0 +1,92 @@ +package com.baeldung.spring.session; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.Set; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + +import redis.clients.jedis.Jedis; +import redis.embedded.RedisServer; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SessionWebApplication.class, webEnvironment = WebEnvironment.DEFINED_PORT) +public class SessionControllerIntegrationTest { + + private Jedis jedis; + private static RedisServer redisServer; + private TestRestTemplate testRestTemplate; + private TestRestTemplate testRestTemplateWithAuth; + private String testUrl = "http://localhost:8080/"; + + @BeforeClass + public static void startRedisServer() throws IOException { + redisServer = new RedisServer(6379); + redisServer.start(); + } + + @AfterClass + public static void stopRedisServer() throws IOException { + redisServer.stop(); + } + + @Before + public void clearRedisData() { + + testRestTemplate = new TestRestTemplate(); + testRestTemplateWithAuth = new TestRestTemplate("admin", "password"); + + jedis = new Jedis("localhost", 6379); + jedis.flushAll(); + } + + @Test + public void testRedisIsEmpty() { + Set result = jedis.keys("*"); + assertEquals(0, result.size()); + } + + @Test + public void testUnauthenticatedCantAccess() { + ResponseEntity result = testRestTemplate.getForEntity(testUrl, String.class); + assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); + } + + @Test + public void testRedisControlsSession() { + ResponseEntity result = testRestTemplateWithAuth.getForEntity(testUrl, String.class); + assertEquals("hello admin", result.getBody()); // login worked + + Set redisResult = jedis.keys("*"); + assertTrue(redisResult.size() > 0); // redis is populated with session data + + String sessionCookie = result.getHeaders().get("Set-Cookie").get(0).split(";")[0]; + HttpHeaders headers = new HttpHeaders(); + headers.add("Cookie", sessionCookie); + HttpEntity httpEntity = new HttpEntity<>(headers); + + result = testRestTemplate.exchange(testUrl, HttpMethod.GET, httpEntity, String.class); + assertEquals("hello admin", result.getBody()); // access with session works worked + + jedis.flushAll(); // clear all keys in redis + + result = testRestTemplate.exchange(testUrl, HttpMethod.GET, httpEntity, String.class); + assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());// access denied after sessions are removed in redis + + } +} \ No newline at end of file diff --git a/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java b/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java deleted file mode 100644 index 84dd2bc139..0000000000 --- a/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.spring.session; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.*; -import redis.clients.jedis.Jedis; - -import java.util.Set; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class SessionControllerIntegrationTest { - - private Jedis jedis; - private TestRestTemplate testRestTemplate; - private TestRestTemplate testRestTemplateWithAuth; - private String testUrl = "http://localhost:8080/"; - - @Before - public void clearRedisData() { - testRestTemplate = new TestRestTemplate(); - testRestTemplateWithAuth = new TestRestTemplate("admin", "password", null); - - jedis = new Jedis("localhost", 6379); - jedis.flushAll(); - } - - @Test - public void testRedisIsEmpty() { - Set result = jedis.keys("*"); - assertEquals(0, result.size()); - } - - @Test - public void testUnauthenticatedCantAccess() { - ResponseEntity result = testRestTemplate.getForEntity(testUrl, String.class); - assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); - } - - @Test - public void testRedisControlsSession() { - ResponseEntity result = testRestTemplateWithAuth.getForEntity(testUrl, String.class); - assertEquals("hello admin", result.getBody()); // login worked - - Set redisResult = jedis.keys("*"); - assertTrue(redisResult.size() > 0); // redis is populated with session data - - String sessionCookie = result.getHeaders().get("Set-Cookie").get(0).split(";")[0]; - HttpHeaders headers = new HttpHeaders(); - headers.add("Cookie", sessionCookie); - HttpEntity httpEntity = new HttpEntity<>(headers); - - result = testRestTemplate.exchange(testUrl, HttpMethod.GET, httpEntity, String.class); - assertEquals("hello admin", result.getBody()); // access with session works worked - - jedis.flushAll(); // clear all keys in redis - - result = testRestTemplate.exchange(testUrl, HttpMethod.GET, httpEntity, String.class); - assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());// access denied after sessions are removed in redis - - } -} \ No newline at end of file diff --git a/spring-sleuth/pom.xml b/spring-sleuth/pom.xml index 2fee474dbe..a9a8d3e96e 100644 --- a/spring-sleuth/pom.xml +++ b/spring-sleuth/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-sleuth @@ -8,10 +8,10 @@ jar - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-sleuth/src/main/resources/logback.xml b/spring-sleuth/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-sleuth/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-social-login/pom.xml b/spring-social-login/pom.xml index d2e9497bcf..6b7b90443a 100644 --- a/spring-social-login/pom.xml +++ b/spring-social-login/pom.xml @@ -1,15 +1,16 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + spring-social-login spring-social-login war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-social-login/src/main/resources/logback.xml b/spring-social-login/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-social-login/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-spel/pom.xml b/spring-spel/pom.xml index 8e805ed6ac..4af318fde2 100644 --- a/spring-spel/pom.xml +++ b/spring-spel/pom.xml @@ -1,10 +1,11 @@ + 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 - spel + spring-spel 1.0-SNAPSHOT + Spring SpEL com.baeldung diff --git a/spring-spel/src/main/resources/logback.xml b/spring-spel/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-spel/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-state-machine/pom.xml b/spring-state-machine/pom.xml index 2755b6e45a..5d15e4dfad 100644 --- a/spring-state-machine/pom.xml +++ b/spring-state-machine/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-state-machine diff --git a/spring-state-machine/src/main/resources/logback.xml b/spring-state-machine/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-state-machine/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/handling-spring-static-resources/README.md b/spring-static-resources/README.md similarity index 100% rename from handling-spring-static-resources/README.md rename to spring-static-resources/README.md diff --git a/spring-static-resources/pom.xml b/spring-static-resources/pom.xml new file mode 100644 index 0000000000..3ca7783682 --- /dev/null +++ b/spring-static-resources/pom.xml @@ -0,0 +1,212 @@ + + + 4.0.0 + com.baeldung + spring-static-resources + 0.1.0-SNAPSHOT + war + spring-static-resources + + + com.baeldung + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 + + + + + + org.springframework.security + spring-security-web + ${org.springframework.security.version} + + + org.springframework.security + spring-security-config + ${org.springframework.security.version} + + + org.springframework.security + spring-security-taglibs + ${org.springframework.security.version} + + + + + org.springframework + spring-core + ${spring.version} + + + commons-logging + commons-logging + + + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-jdbc + ${spring.version} + + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-aop + ${spring.version} + + + org.springframework + spring-tx + ${spring.version} + + + org.springframework + spring-expression + ${spring.version} + + + + org.springframework + spring-web + ${spring.version} + + + org.springframework + spring-webmvc + ${spring.version} + + + + + org.aspectj + aspectjrt + ${org.aspectj-version} + + + javax.inject + javax.inject + ${inject.version} + + + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + + + javax.servlet.jsp + javax.servlet.jsp-api + ${javax.servlet.jsp-api.version} + + + javax.servlet + jstl + ${jstl.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + + + + + joda-time + joda-time + ${joda-time.version} + + + + + com.github.jknack + handlebars + ${handlebars.version} + + + + + spring-static-resources + + + src/main/resources + true + + + + + net.alchim31.maven + yuicompressor-maven-plugin + ${yuicompressor-maven-plugin.version} + + + + compress + + + + + true + ${project.build.directory}/min + + **/*.min.js + **/handlebars-3133af2.js + **/require.js + + + + + org.apache.maven.plugins + maven-war-plugin + 3.2.2 + + + + ${project.build.directory}/min + + + + + + + + + + 5.0.6.RELEASE + + 1.8.9 + 2.3.2-b02 + + + 2.9.6 + + + 6.0.10.Final + 4.1.0 + 2.10 + 1.2 + 4.0.1 + 1 + + + 1.5.1 + + + \ No newline at end of file diff --git a/handling-spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java similarity index 100% rename from handling-spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java rename to spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java diff --git a/handling-spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java b/spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java similarity index 100% rename from handling-spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java rename to spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java diff --git a/spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java new file mode 100644 index 0000000000..dbc548e028 --- /dev/null +++ b/spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java @@ -0,0 +1,104 @@ +package org.baeldung.spring; + +import java.util.Locale; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.MessageSource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.ReloadableResourceBundleMessageSource; +import org.springframework.core.env.Environment; +import org.springframework.web.servlet.LocaleResolver; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.i18n.CookieLocaleResolver; +import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; +import org.springframework.web.servlet.resource.GzipResourceResolver; +import org.springframework.web.servlet.resource.PathResourceResolver; +import org.springframework.web.servlet.resource.ResourceUrlEncodingFilter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +@Configuration +@ComponentScan(basePackages = { "org.baeldung.web.controller", "org.baeldung.persistence.service", "org.baeldung.persistence.dao" }) +@EnableWebMvc +public class MvcConfig implements WebMvcConfigurer { + @Autowired + Environment env; + + public MvcConfig() { + super(); + } + + // API + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/login.html"); + registry.addViewController("/home.html"); + + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + return bean; + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + // For examples using Spring 4.1.0 + if ((env.getProperty("resource.handler.conf")).equals("4.1.0")) { + registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(3600).resourceChain(true).addResolver(new GzipResourceResolver()).addResolver(new PathResourceResolver()); + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/", "classpath:/other-resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver()); + registry.addResourceHandler("/files/**").addResourceLocations("file:/Users/Elena/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver()); + registry.addResourceHandler("/other-files/**").addResourceLocations("file:/Users/Elena/").setCachePeriod(3600).resourceChain(true).addResolver(new GzipResourceResolver()); + } + // For examples using Spring 4.0.7 + else if ((env.getProperty("resource.handler.conf")).equals("4.0.7")) { + registry.addResourceHandler("/resources/**").addResourceLocations("/", "/resources/", "classpath:/other-resources/"); + registry.addResourceHandler("/files/**").addResourceLocations("file:/Users/Elena/"); + + } + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); + localeChangeInterceptor.setParamName("lang"); + registry.addInterceptor(localeChangeInterceptor); + } + + @Bean + public ResourceUrlEncodingFilter resourceUrlEncodingFilter() { + ResourceUrlEncodingFilter filter = new ResourceUrlEncodingFilter(); + + return filter; + } + + @Bean + public LocaleResolver localeResolver() { + CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver(); + cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH); + return cookieLocaleResolver; + } + + @Bean + public MessageSource messageSource() { + ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); + messageSource.setBasename("classpath:messages"); + messageSource.setUseCodeAsDefaultMessage(true); + messageSource.setDefaultEncoding("UTF-8"); + messageSource.setCacheSeconds(0); + return messageSource; + } + +} \ No newline at end of file diff --git a/handling-spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java similarity index 100% rename from handling-spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java rename to spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java diff --git a/handling-spring-static-resources/src/main/java/org/baeldung/web/controller/HomeController.java b/spring-static-resources/src/main/java/org/baeldung/web/controller/HomeController.java similarity index 100% rename from handling-spring-static-resources/src/main/java/org/baeldung/web/controller/HomeController.java rename to spring-static-resources/src/main/java/org/baeldung/web/controller/HomeController.java diff --git a/handling-spring-static-resources/src/main/resources/application.properties b/spring-static-resources/src/main/resources/application.properties similarity index 100% rename from handling-spring-static-resources/src/main/resources/application.properties rename to spring-static-resources/src/main/resources/application.properties diff --git a/spring-static-resources/src/main/resources/logback.xml b/spring-static-resources/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/spring-static-resources/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/handling-spring-static-resources/src/main/resources/messages_en.properties b/spring-static-resources/src/main/resources/messages_en.properties similarity index 100% rename from handling-spring-static-resources/src/main/resources/messages_en.properties rename to spring-static-resources/src/main/resources/messages_en.properties diff --git a/handling-spring-static-resources/src/main/resources/messages_es_ES.properties b/spring-static-resources/src/main/resources/messages_es_ES.properties similarity index 100% rename from handling-spring-static-resources/src/main/resources/messages_es_ES.properties rename to spring-static-resources/src/main/resources/messages_es_ES.properties diff --git a/spring-static-resources/src/main/resources/webSecurityConfig.xml b/spring-static-resources/src/main/resources/webSecurityConfig.xml new file mode 100644 index 0000000000..ea64ad5aea --- /dev/null +++ b/spring-static-resources/src/main/resources/webSecurityConfig.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/Hello.html b/spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/Hello.html similarity index 100% rename from handling-spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/Hello.html rename to spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/Hello.html diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/bootstrap.css b/spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/bootstrap.css similarity index 100% rename from handling-spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/bootstrap.css rename to spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/bootstrap.css diff --git a/spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml new file mode 100644 index 0000000000..c046aa16a9 --- /dev/null +++ b/spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml @@ -0,0 +1,9 @@ + + + + + diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/view/home.jsp b/spring-static-resources/src/main/webapp/WEB-INF/view/home.jsp similarity index 100% rename from handling-spring-static-resources/src/main/webapp/WEB-INF/view/home.jsp rename to spring-static-resources/src/main/webapp/WEB-INF/view/home.jsp diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp b/spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp similarity index 100% rename from handling-spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp rename to spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp diff --git a/spring-static-resources/src/main/webapp/WEB-INF/web.xml b/spring-static-resources/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..4bb60e4f2c --- /dev/null +++ b/spring-static-resources/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,48 @@ + + + + + contextClass + + org.springframework.web.context.support.AnnotationConfigWebApplicationContext + + + + contextConfigLocation + org.baeldung.spring + + + + org.springframework.web.context.ContextLoaderListener + + + + mvc + org.springframework.web.servlet.DispatcherServlet + 1 + + + mvc + / + + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + springSecurityFilterChain + /* + + + localizationFilter + org.springframework.web.filter.RequestContextFilter + + + localizationFilter + /* + + + \ No newline at end of file diff --git a/handling-spring-static-resources/src/main/webapp/js/bootstrap.css b/spring-static-resources/src/main/webapp/js/bootstrap.css similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/bootstrap.css rename to spring-static-resources/src/main/webapp/js/bootstrap.css diff --git a/handling-spring-static-resources/src/main/webapp/js/foo.js b/spring-static-resources/src/main/webapp/js/foo.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/foo.js rename to spring-static-resources/src/main/webapp/js/foo.js diff --git a/handling-spring-static-resources/src/main/webapp/js/handlebars-3133af2.js b/spring-static-resources/src/main/webapp/js/handlebars-3133af2.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/handlebars-3133af2.js rename to spring-static-resources/src/main/webapp/js/handlebars-3133af2.js diff --git a/handling-spring-static-resources/src/main/webapp/js/helpers/utils.js b/spring-static-resources/src/main/webapp/js/helpers/utils.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/helpers/utils.js rename to spring-static-resources/src/main/webapp/js/helpers/utils.js diff --git a/handling-spring-static-resources/src/main/webapp/js/jquery-1.11.1.min.js b/spring-static-resources/src/main/webapp/js/jquery-1.11.1.min.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/jquery-1.11.1.min.js rename to spring-static-resources/src/main/webapp/js/jquery-1.11.1.min.js diff --git a/handling-spring-static-resources/src/main/webapp/js/main.js b/spring-static-resources/src/main/webapp/js/main.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/main.js rename to spring-static-resources/src/main/webapp/js/main.js diff --git a/handling-spring-static-resources/src/main/webapp/js/require.gz b/spring-static-resources/src/main/webapp/js/require.gz similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/require.gz rename to spring-static-resources/src/main/webapp/js/require.gz diff --git a/handling-spring-static-resources/src/main/webapp/js/require.js b/spring-static-resources/src/main/webapp/js/require.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/require.js rename to spring-static-resources/src/main/webapp/js/require.js diff --git a/handling-spring-static-resources/src/main/webapp/js/router.js b/spring-static-resources/src/main/webapp/js/router.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/router.js rename to spring-static-resources/src/main/webapp/js/router.js diff --git a/handling-spring-static-resources/src/main/webapp/other-resources/Hello.html b/spring-static-resources/src/main/webapp/other-resources/Hello.html similarity index 100% rename from handling-spring-static-resources/src/main/webapp/other-resources/Hello.html rename to spring-static-resources/src/main/webapp/other-resources/Hello.html diff --git a/handling-spring-static-resources/src/main/webapp/other-resources/bootstrap.css b/spring-static-resources/src/main/webapp/other-resources/bootstrap.css similarity index 100% rename from handling-spring-static-resources/src/main/webapp/other-resources/bootstrap.css rename to spring-static-resources/src/main/webapp/other-resources/bootstrap.css diff --git a/handling-spring-static-resources/src/main/webapp/other-resources/foo.js b/spring-static-resources/src/main/webapp/other-resources/foo.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/other-resources/foo.js rename to spring-static-resources/src/main/webapp/other-resources/foo.js diff --git a/handling-spring-static-resources/src/main/webapp/resources/bootstrap.css b/spring-static-resources/src/main/webapp/resources/bootstrap.css similarity index 100% rename from handling-spring-static-resources/src/main/webapp/resources/bootstrap.css rename to spring-static-resources/src/main/webapp/resources/bootstrap.css diff --git a/handling-spring-static-resources/src/main/webapp/resources/myCss.css b/spring-static-resources/src/main/webapp/resources/myCss.css similarity index 100% rename from handling-spring-static-resources/src/main/webapp/resources/myCss.css rename to spring-static-resources/src/main/webapp/resources/myCss.css diff --git a/spring-swagger-codegen/pom.xml b/spring-swagger-codegen/pom.xml index 09b7b61156..d14dcc3176 100644 --- a/spring-swagger-codegen/pom.xml +++ b/spring-swagger-codegen/pom.xml @@ -1,5 +1,5 @@ + 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-swagger-codegen diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/README.md b/spring-swagger-codegen/spring-swagger-codegen-api-client/README.md index b1b7a63a9c..455a69b2f3 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/README.md +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/README.md @@ -153,3 +153,5 @@ It's recommended to create an instance of `ApiClient` per thread in a multithrea apiteam@swagger.io + + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml index f0f58b86b8..0f1cfa27ac 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml @@ -1,26 +1,17 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 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 - - com.baeldung - spring-swagger-codegen - 0.0.1-SNAPSHOT - 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 - @@ -29,7 +20,6 @@ repo - Swagger @@ -39,12 +29,19 @@ + + com.baeldung + spring-swagger-codegen + 0.0.1-SNAPSHOT + ../../spring-swagger-codegen + + org.apache.maven.plugins maven-surefire-plugin - 2.12 + ${maven-surefire-plugin.version} @@ -57,26 +54,12 @@ pertest - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory}/lib - - - - org.apache.maven.plugins maven-jar-plugin - 2.2 + ${maven-jar-plugin.version} @@ -92,7 +75,7 @@ org.codehaus.mojo build-helper-maven-plugin - 1.10 + ${build-helper-maven-plugin.version} add_sources @@ -123,7 +106,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 2.10.4 + ${maven-javadoc-plugin.version} attach-javadocs @@ -136,7 +119,7 @@ org.apache.maven.plugins maven-source-plugin - 2.2.1 + ${maven-source-plugin.version} attach-sources @@ -157,7 +140,7 @@ org.apache.maven.plugins maven-gpg-plugin - 1.5 + ${maven-gpg-plugin.version} sign-artifacts @@ -218,22 +201,17 @@ 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 + 2.2 + 1.5 + 2.2.1 + 2.10.4 + 1.10 diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/resources/logback.xml b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiLiveTest.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiLiveTest.java new file mode 100644 index 0000000000..42be6b950b --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiLiveTest.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 PetApiLiveTest { + + 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/PetApiTest.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java deleted file mode 100644 index 0b94027df0..0000000000 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * 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/StoreApiLiveTest.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiLiveTest.java new file mode 100644 index 0000000000..be0cb8030d --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiLiveTest.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 StoreApiLiveTest { + + 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/StoreApiTest.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java deleted file mode 100644 index ce332bee0d..0000000000 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * 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/UserApiLiveTest.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiLiveTest.java new file mode 100644 index 0000000000..5dae1430a0 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiLiveTest.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 UserApiLiveTest { + + 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-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 deleted file mode 100644 index 59e7a39679..0000000000 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiTest.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * 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 index c9e0f5e27f..281ed59857 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml @@ -1,41 +1,44 @@ + 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-swagger-codegen-app 0.0.1-SNAPSHOT - + - org.springframework.boot - spring-boot-starter-parent - 1.5.10.RELEASE + com.baeldung + spring-swagger-codegen + 0.0.1-SNAPSHOT + ../../spring-swagger-codegen com.baeldung spring-swagger-codegen-api-client - 0.0.1-SNAPSHOT + ${spring-swagger-codegen-api-client.version} org.springframework.boot spring-boot-starter-web + ${spring.version} - - 1.8 - - - org.springframework.boot spring-boot-maven-plugin + ${spring.version} - \ No newline at end of file + + 1.8 + 0.0.1-SNAPSHOT + 1.5.10.RELEASE + + diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/src/main/resources/logback.xml b/spring-swagger-codegen/spring-swagger-codegen-app/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-app/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md index 9346b74c89..f9e7dd90a7 100644 --- a/spring-thymeleaf/README.md +++ b/spring-thymeleaf/README.md @@ -14,6 +14,10 @@ - [Working with Fragments in Thymeleaf](http://www.baeldung.com/spring-thymeleaf-fragments) - [Conditionals in Thymeleaf](http://www.baeldung.com/spring-thymeleaf-conditionals) - [Iteration in Thymeleaf](http://www.baeldung.com/thymeleaf-iteration) +- [Working With Arrays in Thymeleaf](http://www.baeldung.com/thymeleaf-arrays) +- [Spring with Thymeleaf Pagination for a List](http://www.baeldung.com/spring-thymeleaf-pagination) +- [Working with Select and Option in Thymeleaf](http://www.baeldung.com/thymeleaf-select-option) +- [Working With Custom HTML Attributes in Thymeleaf](https://www.baeldung.com/thymeleaf-custom-html-attributes) ### Build the Project diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index d13356b3d7..0926728aba 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -1,5 +1,5 @@ + 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-thymeleaf @@ -8,8 +8,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 @@ -17,7 +18,7 @@ org.springframework spring-context - ${org.springframework-version} + ${spring.version} @@ -29,19 +30,38 @@ org.springframework spring-webmvc - ${org.springframework-version} + ${spring.version} + + + org.springframework.data + spring-data-commons + ${spring-data.version} + + + + javax.validation + validation-api + ${javax.validation-version} + + + org.hibernate.validator + hibernate-validator + ${hibernate-validator.version} + + org.springframework.security spring-security-web - ${springframework-security.version} + ${spring-security.version} org.springframework.security spring-security-config - ${springframework-security.version} + ${spring-security.version} + org.thymeleaf @@ -50,10 +70,9 @@ org.thymeleaf - thymeleaf-spring4 + thymeleaf-spring5 ${org.thymeleaf-version} - nz.net.ultraq.thymeleaf thymeleaf-layout-dialect @@ -64,40 +83,30 @@ thymeleaf-extras-java8time ${org.thymeleaf.extras-version} + javax.servlet javax.servlet-api - ${javax.servlet-version} + ${javax.servlet-api.version} provided - - - javax.validation - validation-api - ${javax.validation-version} - - - org.hibernate - hibernate-validator - ${hibernate-validator.version} - - + org.springframework spring-test - ${org.springframework-version} + ${spring.version} test - org.springframework.security spring-security-test - ${springframework-security.version} + ${spring-security.version} test + @@ -110,6 +119,7 @@ false + org.codehaus.cargo cargo-maven2-plugin @@ -117,7 +127,7 @@ true - jetty8x + jetty9x embedded @@ -129,6 +139,7 @@ + org.apache.tomcat.maven tomcat7-maven-plugin @@ -153,24 +164,16 @@ - 1.8 - - 4.3.4.RELEASE - 4.2.0.RELEASE - 3.1.0 - + 2.0.9.RELEASE 3.0.9.RELEASE - 3.0.0.RELEASE - 2.1.2 - - 1.1.0.Final - 5.3.3.Final - 5.2.5.Final + 3.0.1.RELEASE + 2.3.0 + 2.0.1.Final + 6.0.11.Final - 2.6 1.6.1 2.2 - \ No newline at end of file + diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/WorkingWithArraysInThymeleafApplication.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/WorkingWithArraysInThymeleafApplication.java new file mode 100644 index 0000000000..bce0660fda --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/WorkingWithArraysInThymeleafApplication.java @@ -0,0 +1,12 @@ +// package com.baeldung.thymeleaf; + +// import org.springframework.boot.SpringApplication; +// import org.springframework.boot.autoconfigure.SpringBootApplication; + +// @SpringBootApplication +// public class WorkingWithArraysInThymeleafApplication { + +// public static void main(String[] args) { +// SpringApplication.run(WorkingWithArraysInThymeleafApplication.class, args); +// } +// } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java index 2e76877199..34a59ea391 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java @@ -2,6 +2,9 @@ package com.baeldung.thymeleaf.config; import java.util.Locale; +import nz.net.ultraq.thymeleaf.LayoutDialect; +import nz.net.ultraq.thymeleaf.decorators.strategies.GroupingStrategy; + import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; @@ -15,23 +18,20 @@ import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.i18n.SessionLocaleResolver; -import org.thymeleaf.TemplateEngine; import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect; -import org.thymeleaf.spring4.SpringTemplateEngine; -import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; -import org.thymeleaf.spring4.view.ThymeleafViewResolver; +import org.thymeleaf.spring5.ISpringTemplateEngine; +import org.thymeleaf.spring5.SpringTemplateEngine; +import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver; +import org.thymeleaf.spring5.view.ThymeleafViewResolver; import org.thymeleaf.templatemode.TemplateMode; import org.thymeleaf.templateresolver.ITemplateResolver; import com.baeldung.thymeleaf.formatter.NameFormatter; import com.baeldung.thymeleaf.utils.ArrayUtil; -import nz.net.ultraq.thymeleaf.LayoutDialect; -import nz.net.ultraq.thymeleaf.decorators.strategies.GroupingStrategy; - @Configuration @EnableWebMvc @ComponentScan({ "com.baeldung.thymeleaf" }) @@ -39,10 +39,11 @@ import nz.net.ultraq.thymeleaf.decorators.strategies.GroupingStrategy; * Java configuration file that is used for Spring MVC and Thymeleaf * configurations */ -public class WebMVCConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware { +public class WebMVCConfig implements WebMvcConfigurer, ApplicationContextAware { private ApplicationContext applicationContext; + @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @@ -77,7 +78,7 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application return resolver; } - private TemplateEngine templateEngine(ITemplateResolver templateResolver) { + private ISpringTemplateEngine templateEngine(ITemplateResolver templateResolver) { SpringTemplateEngine engine = new SpringTemplateEngine(); engine.addDialect(new LayoutDialect(new GroupingStrategy())); engine.addDialect(new Java8TimeDialect()); diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java index 46bff38a3f..ea51ca3cd9 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java @@ -27,7 +27,7 @@ public class WebMVCSecurity extends WebSecurityConfigurerAdapter { @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER"); + auth.inMemoryAuthentication().withUser("user1").password("{noop}user1Pass").authorities("ROLE_USER"); } @Override diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BookController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BookController.java new file mode 100644 index 0000000000..b8132cddc8 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BookController.java @@ -0,0 +1,49 @@ +package com.baeldung.thymeleaf.controller; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; + +import com.baeldung.thymeleaf.model.Book; +import com.baeldung.thymeleaf.service.BookService; + +@Controller +public class BookController { + + private static int currentPage = 1; + private static int pageSize = 5; + + @Autowired + private BookService bookService; + + @RequestMapping(value = "/listBooks", method = RequestMethod.GET) + public String listBooks(Model model, @RequestParam("page") Optional page, @RequestParam("size") Optional size) { + page.ifPresent(p -> currentPage = p); + size.ifPresent(s -> pageSize = s); + + Page bookPage = bookService.findPaginated(PageRequest.of(currentPage - 1, pageSize)); + + model.addAttribute("bookPage", bookPage); + + int totalPages = bookPage.getTotalPages(); + if (totalPages > 0) { + List pageNumbers = IntStream.rangeClosed(1, totalPages) + .boxed() + .collect(Collectors.toList()); + model.addAttribute("pageNumbers", pageNumbers); + } + + return "listBooks.html"; + } +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/CourseRegistrationController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/CourseRegistrationController.java new file mode 100644 index 0000000000..2d2b5906e1 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/CourseRegistrationController.java @@ -0,0 +1,30 @@ +package com.baeldung.thymeleaf.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import com.baeldung.thymeleaf.model.Course; + +/** + * Handles requests for the student model. + * + */ +@Controller +public class CourseRegistrationController { + + @RequestMapping(value = "/registerCourse", method = RequestMethod.POST) + public String register(@ModelAttribute Course course, Model model) { + model.addAttribute("successMessage", "You have successfully registered for course: " + course.getName() + "."); + return "courseRegistration.html"; + } + + @RequestMapping(value = "/registerCourse", method = RequestMethod.GET) + public String register(Model model) { + model.addAttribute("course", new Course()); + return "courseRegistration.html"; + } + +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ThymeleafArrayController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ThymeleafArrayController.java new file mode 100644 index 0000000000..8276cc4376 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ThymeleafArrayController.java @@ -0,0 +1,17 @@ +package com.baeldung.thymeleaf.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class ThymeleafArrayController { + @GetMapping("/arrays") + public String arrayController(Model model) { + String[] continents = {"Africa", "Antarctica", "Asia", "Australia", "Europe", "North America", "Sourth America"}; + + model.addAttribute("continents", continents); + + return "continents"; + } +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Book.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Book.java new file mode 100644 index 0000000000..0203231175 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Book.java @@ -0,0 +1,29 @@ +package com.baeldung.thymeleaf.model; + +public class Book { + private int id; + private String name; + + public Book(int id, String name) { + super(); + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Course.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Course.java new file mode 100644 index 0000000000..df2e9cd097 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Course.java @@ -0,0 +1,52 @@ +package com.baeldung.thymeleaf.model; + +import java.util.Date; + +public class Course { + + private String name; + private String description; + private Date startDate; + private Date endDate; + private String teacher; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public Date getEndDate() { + return endDate; + } + + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + + public String getTeacher() { + return teacher; + } + + public void setTeacher(String teacher) { + this.teacher = teacher; + } +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Page.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Page.java new file mode 100644 index 0000000000..e9dd0a8135 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Page.java @@ -0,0 +1,61 @@ +package com.baeldung.thymeleaf.model; + +import java.util.Collections; +import java.util.List; + +public class Page { + + private List list; + + private int pageSize = 0; + + private int currentPage = 0; + + private int totalPages = 0; + + public Page(List list, int pageSize, int currentPage) { + + if (list.isEmpty()) { + this.list = list; + } + + if (pageSize <= 0 || pageSize > list.size() || currentPage <= 0) { + throw new IllegalArgumentException("invalid page size or current page!"); + } + + this.pageSize = pageSize; + + this.currentPage = currentPage; + + if (list.size() % pageSize == 0) { + this.totalPages = list.size() / pageSize; + } else { + this.totalPages = list.size() / pageSize + 1; + } + + int startItem = (currentPage - 1) * pageSize; + if (list.size() < startItem) { + this.list = Collections.emptyList(); + } + + int toIndex = Math.min(startItem + pageSize, list.size()); + this.list = list.subList(startItem, toIndex); + } + + public List getList() { + return list; + } + + public int getPageSize() { + return pageSize; + } + + public int getCurrentPage() { + return currentPage; + } + + public int getTotalPages() { + return totalPages; + } + +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/service/BookService.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/service/BookService.java new file mode 100644 index 0000000000..2aaa559251 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/service/BookService.java @@ -0,0 +1,38 @@ +package com.baeldung.thymeleaf.service; + +import java.util.Collections; +import java.util.List; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +import com.baeldung.thymeleaf.model.Book; +import com.baeldung.thymeleaf.utils.BookUtils; + +@Service +public class BookService { + + final private List books = BookUtils.buildBooks(); + + public Page findPaginated(Pageable pageable) { + int pageSize = pageable.getPageSize(); + int currentPage = pageable.getPageNumber(); + int startItem = currentPage * pageSize; + List list; + + if (books.size() < startItem) { + list = Collections.emptyList(); + } else { + int toIndex = Math.min(startItem + pageSize, books.size()); + list = books.subList(startItem, toIndex); + } + + Page bookPage = new PageImpl(list, PageRequest.of(currentPage, pageSize), books.size()); + + return bookPage; + + } +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/BookUtils.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/BookUtils.java new file mode 100644 index 0000000000..3cd9e6a92e --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/BookUtils.java @@ -0,0 +1,28 @@ +package com.baeldung.thymeleaf.utils; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.IntStream; + +import com.baeldung.thymeleaf.model.Book; + +public class BookUtils { + + private static List books = new ArrayList(); + + private static final int NUM_BOOKS = 30; + + private static final int MIN_BOOK_NUM = 1000; + + public static List buildBooks() { + if (books.isEmpty()) { + IntStream.range(0, NUM_BOOKS).forEach(n -> { + books.add(new Book(MIN_BOOK_NUM + n + 1, "Spring in Action")); + }); + + } + + return books; + } + +} diff --git a/spring-thymeleaf/src/main/resources/logback.xml b/spring-thymeleaf/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-thymeleaf/src/main/resources/logback.xml +++ b/spring-thymeleaf/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-thymeleaf/src/main/resources/messages_en.properties b/spring-thymeleaf/src/main/resources/messages_en.properties index 373c20f1d1..b534d448b6 100644 --- a/spring-thymeleaf/src/main/resources/messages_en.properties +++ b/spring-thymeleaf/src/main/resources/messages_en.properties @@ -1,12 +1,13 @@ -msg.id=ID -msg.name=Name -msg.gender=Gender -msg.percent=Percentage -welcome.message=Welcome Student !!! -msg.AddStudent=Add Student -msg.ListStudents=List Students -msg.Home=Home -msg.ListTeachers=List Teachers -msg.courses=Courses -msg.skills=Skills +msg.id=ID +msg.name=Name +msg.gender=Gender +msg.percent=Percentage +welcome.message=Welcome Student !!! +msg.AddStudent=Add Student +msg.ListStudents=List Students +msg.Home=Home +msg.ListTeachers=List Teachers +msg.ListBooks=List Books with paging +msg.courses=Courses +msg.skills=Skills msg.active=Active \ No newline at end of file diff --git a/spring-thymeleaf/src/main/resources/templates/continents.html b/spring-thymeleaf/src/main/resources/templates/continents.html new file mode 100644 index 0000000000..0e7ffa3f58 --- /dev/null +++ b/spring-thymeleaf/src/main/resources/templates/continents.html @@ -0,0 +1,49 @@ + + + + Arrays in Thymeleaf + + + + + +

    THE CONTINENTS

    +

    + We have a total of + continents in this world. Following is a list showing their order + based on the number of population in each of them. +

    + +
      +
    1. +
    2. +
    3. +
    4. +
    5. +
    6. +
    7. +
    + +
      +
    • +
    + +

    + +

    + The greatest + continents. +

    + +

    + Europe is a continent: . +

    + +

    + Array of continents is empty . +

    + + + diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html index f3d28d7ef4..34a6dec4da 100644 --- a/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html @@ -32,7 +32,9 @@
    - - 1.2.3.RELEASE - 3.5 - 2.6 -
    \ No newline at end of file diff --git a/spring-zuul/spring-zuul-foos-resource/pom.xml b/spring-zuul/spring-zuul-foos-resource/pom.xml index 58274c523a..70e39db4aa 100644 --- a/spring-zuul/spring-zuul-foos-resource/pom.xml +++ b/spring-zuul/spring-zuul-foos-resource/pom.xml @@ -1,6 +1,7 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + spring-zuul-foos-resource spring-zuul-foos-resource war @@ -16,13 +17,11 @@ org.springframework.boot spring-boot-starter-web - org.apache.commons commons-lang3 ${commons-lang3.version} -
    diff --git a/spring-zuul/spring-zuul-foos-resource/src/main/resources/logback.xml b/spring-zuul/spring-zuul-foos-resource/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-zuul/spring-zuul-foos-resource/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-zuul/spring-zuul-ui/pom.xml b/spring-zuul/spring-zuul-ui/pom.xml index 42c18a46c7..6090f5f8b8 100644 --- a/spring-zuul/spring-zuul-ui/pom.xml +++ b/spring-zuul/spring-zuul-ui/pom.xml @@ -1,8 +1,8 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - spring-zuul-ui + spring-zuul-ui spring-zuul-ui war @@ -12,33 +12,26 @@ 1.0.0-SNAPSHOT - org.springframework.cloud spring-cloud-starter-zuul ${spring-cloud.version} - - - + org.springframework.boot spring-boot-starter-web - org.springframework.boot spring-boot-starter-thymeleaf - org.springframework spring-test test - org.hamcrest hamcrest-core @@ -49,13 +42,11 @@ hamcrest-library test - org.mockito mockito-core test - diff --git a/spring-zuul/spring-zuul-ui/src/main/resources/logback.xml b/spring-zuul/spring-zuul-ui/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-zuul/spring-zuul-ui/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/sse-jaxrs/pom.xml b/sse-jaxrs/pom.xml new file mode 100644 index 0000000000..ac9bff937f --- /dev/null +++ b/sse-jaxrs/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + + com.baeldung.sse + sse-jaxrs + 1.0-SNAPSHOT + pom + + + 1.8 + 1.8 + + + + sse-jaxrs-server + sse-jaxrs-client + + + diff --git a/sse-jaxrs/sse-jaxrs-client/pom.xml b/sse-jaxrs/sse-jaxrs-client/pom.xml new file mode 100644 index 0000000000..a9068e133f --- /dev/null +++ b/sse-jaxrs/sse-jaxrs-client/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + + com.baeldung.sse + sse-jaxrs + 1.0-SNAPSHOT + + + sse-jaxrs-client + + + 3.2.0 + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + singleEvent + + java + + + com.baeldung.sse.jaxrs.client.SseClientApp + + + + broadcast + + java + + + com.baeldung.sse.jaxrs.client.SseClientBroadcastApp + + + + + + + + + + org.apache.cxf + cxf-rt-rs-client + ${cxf-version} + + + org.apache.cxf + cxf-rt-rs-sse + ${cxf-version} + + + + diff --git a/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java b/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java new file mode 100644 index 0000000000..5d42b3a243 --- /dev/null +++ b/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java @@ -0,0 +1,48 @@ +package com.baeldung.sse.jaxrs.client; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.sse.InboundSseEvent; +import javax.ws.rs.sse.SseEventSource; +import java.util.function.Consumer; + +public class SseClientApp { + + private static final String url = "http://127.0.0.1:9080/sse-jaxrs-server/sse/stock/prices"; + + public static void main(String... args) throws Exception { + + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(url); + try (SseEventSource eventSource = SseEventSource.target(target).build()) { + + eventSource.register(onEvent, onError, onComplete); + eventSource.open(); + + //Consuming events for one hour + Thread.sleep(60 * 60 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + client.close(); + System.out.println("End"); + } + + // A new event is received + private static Consumer onEvent = (inboundSseEvent) -> { + String data = inboundSseEvent.readData(); + System.out.println(data); + }; + + //Error + private static Consumer onError = (throwable) -> { + throwable.printStackTrace(); + }; + + //Connection close and there is nothing to receive + private static Runnable onComplete = () -> { + System.out.println("Done!"); + }; + +} diff --git a/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java b/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java new file mode 100644 index 0000000000..9afc187a6d --- /dev/null +++ b/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java @@ -0,0 +1,52 @@ +package com.baeldung.sse.jaxrs.client; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.sse.InboundSseEvent; +import javax.ws.rs.sse.SseEventSource; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +public class SseClientBroadcastApp { + + private static final String subscribeUrl = "http://localhost:9080/sse-jaxrs-server/sse/stock/subscribe"; + + + public static void main(String... args) throws Exception { + + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(subscribeUrl); + try (final SseEventSource eventSource = SseEventSource.target(target) + .reconnectingEvery(5, TimeUnit.SECONDS) + .build()) { + eventSource.register(onEvent, onError, onComplete); + eventSource.open(); + System.out.println("Wainting for incoming event ..."); + + //Consuming events for one hour + Thread.sleep(60 * 60 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + client.close(); + System.out.println("End"); + } + + // A new event is received + private static Consumer onEvent = (inboundSseEvent) -> { + String data = inboundSseEvent.readData(); + System.out.println(data); + }; + + //Error + private static Consumer onError = (throwable) -> { + throwable.printStackTrace(); + }; + + //Connection close and there is nothing to receive + private static Runnable onComplete = () -> { + System.out.println("Done!"); + }; + +} diff --git a/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml b/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/sse-jaxrs/sse-jaxrs-server/pom.xml b/sse-jaxrs/sse-jaxrs-server/pom.xml new file mode 100644 index 0000000000..1e89c70e13 --- /dev/null +++ b/sse-jaxrs/sse-jaxrs-server/pom.xml @@ -0,0 +1,85 @@ + + + 4.0.0 + + + com.baeldung.sse + sse-jaxrs + 1.0-SNAPSHOT + + + sse-jaxrs-server + war + + + 2.4.2 + false + 18.0.0.2 + + + + ${artifactId} + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + ${liberty-maven-plugin.version} + + + io.openliberty + openliberty-webProfile8 + ${openliberty-version} + zip + + project + true + src/main/liberty/config/server.xml + + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + + + + + + javax.ws.rs + javax.ws.rs-api + 2.1 + provided + + + javax.enterprise + cdi-api + 2.0 + provided + + + javax.json.bind + javax.json.bind-api + 1.0 + provided + + + + + diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java b/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java new file mode 100644 index 0000000000..058d19f045 --- /dev/null +++ b/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java @@ -0,0 +1,8 @@ +package com.baeldung.sse.jaxrs; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("sse") +public class AppConfig extends Application { +} diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java b/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java new file mode 100644 index 0000000000..1f60168a1b --- /dev/null +++ b/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java @@ -0,0 +1,119 @@ +package com.baeldung.sse.jaxrs; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.sse.OutboundSseEvent; +import javax.ws.rs.sse.Sse; +import javax.ws.rs.sse.SseBroadcaster; +import javax.ws.rs.sse.SseEventSink; + +@ApplicationScoped +@Path("stock") +public class SseResource { + + @Inject + private StockService stockService; + + private Sse sse; + private SseBroadcaster sseBroadcaster; + private OutboundSseEvent.Builder eventBuilder; + + @Context + public void setSse(Sse sse) { + this.sse = sse; + this.eventBuilder = sse.newEventBuilder(); + this.sseBroadcaster = sse.newBroadcaster(); + } + + @GET + @Path("prices") + @Produces("text/event-stream") + public void getStockPrices(@Context SseEventSink sseEventSink, + @HeaderParam(HttpHeaders.LAST_EVENT_ID_HEADER) @DefaultValue("-1") int lastReceivedId) { + + int lastEventId = 1; + if (lastReceivedId != -1) { + lastEventId = ++lastReceivedId; + } + boolean running = true; + while (running) { + Stock stock = stockService.getNextTransaction(lastEventId); + if (stock != null) { + OutboundSseEvent sseEvent = this.eventBuilder + .name("stock") + .id(String.valueOf(lastEventId)) + .mediaType(MediaType.APPLICATION_JSON_TYPE) + .data(Stock.class, stock) + .reconnectDelay(3000) + .comment("price change") + .build(); + sseEventSink.send(sseEvent); + lastEventId++; + } + //Simulate connection close + if (lastEventId % 5 == 0) { + sseEventSink.close(); + break; + } + + try { + //Wait 5 seconds + Thread.sleep(5 * 1000); + } catch (InterruptedException ex) { + // ... + } + //Simulatae a while boucle break + running = lastEventId <= 2000; + } + sseEventSink.close(); + } + + @GET + @Path("subscribe") + @Produces(MediaType.SERVER_SENT_EVENTS) + public void listen(@Context SseEventSink sseEventSink) { + sseEventSink.send(sse.newEvent("Welcome !")); + this.sseBroadcaster.register(sseEventSink); + sseEventSink.send(sse.newEvent("You are registred !")); + } + + @GET + @Path("publish") + public void broadcast() { + Runnable r = new Runnable() { + @Override + public void run() { + int lastEventId = 0; + boolean running = true; + while (running) { + lastEventId++; + Stock stock = stockService.getNextTransaction(lastEventId); + if (stock != null) { + OutboundSseEvent sseEvent = eventBuilder + .name("stock") + .id(String.valueOf(lastEventId)) + .mediaType(MediaType.APPLICATION_JSON_TYPE) + .data(Stock.class, stock) + .reconnectDelay(3000) + .comment("price change") + .build(); + sseBroadcaster.broadcast(sseEvent); + } + try { + //Wait 5 seconds + Thread.currentThread().sleep(5 * 1000); + } catch (InterruptedException ex) { + // ... + } + //Simulatae a while boucle break + running = lastEventId <= 2000; + } + } + }; + new Thread(r).start(); + } +} diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java b/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java new file mode 100644 index 0000000000..a186b32771 --- /dev/null +++ b/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java @@ -0,0 +1,50 @@ +package com.baeldung.sse.jaxrs; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +public class Stock { + private Integer id; + private String name; + private BigDecimal price; + LocalDateTime dateTime; + + public Stock(Integer id, String name, BigDecimal price, LocalDateTime dateTime) { + this.id = id; + this.name = name; + this.price = price; + this.dateTime = dateTime; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public LocalDateTime getDateTime() { + return dateTime; + } + + public void setDateTime(LocalDateTime dateTime) { + this.dateTime = dateTime; + } +} diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java b/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java new file mode 100644 index 0000000000..15818ead5d --- /dev/null +++ b/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java @@ -0,0 +1,78 @@ +package com.baeldung.sse.jaxrs; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.context.Initialized; +import javax.enterprise.event.Event; +import javax.enterprise.event.Observes; +import javax.inject.Inject; +import javax.inject.Named; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Random; +import java.util.concurrent.atomic.AtomicInteger; + +@ApplicationScoped +@Named +public class StockService { + + private static final BigDecimal UP = BigDecimal.valueOf(1.05f); + private static final BigDecimal DOWN = BigDecimal.valueOf(0.95f); + + List stockNames = Arrays.asList("GOOG", "IBM", "MS", "GOOG", "YAHO"); + List stocksDB = new ArrayList<>(); + private AtomicInteger counter = new AtomicInteger(0); + + public void init(@Observes @Initialized(ApplicationScoped.class) Object init) { + //Open price + System.out.println("@Start Init ..."); + stockNames.forEach(stockName -> { + stocksDB.add(new Stock(counter.incrementAndGet(), stockName, generateOpenPrice(), LocalDateTime.now())); + }); + + Runnable runnable = new Runnable() { + @Override + public void run() { + //Simulate Change price and put every x seconds + while (true) { + int indx = new Random().nextInt(stockNames.size()); + String stockName = stockNames.get(indx); + BigDecimal price = getLastPrice(stockName); + BigDecimal newprice = changePrice(price); + Stock stock = new Stock(counter.incrementAndGet(), stockName, newprice, LocalDateTime.now()); + stocksDB.add(stock); + + int r = new Random().nextInt(30); + try { + Thread.currentThread().sleep(r*1000); + } catch (InterruptedException ex) { + // ... + } + } + } + }; + new Thread(runnable).start(); + System.out.println("@End Init ..."); + } + + public Stock getNextTransaction(Integer lastEventId) { + return stocksDB.stream().filter(s -> s.getId().equals(lastEventId)).findFirst().orElse(null); + } + + BigDecimal generateOpenPrice() { + float min = 70; + float max = 120; + return BigDecimal.valueOf(min + new Random().nextFloat() * (max - min)).setScale(4,RoundingMode.CEILING); + } + + BigDecimal changePrice(BigDecimal price) { + return Math.random() >= 0.5 ? price.multiply(UP).setScale(4,RoundingMode.CEILING) : price.multiply(DOWN).setScale(4,RoundingMode.CEILING); + } + + private BigDecimal getLastPrice(String stockName) { + return stocksDB.stream().filter(stock -> stock.getName().equals(stockName)).findFirst().get().getPrice(); + } +} diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml b/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..9bf66d7795 --- /dev/null +++ b/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml @@ -0,0 +1,7 @@ + + + jaxrs-2.1 + cdi-2.0 + + + diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml b/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..4f0b3cdeeb --- /dev/null +++ b/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml @@ -0,0 +1,6 @@ + + \ No newline at end of file diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml b/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml b/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..b4b8121fdd --- /dev/null +++ b/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,11 @@ + + + Hello Servlet + + + index.html + + + diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html b/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html new file mode 100644 index 0000000000..9015a7a32c --- /dev/null +++ b/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html @@ -0,0 +1 @@ +index diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html b/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html new file mode 100644 index 0000000000..5a46e2a5d3 --- /dev/null +++ b/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html @@ -0,0 +1,38 @@ + + + + Server-Sent Event Broadcasting + + +

    Stock prices :

    +
    +
      +
    +
    + + + \ No newline at end of file diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse.html b/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse.html new file mode 100644 index 0000000000..8fddae4717 --- /dev/null +++ b/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse.html @@ -0,0 +1,38 @@ + + + + Server-Sent Event + + +

    Stock prices :

    +
    +
      +
    +
    + + + \ No newline at end of file diff --git a/static-analysis/pom.xml b/static-analysis/pom.xml index 93d071714e..14853d81f7 100644 --- a/static-analysis/pom.xml +++ b/static-analysis/pom.xml @@ -1,8 +1,8 @@ - + 4.0.0 + com.baeldung static-analysis 1.0-SNAPSHOT diff --git a/static-analysis/src/main/resources/logback.xml b/static-analysis/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/static-analysis/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/stripe/pom.xml b/stripe/pom.xml index b6dae6e680..1e13612fb5 100644 --- a/stripe/pom.xml +++ b/stripe/pom.xml @@ -1,7 +1,8 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + com.baeldung.stripe stripe 0.0.1-SNAPSHOT @@ -10,10 +11,10 @@ Demo project for Stripe API - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -25,20 +26,23 @@ org.springframework.boot spring-boot-starter-thymeleaf - org.projectlombok lombok - 1.16.16 - + ${lombok.version} + com.stripe stripe-java - 4.2.0 + ${stripe.version} + + + 1.16.16 + 4.2.0 + diff --git a/stripe/src/main/resources/logback.xml b/stripe/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/stripe/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/structurizr/pom.xml b/structurizr/pom.xml index 1656bb10ec..cbbbf8d68c 100644 --- a/structurizr/pom.xml +++ b/structurizr/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.baeldung @@ -13,31 +12,26 @@ 1.0.0-SNAPSHOT - - 1.8 - 1.8 - - com.structurizr structurizr-core - 1.0.0-RC3 + ${structurizr.version} com.structurizr structurizr-spring - 1.0.0-RC3 + ${structurizr.version} com.structurizr structurizr-client - 0.6.0 + ${structurizr-client.version} org.springframework spring-context - 4.3.8.RELEASE + ${spring.version} @@ -51,4 +45,13 @@ http://jcenter.bintray.com + + + 1.8 + 1.8 + 1.0.0-RC3 + 0.6.0 + 4.3.8.RELEASE + + \ No newline at end of file diff --git a/structurizr/src/main/resources/logback.xml b/structurizr/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/structurizr/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/struts-2/pom.xml b/struts-2/pom.xml index bb23600446..fee68c8303 100644 --- a/struts-2/pom.xml +++ b/struts-2/pom.xml @@ -1,62 +1,44 @@ + 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 - struts + struts-2 0.0.1-SNAPSHOT pom - struts + Struts 2 - com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring - + com.baeldung + parent-spring-4 + 0.0.1-SNAPSHOT + ../parent-spring-4 + - - src/main/java - - - src/main/resources - - - - - - maven-war-plugin - 3.0.0 - - WebContent - - - - org.apache.struts struts2-core - 2.5.5 + ${struts2.version} org.apache.struts struts2-junit-plugin - 2.5.5 + ${struts2.version} org.apache.struts struts2-convention-plugin - 2.5.8 + ${struts2-convention-plugin.version} javax.servlet javax.servlet-api - 3.0.1 + ${servlet.version} org.springframework spring-core - 4.3.6.RELEASE + ${spring.version} commons-logging @@ -65,4 +47,31 @@ + + + src/main/java + + + src/main/resources + + + + + maven-war-plugin + ${maven-war-plugin.version} + + WebContent + + + + + + + 2.5.5 + 2.5.8 + 3.0.1 + 4.3.6.RELEASE + 3.0.0 + + \ No newline at end of file diff --git a/struts-2/src/main/resources/logback.xml b/struts-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/struts-2/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/testing-modules/README.md b/testing-modules/README.md index d83970f96a..b189b9819e 100644 --- a/testing-modules/README.md +++ b/testing-modules/README.md @@ -12,4 +12,5 @@ - [Hamcrest Object Matchers](http://www.baeldung.com/hamcrest-object-matchers) - [Headers, Cookies and Parameters with REST-assured](http://www.baeldung.com/rest-assured-header-cookie-parameter) - [JSON Schema Validation with REST-assured](http://www.baeldung.com/rest-assured-json-schema) - +- [Testing Callbacks with Mockito](http://www.baeldung.com/mockito-callbacks) +- [Running JUnit Tests in Parallel with Maven](https://www.baeldung.com/maven-junit-parallel-tests) diff --git a/testing-modules/gatling/README.md b/testing-modules/gatling/README.md index 5c81c4bd6a..941ab75f06 100644 --- a/testing-modules/gatling/README.md +++ b/testing-modules/gatling/README.md @@ -1,2 +1,5 @@ ### Relevant Articles: - [Intro to Gatling](http://www.baeldung.com/introduction-to-gatling) + +### Running a simualtion +- To run a simulation use "simulation" profile, command - `mvn install -Psimulation -Dgib.enabled=false` diff --git a/testing-modules/gatling/pom.xml b/testing-modules/gatling/pom.xml index c4aec4d61a..8d4c89ec62 100644 --- a/testing-modules/gatling/pom.xml +++ b/testing-modules/gatling/pom.xml @@ -1,117 +1,135 @@ - - 4.0.0 - org.baeldung - gatling - 1.0-SNAPSHOT + + 4.0.0 + org.baeldung + gatling + 1.0-SNAPSHOT + com.baeldung parent-modules 1.0.0-SNAPSHOT + ../../ - - 1.8 - 1.8 - UTF-8 - 2.11.12 - 2.2.5 - 3.2.2 - 2.2.1 - + + + + io.gatling.highcharts + gatling-charts-highcharts + + + io.gatling + gatling-app + + + io.gatling + gatling-recorder + + + org.scala-lang + scala-library + + - - - - io.gatling - gatling-app - ${gatling.version} - - - io.gatling - gatling-recorder - ${gatling.version} - - - io.gatling.highcharts - gatling-charts-highcharts - ${gatling.version} - - - org.scala-lang - scala-library - ${scala.version} - - - + + src/test/scala + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin.version} + + + + + + net.alchim31.maven + scala-maven-plugin + + + + testCompile + + + + + -Ydelambdafy:method + -target:jvm-1.8 + -deprecation + -feature + -unchecked + -language:implicitConversions + -language:postfixOps + + + + + + + + + + + simulation + + + + io.gatling + gatling-maven-plugin + ${gatling-maven-plugin.version} + + + test + + execute + + + true + + + + + + + + - - - io.gatling.highcharts - gatling-charts-highcharts - - - io.gatling - gatling-app - - - io.gatling - gatling-recorder - - - org.scala-lang - scala-library - - + + + + io.gatling + gatling-app + ${gatling.version} + + + io.gatling + gatling-recorder + ${gatling.version} + + + io.gatling.highcharts + gatling-charts-highcharts + ${gatling.version} + + + org.scala-lang + scala-library + ${scala.version} + + + + + + 1.8 + 1.8 + UTF-8 + 2.12.6 + 2.3.1 + 3.2.2 + 2.2.4 + - - src/test/scala - - - - net.alchim31.maven - scala-maven-plugin - ${scala-maven-plugin.version} - - - - - - net.alchim31.maven - scala-maven-plugin - - - - testCompile - - - - - -Ydelambdafy:method - -target:jvm-1.8 - -deprecation - -feature - -unchecked - -language:implicitConversions - -language:postfixOps - - - - - - - io.gatling - gatling-maven-plugin - ${gatling-maven-plugin.version} - - - test - - execute - - - - - - diff --git a/testing-modules/groovy-spock/pom.xml b/testing-modules/groovy-spock/pom.xml index 84b27187eb..e0da345eb4 100644 --- a/testing-modules/groovy-spock/pom.xml +++ b/testing-modules/groovy-spock/pom.xml @@ -1,12 +1,11 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 org.spockframework groovy-spock 1.0-SNAPSHOT jar - Spock Framework - Example Project com.baeldung @@ -15,6 +14,20 @@ ../../ + + + org.spockframework + spock-core + ${spock-core.version} + test + + + org.codehaus.groovy + groovy-all + ${groovy-all.version} + + + @@ -33,23 +46,7 @@ - - - org.spockframework - spock-core - ${spock-core.version} - test - - - org.codehaus.groovy - groovy-all - ${groovy-all.version} - - - - UTF-8 - UTF-8 1.0-groovy-2.4 2.4.7 1.5 diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md index 0a9dccf666..40c4e8cde9 100644 --- a/testing-modules/junit-5/README.md +++ b/testing-modules/junit-5/README.md @@ -12,3 +12,7 @@ - [JUnit Assert an Exception is Thrown](http://www.baeldung.com/junit-assert-exception) - [@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll](http://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall) - [Migrating from JUnit 4 to JUnit 5](http://www.baeldung.com/junit-5-migration) +- [JUnit5 Programmatic Extension Registration with @RegisterExtension](http://www.baeldung.com/junit-5-registerextension-annotation) +- [The Order of Tests in JUnit](http://www.baeldung.com/junit-5-test-order) +- [Running JUnit Tests Programmatically, from a Java Application](https://www.baeldung.com/junit-tests-run-programmatically-from-java) +- [Testing an Abstract Class With JUnit](https://www.baeldung.com/junit-test-abstract-class) diff --git a/testing-modules/junit-5/pom.xml b/testing-modules/junit-5/pom.xml index cfffa29aec..93365264ac 100644 --- a/testing-modules/junit-5/pom.xml +++ b/testing-modules/junit-5/pom.xml @@ -1,12 +1,10 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - - + junit-5 1.0-SNAPSHOT - junit-5 Intro to JUnit 5 @@ -17,45 +15,12 @@ ../../ - - - - - src/test/resources - true - - - - - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - - - - - org.codehaus.mojo - exec-maven-plugin - 1.6.0 - - - - java - - - - - com.baeldung.TestLauncher - - - - - + + org.junit.platform + junit-platform-engine + ${junit.platform.version} + org.junit.platform junit-platform-runner @@ -68,6 +33,12 @@ ${junit.vintage.version} test + + org.junit.jupiter + junit-jupiter-migrationsupport + ${junit.vintage.version} + test + org.apache.logging.log4j log4j-core @@ -89,22 +60,74 @@ spring-context ${spring.version} - + + org.powermock + powermock-module-junit4 + ${powermock.version} + test + + + junit + junit + + + + + org.powermock + powermock-api-mockito2 + ${powermock.version} + test + + + + + src/test/resources + true + + + + + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + + + java + + + + + com.baeldung.TestLauncher + + + + + - UTF-8 - 1.8 - 5.1.0 - 1.0.1 - 4.12.1 + 5.2.0 + 1.2.0 + 5.2.0 2.8.2 1.4.196 - 2.11.0 - - 3.7.0 - 2.19.1 + 2.8.9 + 1.7.4 + 2.21.0 + 1.6.0 5.0.1.RELEASE - + diff --git a/testing-modules/junit-5/src/main/java/com/baeldung/abstractclass/abstractmethod/AbstractMethodCalling.java b/testing-modules/junit-5/src/main/java/com/baeldung/abstractclass/abstractmethod/AbstractMethodCalling.java new file mode 100644 index 0000000000..e55c6b98e2 --- /dev/null +++ b/testing-modules/junit-5/src/main/java/com/baeldung/abstractclass/abstractmethod/AbstractMethodCalling.java @@ -0,0 +1,17 @@ +/** + * + */ +package com.baeldung.abstractclass.abstractmethod; + +/** + * When method calls abstract method. + */ +public abstract class AbstractMethodCalling { + + public abstract String abstractFunc(); + + public String defaultImpl() { + String res = abstractFunc(); + return (res == null) ? "Default" : (res + " Default"); + } +} diff --git a/testing-modules/junit-5/src/main/java/com/baeldung/abstractclass/indepedentmethod/AbstractIndependent.java b/testing-modules/junit-5/src/main/java/com/baeldung/abstractclass/indepedentmethod/AbstractIndependent.java new file mode 100644 index 0000000000..4dce2665d5 --- /dev/null +++ b/testing-modules/junit-5/src/main/java/com/baeldung/abstractclass/indepedentmethod/AbstractIndependent.java @@ -0,0 +1,14 @@ +package com.baeldung.abstractclass.indepedentmethod; + +/** + * Test Independent Method + * + */ +public abstract class AbstractIndependent { + + public abstract int abstractFunc(); + + public String defaultImpl() { + return "DEFAULT-1"; + } +} diff --git a/testing-modules/junit-5/src/main/java/com/baeldung/abstractclass/indepedentmethod/ConcreteImpl.java b/testing-modules/junit-5/src/main/java/com/baeldung/abstractclass/indepedentmethod/ConcreteImpl.java new file mode 100644 index 0000000000..6e71b88946 --- /dev/null +++ b/testing-modules/junit-5/src/main/java/com/baeldung/abstractclass/indepedentmethod/ConcreteImpl.java @@ -0,0 +1,10 @@ +package com.baeldung.abstractclass.indepedentmethod; + +public class ConcreteImpl extends AbstractIndependent { + + @Override + public int abstractFunc() { + return 4; + } + +} diff --git a/testing-modules/junit-5/src/main/java/com/baeldung/abstractclass/instancefields/AbstractInstanceFields.java b/testing-modules/junit-5/src/main/java/com/baeldung/abstractclass/instancefields/AbstractInstanceFields.java new file mode 100644 index 0000000000..262f72e393 --- /dev/null +++ b/testing-modules/junit-5/src/main/java/com/baeldung/abstractclass/instancefields/AbstractInstanceFields.java @@ -0,0 +1,22 @@ +package com.baeldung.abstractclass.instancefields; + +/** + * Test Independent Method + */ +public abstract class AbstractInstanceFields { + + protected int count; + private boolean active = false; + + public abstract int abstractFunc(); + + public String testFunc() { + String response; + if (count > 5) { + response = "Overflow"; + } else { + response = active ? "Added" : "Blocked"; + } + return response; + } +} diff --git a/testing-modules/junit-5/src/main/java/com/baeldung/abstractclass/privatemethod/AbstractPrivateMethods.java b/testing-modules/junit-5/src/main/java/com/baeldung/abstractclass/privatemethod/AbstractPrivateMethods.java new file mode 100644 index 0000000000..fe7fb25931 --- /dev/null +++ b/testing-modules/junit-5/src/main/java/com/baeldung/abstractclass/privatemethod/AbstractPrivateMethods.java @@ -0,0 +1,17 @@ +package com.baeldung.abstractclass.privatemethod; + +import java.time.LocalDateTime; + +public abstract class AbstractPrivateMethods { + + public abstract int abstractFunc(); + + public String defaultImpl() { + return getCurrentDateTime() + "DEFAULT-1"; + } + + private String getCurrentDateTime() { + return LocalDateTime.now() + .toString(); + } +} diff --git a/testing-modules/junit-5/src/main/resources/logback.xml b/testing-modules/junit-5/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/testing-modules/junit-5/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/AssertionUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/AssertionUnitTest.java index 79ba882205..31b6e14d6c 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/AssertionUnitTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/AssertionUnitTest.java @@ -11,14 +11,17 @@ import java.util.Optional; import java.util.function.BooleanSupplier; import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** * Unit test that demonstrate the different assertions available within JUnit 4 */ +@DisplayName("Test case for assertions") public class AssertionUnitTest { @Test + @DisplayName("Arrays should be equals") public void whenAssertingArraysEquality_thenEqual() { char[] expected = {'J', 'u', 'p', 'i', 't', 'e', 'r'}; char[] actual = "Jupiter".toCharArray(); @@ -27,6 +30,7 @@ public class AssertionUnitTest { } @Test + @DisplayName("The area of two polygons should be equal") public void whenAssertingEquality_thenEqual() { float square = 2 * 2; float rectangle = 2 * 2; diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/AssumptionUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/AssumptionUnitTest.java deleted file mode 100644 index 7d67d93486..0000000000 --- a/testing-modules/junit-5/src/test/java/com/baeldung/AssumptionUnitTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assumptions.assumeFalse; -import static org.junit.jupiter.api.Assumptions.assumeTrue; -import static org.junit.jupiter.api.Assumptions.assumingThat; - -import org.junit.jupiter.api.Test; - -public class AssumptionUnitTest { - - @Test - void trueAssumption() { - assumeTrue(5 > 1); - assertEquals(5 + 2, 7); - } - - @Test - void falseAssumption() { - assumeFalse(5 < 1); - assertEquals(5 + 2, 7); - } - - @Test - void assumptionThat() { - String someString = "Just a string"; - assumingThat(someString.equals("Just a string"), () -> assertEquals(2 + 2, 4)); - } -} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/EmployeesTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/EmployeesTest.java deleted file mode 100644 index 71bb52284b..0000000000 --- a/testing-modules/junit-5/src/test/java/com/baeldung/EmployeesTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung; - -import java.sql.SQLException; - -import org.apache.logging.log4j.Logger; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import com.baeldung.extensions.EmployeeDaoParameterResolver; -import com.baeldung.extensions.EmployeeDatabaseSetupExtension; -import com.baeldung.extensions.EnvironmentExtension; -import com.baeldung.extensions.IgnoreFileNotFoundExceptionExtension; -import com.baeldung.extensions.LoggingExtension; -import com.baeldung.helpers.Employee; -import com.baeldung.helpers.EmployeeJdbcDao; - -import static org.junit.jupiter.api.Assertions.*; - -@ExtendWith({ EnvironmentExtension.class, EmployeeDatabaseSetupExtension.class, EmployeeDaoParameterResolver.class }) -@ExtendWith(LoggingExtension.class) -@ExtendWith(IgnoreFileNotFoundExceptionExtension.class) -public class EmployeesTest { - - private EmployeeJdbcDao employeeDao; - - private Logger logger; - - public EmployeesTest(EmployeeJdbcDao employeeDao) { - this.employeeDao = employeeDao; - } - - @Test - public void whenAddEmployee_thenGetEmployee() throws SQLException { - Employee emp = new Employee(1, "john"); - employeeDao.add(emp); - assertEquals(1, employeeDao.findAll() - .size()); - } - - @Test - public void whenGetEmployees_thenEmptyList() throws SQLException { - assertEquals(0, employeeDao.findAll() - .size()); - } - - public void setLogger(Logger logger) { - this.logger = logger; - } - -} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/EmployeesUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/EmployeesUnitTest.java new file mode 100644 index 0000000000..1ea116be6d --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/EmployeesUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung; + +import java.sql.SQLException; + +import org.apache.logging.log4j.Logger; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import com.baeldung.extensions.EmployeeDaoParameterResolver; +import com.baeldung.extensions.EmployeeDatabaseSetupExtension; +import com.baeldung.extensions.EnvironmentExtension; +import com.baeldung.extensions.IgnoreFileNotFoundExceptionExtension; +import com.baeldung.extensions.LoggingExtension; +import com.baeldung.helpers.Employee; +import com.baeldung.helpers.EmployeeJdbcDao; + +import static org.junit.jupiter.api.Assertions.*; + +@ExtendWith({ EnvironmentExtension.class, EmployeeDatabaseSetupExtension.class, EmployeeDaoParameterResolver.class }) +@ExtendWith(LoggingExtension.class) +@ExtendWith(IgnoreFileNotFoundExceptionExtension.class) +public class EmployeesUnitTest { + + private EmployeeJdbcDao employeeDao; + + private Logger logger; + + public EmployeesUnitTest(EmployeeJdbcDao employeeDao) { + this.employeeDao = employeeDao; + } + + @Test + public void whenAddEmployee_thenGetEmployee() throws SQLException { + Employee emp = new Employee(1, "john"); + employeeDao.add(emp); + assertEquals(1, employeeDao.findAll() + .size()); + } + + @Test + public void whenGetEmployees_thenEmptyList() throws SQLException { + assertEquals(0, employeeDao.findAll() + .size()); + } + + public void setLogger(Logger logger) { + this.logger = logger; + } + +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsTest.java deleted file mode 100644 index efde4e7404..0000000000 --- a/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.jupiter.api.Test; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; - -import com.baeldung.junit5.Greetings; - -@RunWith(JUnitPlatform.class) -public class GreetingsTest { - - @Test - void whenCallingSayHello_thenReturnHello() { - assertTrue("Hello".equals(Greetings.sayHello())); - } - -} \ No newline at end of file diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsUnitTest.java new file mode 100644 index 0000000000..a07162ceed --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +import com.baeldung.junit5.Greetings; + +@RunWith(JUnitPlatform.class) +public class GreetingsUnitTest { + + @Test + void whenCallingSayHello_thenReturnHello() { + assertTrue("Hello".equals(Greetings.sayHello())); + } + +} \ No newline at end of file diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/NestedUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/NestedUnitTest.java index 7586a2f51a..299cac2480 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/NestedUnitTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/NestedUnitTest.java @@ -10,13 +10,13 @@ import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; public class NestedUnitTest { + Stack stack; - boolean isRun = false; @Test @DisplayName("is instantiated with new Stack()") void isInstantiatedWithNew() { - new Stack(); + new Stack<>(); } @Nested @@ -25,7 +25,7 @@ public class NestedUnitTest { @BeforeEach void init() { - stack = new Stack(); + stack = new Stack<>(); } @Test diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/RegisterExtensionUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/RegisterExtensionUnitTest.java new file mode 100644 index 0000000000..721cfdb013 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/RegisterExtensionUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung; + +import com.baeldung.extensions.RegisterExtensionSampleExtension; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +/** + * This test demonstrates the use of the same extension in two ways. + * 1. Once as instance level field: Only method level callbacks are called. + * 2. Once as class level static field: All methods are called. + */ +public class RegisterExtensionUnitTest { + + @RegisterExtension + static RegisterExtensionSampleExtension staticExtension = new RegisterExtensionSampleExtension("static version"); + + @RegisterExtension + RegisterExtensionSampleExtension instanceLevelExtension = new RegisterExtensionSampleExtension("instance version"); + + @Test + public void demoTest() { + Assertions.assertEquals("instance version", instanceLevelExtension.getType()); + } + +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/abstractclass/abstractmethod/AbstractMethodCallingUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/abstractclass/abstractmethod/AbstractMethodCallingUnitTest.java new file mode 100644 index 0000000000..7ebd866f3d --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/abstractclass/abstractmethod/AbstractMethodCallingUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.abstractclass.abstractmethod; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +public class AbstractMethodCallingUnitTest { + + private AbstractMethodCalling cls; + + @BeforeEach + public void setup() { + cls = Mockito.mock(AbstractMethodCalling.class); + } + + @Test + public void givenDefaultImpl_whenMockAbstractFunc_thenExpectedBehaviour() { + Mockito + .when(cls.abstractFunc()) + .thenReturn("Abstract"); + Mockito + .doCallRealMethod() + .when(cls) + .defaultImpl(); + + // validate result by mock abstractFunc's behaviour + Assertions.assertEquals("Abstract Default", cls.defaultImpl()); + + // check the value with null response from abstract method + Mockito + .doReturn(null) + .when(cls) + .abstractFunc(); + Assertions.assertEquals("Default", cls.defaultImpl()); + } + +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/abstractclass/indepedentmethod/AbstractIndependentUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/abstractclass/indepedentmethod/AbstractIndependentUnitTest.java new file mode 100644 index 0000000000..db9811e6c1 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/abstractclass/indepedentmethod/AbstractIndependentUnitTest.java @@ -0,0 +1,25 @@ +/** + * + */ +package com.baeldung.abstractclass.indepedentmethod; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +public class AbstractIndependentUnitTest { + + @Test + public void givenNonAbstractMethod_whenConcreteImpl_testCorrectBehaviour() { + ConcreteImpl conClass = new ConcreteImpl(); + String actual = conClass.defaultImpl(); + + Assertions.assertEquals("DEFAULT-1", actual); + } + + @Test + public void givenNonAbstractMethod_whenMockitoMock_testCorrectBehaviour() { + AbstractIndependent absCls = Mockito.mock(AbstractIndependent.class, Mockito.CALLS_REAL_METHODS); + Assertions.assertEquals("DEFAULT-1", absCls.defaultImpl()); + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/abstractclass/instancefields/AbstractInstanceFieldsUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/abstractclass/instancefields/AbstractInstanceFieldsUnitTest.java new file mode 100644 index 0000000000..5187ce00ab --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/abstractclass/instancefields/AbstractInstanceFieldsUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.abstractclass.instancefields; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.reflect.Whitebox; + +public class AbstractInstanceFieldsUnitTest { + + @Test + public void givenProtectedInstanceField_whenMockClassCountGt5_thenTestNonAbstractMethod() { + + // mock + AbstractInstanceFields instClass = Mockito.mock(AbstractInstanceFields.class); + Mockito + .doCallRealMethod() + .when(instClass) + .testFunc(); + + // set counter greater than 5 + instClass.count = 7; + + // compare the result + Assertions.assertEquals("Overflow", instClass.testFunc()); + } + + @Test + public void givenNonAbstractMethodAndPrivateField_whenPowerMockitoAndActiveFieldTrue_thenCorrectBehaviour() { + + AbstractInstanceFields instClass = PowerMockito.mock(AbstractInstanceFields.class); + PowerMockito + .doCallRealMethod() + .when(instClass) + .testFunc(); + Whitebox.setInternalState(instClass, "active", true); + + // compare the expected result with actual + Assertions.assertEquals("Added", instClass.testFunc()); + } + +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/abstractclass/privatemethod/AbstractPrivateMethodsUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/abstractclass/privatemethod/AbstractPrivateMethodsUnitTest.java new file mode 100644 index 0000000000..9ce7ff8706 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/abstractclass/privatemethod/AbstractPrivateMethodsUnitTest.java @@ -0,0 +1,41 @@ +/** + * + */ +package com.baeldung.abstractclass.privatemethod; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.time.LocalDateTime; + +/** + * Providing custom values for private methods using powermock + * + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest(AbstractPrivateMethods.class) +public class AbstractPrivateMethodsUnitTest { + + @Test + public void givenNonAbstractMethodAndCallPrivateMethod_whenMockPrivateMethod_thenVerifyBehaviour() throws Exception { + AbstractPrivateMethods mockClass = PowerMockito.mock(AbstractPrivateMethods.class); + + String dateTime = LocalDateTime + .now() + .toString(); + PowerMockito + .doCallRealMethod() + .when(mockClass) + .defaultImpl(); + PowerMockito + .doReturn(dateTime) + .when(mockClass, "getCurrentDateTime");// .thenReturn(dateTime); + String actual = mockClass.defaultImpl(); + Assertions.assertEquals(dateTime + "DEFAULT-1", actual); + } + +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionTest.java deleted file mode 100644 index f97e2ba9c7..0000000000 --- a/testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.exception; - -import static org.junit.jupiter.api.Assertions.assertThrows; - -import org.junit.jupiter.api.Test; - -public class ExceptionAssertionTest { - @Test - public void whenExceptionThrown_thenAssertionSucceeds() { - String test = null; - assertThrows(NullPointerException.class, () -> { - test.length(); - }); - } - - @Test - public void whenDerivedExceptionThrown_thenAssertionSucceds() { - String test = null; - assertThrows(RuntimeException.class, () -> { - test.length(); - }); - } -} \ No newline at end of file diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionUnitTest.java new file mode 100644 index 0000000000..002aae34a8 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.exception; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +public class ExceptionAssertionUnitTest { + @Test + public void whenExceptionThrown_thenAssertionSucceeds() { + String test = null; + assertThrows(NullPointerException.class, () -> { + test.length(); + }); + } + + @Test + public void whenDerivedExceptionThrown_thenAssertionSucceds() { + String test = null; + assertThrows(RuntimeException.class, () -> { + test.length(); + }); + } +} \ No newline at end of file diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/extensions/RegisterExtensionSampleExtension.java b/testing-modules/junit-5/src/test/java/com/baeldung/extensions/RegisterExtensionSampleExtension.java new file mode 100644 index 0000000000..64f4d8fd3e --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/extensions/RegisterExtensionSampleExtension.java @@ -0,0 +1,34 @@ +package com.baeldung.extensions; + +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This extension is meant to demonstrate the use of RegisterExtension. + */ +public class RegisterExtensionSampleExtension implements BeforeAllCallback, BeforeEachCallback { + + private final String type; + Logger logger = LoggerFactory.getLogger(RegisterExtensionSampleExtension.class); + + public RegisterExtensionSampleExtension(String type) { + this.type = type; + } + + @Override + public void beforeAll(ExtensionContext extensionContext) throws Exception { + logger.info("Type {} In beforeAll : {}", type, extensionContext.getDisplayName()); + } + + @Override + public void beforeEach(ExtensionContext extensionContext) throws Exception { + logger.info("Type {} In beforeEach : {}", type, extensionContext.getDisplayName()); + } + + public String getType() { + return type; + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java deleted file mode 100644 index 3b89508c88..0000000000 --- a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.junit5.spring; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import com.baeldung.junit5.Greetings; - -@ExtendWith(SpringExtension.class) -@ContextConfiguration(classes = { SpringTestConfiguration.class }) -public class GreetingsSpringTest { - - @Test - void whenCallingSayHello_thenReturnHello() { - assertTrue("Hello".equals(Greetings.sayHello())); - } - -} \ No newline at end of file diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java new file mode 100644 index 0000000000..317a0797ed --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.junit5.spring; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.junit5.Greetings; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { SpringTestConfiguration.class }) +public class GreetingsSpringUnitTest { + + @Test + void whenCallingSayHello_thenReturnHello() { + assertTrue("Hello".equals(Greetings.sayHello())); + } + +} \ No newline at end of file diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/methodorders/DefaultOrderOfExecutionUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/methodorders/DefaultOrderOfExecutionUnitTest.java new file mode 100644 index 0000000000..c269a0e9b6 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/methodorders/DefaultOrderOfExecutionUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.methodorders; + +import static org.junit.Assert.assertEquals; + +import org.junit.AfterClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +@FixMethodOrder(MethodSorters.DEFAULT) +public class DefaultOrderOfExecutionUnitTest { + private static StringBuilder output = new StringBuilder(""); + + @Test + public void secondTest() { + output.append("b"); + } + + @Test + public void thirdTest() { + output.append("c"); + } + + @Test + public void firstTest() { + output.append("a"); + } + + @AfterClass + public static void assertOutput() { + assertEquals(output.toString(), "cab"); + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/methodorders/JVMOrderOfExecutionUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/methodorders/JVMOrderOfExecutionUnitTest.java new file mode 100644 index 0000000000..c4996dacf3 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/methodorders/JVMOrderOfExecutionUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.methodorders; + +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +@FixMethodOrder(MethodSorters.JVM) +public class JVMOrderOfExecutionUnitTest { + + private static StringBuilder output = new StringBuilder(""); + + @Test + public void secondTest() { + output.append("b"); + } + + @Test + public void thirdTest() { + output.append("c"); + } + + @Test + public void firstTest() { + output.append("a"); + } +} \ No newline at end of file diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/methodorders/NameAscendingOrderOfExecutionUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/methodorders/NameAscendingOrderOfExecutionUnitTest.java new file mode 100644 index 0000000000..032bc81779 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/methodorders/NameAscendingOrderOfExecutionUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.methodorders; + +import static org.junit.Assert.assertEquals; + +import org.junit.AfterClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class NameAscendingOrderOfExecutionUnitTest { + private static StringBuilder output = new StringBuilder(""); + + @Test + public void secondTest() { + output.append("b"); + } + + @Test + public void thirdTest() { + output.append("c"); + } + + @Test + public void firstTest() { + output.append("a"); + } + + @AfterClass + public static void assertOutput() { + assertEquals(output.toString(), "abc"); + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleTest.java deleted file mode 100644 index fd7fd93d66..0000000000 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.migration.junit4; - -import org.junit.Ignore; -import org.junit.Test; -import org.junit.experimental.categories.Category; - -import com.baeldung.migration.junit4.categories.Annotations; -import com.baeldung.migration.junit4.categories.JUnit4Tests; - -@Category(value = { Annotations.class, JUnit4Tests.class }) -public class AnnotationTestExampleTest { - @Test(expected = Exception.class) - public void shouldRaiseAnException() throws Exception { - throw new Exception("This is my expected exception"); - } - - @Test(timeout = 1) - @Ignore - public void shouldFailBecauseTimeout() throws InterruptedException { - Thread.sleep(10); - } - -} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java new file mode 100644 index 0000000000..45671f200d --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.migration.junit4; + +import org.junit.Ignore; +import org.junit.Test; +import org.junit.experimental.categories.Category; + +import com.baeldung.migration.junit4.categories.Annotations; +import com.baeldung.migration.junit4.categories.JUnit4UnitTest; + +@Category(value = { Annotations.class, JUnit4UnitTest.class }) +public class AnnotationTestExampleUnitTest { + @Test(expected = Exception.class) + public void shouldRaiseAnException() throws Exception { + throw new Exception("This is my expected exception"); + } + + @Test(timeout = 1) + @Ignore + public void shouldFailBecauseTimeout() throws InterruptedException { + Thread.sleep(10); + } + +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleTest.java deleted file mode 100644 index ff2a05a8c4..0000000000 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.migration.junit4; - -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.List; - -import org.junit.Ignore; -import org.junit.Test; - -public class AssertionsExampleTest { - @Test - @Ignore - public void shouldFailBecauseTheNumbersAreNotEqualld() { - assertEquals("Numbers are not equal!", 2, 3); - } - - @Test - public void shouldAssertAllTheGroup() { - List list = Arrays.asList(1, 2, 3); - assertEquals("List is not incremental", list.get(0) - .intValue(), 1); - assertEquals("List is not incremental", list.get(1) - .intValue(), 2); - assertEquals("List is not incremental", list.get(2) - .intValue(), 3); - } -} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java new file mode 100644 index 0000000000..63446f583d --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.migration.junit4; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Ignore; +import org.junit.Test; + +public class AssertionsExampleUnitTest { + @Test + @Ignore + public void shouldFailBecauseTheNumbersAreNotEqualld() { + assertEquals("Numbers are not equal!", 2, 3); + } + + @Test + public void shouldAssertAllTheGroup() { + List list = Arrays.asList(1, 2, 3); + assertEquals("List is not incremental", list.get(0) + .intValue(), 1); + assertEquals("List is not incremental", list.get(1) + .intValue(), 2); + assertEquals("List is not incremental", list.get(2) + .intValue(), 3); + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsTest.java deleted file mode 100644 index e26b10e7e5..0000000000 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.migration.junit4; - -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@RunWith(JUnit4.class) -public class BeforeAndAfterAnnotationsTest { - - private static final Logger LOG = LoggerFactory.getLogger(BeforeAndAfterAnnotationsTest.class); - - private List list; - - @Before - public void init() { - LOG.info("startup"); - list = new ArrayList<>(Arrays.asList("test1", "test2")); - } - - @After - public void finalize() { - LOG.info("finalize"); - list.clear(); - } - - @Test - public void whenCheckingListSize_ThenSizeEqualsToInit() { - LOG.info("executing test"); - assertEquals(2, list.size()); - - list.add("another test"); - } - - @Test - public void whenCheckingListSizeAgain_ThenSizeEqualsToInit() { - LOG.info("executing another test"); - assertEquals(2, list.size()); - - list.add("yet another test"); - } -} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java new file mode 100644 index 0000000000..aa3e46defb --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.migration.junit4; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@RunWith(JUnit4.class) +public class BeforeAndAfterAnnotationsUnitTest { + + private static final Logger LOG = LoggerFactory.getLogger(BeforeAndAfterAnnotationsUnitTest.class); + + private List list; + + @Before + public void init() { + LOG.info("startup"); + list = new ArrayList<>(Arrays.asList("test1", "test2")); + } + + @After + public void finalize() { + LOG.info("finalize"); + list.clear(); + } + + @Test + public void whenCheckingListSize_ThenSizeEqualsToInit() { + LOG.info("executing test"); + assertEquals(2, list.size()); + + list.add("another test"); + } + + @Test + public void whenCheckingListSizeAgain_ThenSizeEqualsToInit() { + LOG.info("executing another test"); + assertEquals(2, list.size()); + + list.add("yet another test"); + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsTest.java deleted file mode 100644 index 31717362ef..0000000000 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.migration.junit4; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@RunWith(JUnit4.class) -public class BeforeClassAndAfterClassAnnotationsTest { - - private static final Logger LOG = LoggerFactory.getLogger(BeforeClassAndAfterClassAnnotationsTest.class); - - @BeforeClass - public static void setup() { - LOG.info("startup - creating DB connection"); - } - - @AfterClass - public static void tearDown() { - LOG.info("closing DB connection"); - } - - @Test - public void simpleTest() { - LOG.info("simple test"); - } - - @Test - public void anotherSimpleTest() { - LOG.info("another simple test"); - } -} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java new file mode 100644 index 0000000000..8a82a75d3d --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.migration.junit4; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@RunWith(JUnit4.class) +public class BeforeClassAndAfterClassAnnotationsUnitTest { + + private static final Logger LOG = LoggerFactory.getLogger(BeforeClassAndAfterClassAnnotationsUnitTest.class); + + @BeforeClass + public static void setup() { + LOG.info("startup - creating DB connection"); + } + + @AfterClass + public static void tearDown() { + LOG.info("closing DB connection"); + } + + @Test + public void simpleTest() { + LOG.info("simple test"); + } + + @Test + public void anotherSimpleTest() { + LOG.info("another simple test"); + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionTest.java deleted file mode 100644 index 6cd2559f57..0000000000 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.migration.junit4; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -public class ExceptionAssertionTest { - - @Rule - public ExpectedException exceptionRule = ExpectedException.none(); - - @Test(expected = NullPointerException.class) - public void whenExceptionThrown_thenExpectationSatisfied() { - String test = null; - test.length(); - } - - @Test - public void whenExceptionThrown_thenRuleIsApplied() { - exceptionRule.expect(NumberFormatException.class); - exceptionRule.expectMessage("For input string"); - Integer.parseInt("1a"); - } -} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionUnitTest.java new file mode 100644 index 0000000000..afe4af8c4a --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.migration.junit4; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +public class ExceptionAssertionUnitTest { + + @Rule + public ExpectedException exceptionRule = ExpectedException.none(); + + @Test(expected = NullPointerException.class) + public void whenExceptionThrown_thenExpectationSatisfied() { + String test = null; + test.length(); + } + + @Test + public void whenExceptionThrown_thenRuleIsApplied() { + exceptionRule.expect(NumberFormatException.class); + exceptionRule.expectMessage("For input string"); + Integer.parseInt("1a"); + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleTest.java deleted file mode 100644 index 10af6a9254..0000000000 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.migration.junit4; - -import org.junit.Rule; -import org.junit.Test; - -import com.baeldung.migration.junit4.rules.TraceUnitTestRule; - -public class RuleExampleTest { - - @Rule - public final TraceUnitTestRule traceRuleTests = new TraceUnitTestRule(); - - @Test - public void whenTracingTests() { - System.out.println("This is my test"); - /*...*/ - } -} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java new file mode 100644 index 0000000000..969d1b370e --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.migration.junit4; + +import org.junit.Rule; +import org.junit.Test; + +import com.baeldung.migration.junit4.rules.TraceUnitTestRule; + +public class RuleExampleUnitTest { + + @Rule + public final TraceUnitTestRule traceRuleTests = new TraceUnitTestRule(); + + @Test + public void whenTracingTests() { + System.out.println("This is my test"); + /*...*/ + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4Tests.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4Tests.java deleted file mode 100644 index 6af63d58ab..0000000000 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4Tests.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.baeldung.migration.junit4.categories; - -public interface JUnit4Tests { - -} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java new file mode 100644 index 0000000000..dc5d4349f3 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java @@ -0,0 +1,5 @@ +package com.baeldung.migration.junit4.categories; + +public interface JUnit4UnitTest { + +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleTest.java deleted file mode 100644 index 07d8ae64e4..0000000000 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.migration.junit5; - -import java.time.Duration; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; - -@Tag("annotations") -@Tag("junit5") -@RunWith(JUnitPlatform.class) -public class AnnotationTestExampleTest { - @Test - public void shouldRaiseAnException() throws Exception { - Assertions.assertThrows(Exception.class, () -> { - throw new Exception("This is my expected exception"); - }); - } - - @Test - @Disabled - public void shouldFailBecauseTimeout() throws InterruptedException { - Assertions.assertTimeout(Duration.ofMillis(1), () -> Thread.sleep(10)); - } -} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java new file mode 100644 index 0000000000..c2bbfd4d07 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.migration.junit5; + +import java.time.Duration; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +@Tag("annotations") +@Tag("junit5") +@RunWith(JUnitPlatform.class) +public class AnnotationTestExampleUnitTest { + @Test + public void shouldRaiseAnException() throws Exception { + Assertions.assertThrows(Exception.class, () -> { + throw new Exception("This is my expected exception"); + }); + } + + @Test + @Disabled + public void shouldFailBecauseTimeout() throws InterruptedException { + Assertions.assertTimeout(Duration.ofMillis(1), () -> Thread.sleep(10)); + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java deleted file mode 100644 index 3cfe4c59f5..0000000000 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.migration.junit5; - -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; - -@RunWith(JUnitPlatform.class) -public class AssertionsExampleTest { - @Test - @Disabled - public void shouldFailBecauseTheNumbersAreNotEqual() { - Assertions.assertEquals(2, 3, "Numbers are not equal!"); - } - - @Test - @Disabled - public void shouldFailBecauseItsNotTrue_overloading() { - Assertions.assertTrue(() -> { - return false; - }, () -> "It's not true!"); - } - - @Test - public void shouldAssertAllTheGroup() { - List list = Arrays.asList(1, 2, 3); - - Assertions.assertAll("List is not incremental", () -> Assertions.assertEquals(list.get(0) - .intValue(), 1), () -> Assertions.assertEquals( - list.get(1) - .intValue(), - 2), - () -> Assertions.assertEquals(list.get(2) - .intValue(), 3)); - } -} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java new file mode 100644 index 0000000000..c35611aad1 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.migration.junit5; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +public class AssertionsExampleUnitTest { + @Test + @Disabled + public void shouldFailBecauseTheNumbersAreNotEqual() { + Assertions.assertEquals(2, 3, "Numbers are not equal!"); + } + + @Test + @Disabled + public void shouldFailBecauseItsNotTrue_overloading() { + Assertions.assertTrue(() -> { + return false; + }, () -> "It's not true!"); + } + + @Test + public void shouldAssertAllTheGroup() { + List list = Arrays.asList(1, 2, 3); + + Assertions.assertAll("List is not incremental", () -> Assertions.assertEquals(list.get(0) + .intValue(), 1), () -> Assertions.assertEquals( + list.get(1) + .intValue(), + 2), + () -> Assertions.assertEquals(list.get(2) + .intValue(), 3)); + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java new file mode 100644 index 0000000000..80201a3f44 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.migration.junit5; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.junit.jupiter.api.Assumptions.assumingThat; + +import org.junit.jupiter.api.Test; + +public class AssumptionUnitTest { + + @Test + public void trueAssumption() { + assumeTrue(5 > 1, () -> "5 is greater the 1"); + assertEquals(5 + 2, 7); + } + + @Test + public void falseAssumption() { + assumeFalse(5 < 1, () -> "5 is less then 1"); + assertEquals(5 + 2, 7); + } + + @Test + public void assumptionThat() { + String someString = "Just a string"; + assumingThat(someString.equals("Just a string"), () -> assertEquals(2 + 2, 4)); + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsTest.java deleted file mode 100644 index 9af837dcb1..0000000000 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.migration.junit5; - -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@RunWith(JUnitPlatform.class) -public class BeforeAllAndAfterAllAnnotationsTest { - - private static final Logger LOG = LoggerFactory.getLogger(BeforeAllAndAfterAllAnnotationsTest.class); - - @BeforeAll - public static void setup() { - LOG.info("startup - creating DB connection"); - } - - @AfterAll - public static void tearDown() { - LOG.info("closing DB connection"); - } - - @Test - public void simpleTest() { - LOG.info("simple test"); - } - - @Test - public void anotherSimpleTest() { - LOG.info("another simple test"); - } -} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java new file mode 100644 index 0000000000..b81e9b7b8e --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.migration.junit5; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@RunWith(JUnitPlatform.class) +public class BeforeAllAndAfterAllAnnotationsUnitTest { + + private static final Logger LOG = LoggerFactory.getLogger(BeforeAllAndAfterAllAnnotationsUnitTest.class); + + @BeforeAll + public static void setup() { + LOG.info("startup - creating DB connection"); + } + + @AfterAll + public static void tearDown() { + LOG.info("closing DB connection"); + } + + @Test + public void simpleTest() { + LOG.info("simple test"); + } + + @Test + public void anotherSimpleTest() { + LOG.info("another simple test"); + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsTest.java deleted file mode 100644 index 6302992a5b..0000000000 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.migration.junit5; - -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@RunWith(JUnitPlatform.class) -public class BeforeEachAndAfterEachAnnotationsTest { - - private static final Logger LOG = LoggerFactory.getLogger(BeforeEachAndAfterEachAnnotationsTest.class); - - private List list; - - @BeforeEach - public void init() { - LOG.info("startup"); - list = new ArrayList<>(Arrays.asList("test1", "test2")); - } - - @AfterEach - public void finalize() { - LOG.info("finalize"); - list.clear(); - } - - @Test - public void whenCheckingListSize_ThenSizeEqualsToInit() { - LOG.info("executing test"); - assertEquals(2, list.size()); - - list.add("another test"); - } - - @Test - public void whenCheckingListSizeAgain_ThenSizeEqualsToInit() { - LOG.info("executing another test"); - assertEquals(2, list.size()); - - list.add("yet another test"); - } -} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java new file mode 100644 index 0000000000..be916d66ea --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.migration.junit5; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@RunWith(JUnitPlatform.class) +public class BeforeEachAndAfterEachAnnotationsUnitTest { + + private static final Logger LOG = LoggerFactory.getLogger(BeforeEachAndAfterEachAnnotationsUnitTest.class); + + private List list; + + @BeforeEach + public void init() { + LOG.info("startup"); + list = new ArrayList<>(Arrays.asList("test1", "test2")); + } + + @AfterEach + public void finalize() { + LOG.info("finalize"); + list.clear(); + } + + @Test + public void whenCheckingListSize_ThenSizeEqualsToInit() { + LOG.info("executing test"); + assertEquals(2, list.size()); + + list.add("another test"); + } + + @Test + public void whenCheckingListSizeAgain_ThenSizeEqualsToInit() { + LOG.info("executing another test"); + assertEquals(2, list.size()); + + list.add("yet another test"); + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleTest.java deleted file mode 100644 index a05360250b..0000000000 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.migration.junit5; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; - -import com.baeldung.migration.junit5.extensions.TraceUnitExtension; - -@RunWith(JUnitPlatform.class) -@ExtendWith(TraceUnitExtension.class) -public class RuleExampleTest { - - @Test - public void whenTracingTests() { - System.out.println("This is my test"); - /*...*/ - } -} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java new file mode 100644 index 0000000000..7b1bcda730 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.migration.junit5; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +import com.baeldung.migration.junit5.extensions.TraceUnitExtension; + +@RunWith(JUnitPlatform.class) +@ExtendWith(TraceUnitExtension.class) +public class RuleExampleUnitTest { + + @Test + public void whenTracingTests() { + System.out.println("This is my test"); + /*...*/ + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorTest.java deleted file mode 100644 index cd6f2b7e4f..0000000000 --- a/testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorTest.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.baeldung.param; - -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.RepeatedTest; -import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; - -@RunWith(JUnitPlatform.class) -@DisplayName("Testing PersonValidator") -public class PersonValidatorTest { - - /** - * Nested class, uses ExtendWith - * {@link com.baeldung.param.ValidPersonParameterResolver ValidPersonParameterResolver} - * to feed Test methods with "good" data. - */ - @Nested - @DisplayName("When using Valid data") - @ExtendWith(ValidPersonParameterResolver.class) - public class ValidData { - - /** - * Repeat the test ten times, that way we have a good shot at - * running all of the data through at least once. - * - * @param person - * A valid Person object to validate. - */ - @RepeatedTest(value = 10) - @DisplayName("All first names are valid") - public void validateFirstName(Person person) { - try { - assertTrue(PersonValidator.validateFirstName(person)); - } catch (PersonValidator.ValidationException e) { - fail("Exception not expected: " + e.getLocalizedMessage()); - } - } - - /** - * Repeat the test ten times, that way we have a good shot at - * running all of the data through at least once. - * - * @param person - * A valid Person object to validate. - */ - @RepeatedTest(value = 10) - @DisplayName("All last names are valid") - public void validateLastName(Person person) { - try { - assertTrue(PersonValidator.validateLastName(person)); - } catch (PersonValidator.ValidationException e) { - fail("Exception not expected: " + e.getLocalizedMessage()); - } - } - - } - - /** - * Nested class, uses ExtendWith - * {@link com.baeldung.param.InvalidPersonParameterResolver InvalidPersonParameterResolver} - * to feed Test methods with "bad" data. - */ - @Nested - @DisplayName("When using Invalid data") - @ExtendWith(InvalidPersonParameterResolver.class) - public class InvalidData { - - /** - * Repeat the test ten times, that way we have a good shot at - * running all of the data through at least once. - * - * @param person - * An invalid Person object to validate. - */ - @RepeatedTest(value = 10) - @DisplayName("All first names are invalid") - public void validateFirstName(Person person) { - assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateFirstName(person)); - } - - /** - * Repeat the test ten times, that way we have a good shot at - * running all of the data through at least once. - * - * @param person - * An invalid Person object to validate. - */ - @RepeatedTest(value = 10) - @DisplayName("All first names are invalid") - public void validateLastName(Person person) { - assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateLastName(person)); - } - - } - -} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorUnitTest.java new file mode 100644 index 0000000000..3db44c9d63 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorUnitTest.java @@ -0,0 +1,102 @@ +package com.baeldung.param; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@DisplayName("Testing PersonValidator") +public class PersonValidatorUnitTest { + + /** + * Nested class, uses ExtendWith + * {@link com.baeldung.param.ValidPersonParameterResolver ValidPersonParameterResolver} + * to feed Test methods with "good" data. + */ + @Nested + @DisplayName("When using Valid data") + @ExtendWith(ValidPersonParameterResolver.class) + public class ValidData { + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * A valid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All first names are valid") + public void validateFirstName(Person person) { + try { + assertTrue(PersonValidator.validateFirstName(person)); + } catch (PersonValidator.ValidationException e) { + fail("Exception not expected: " + e.getLocalizedMessage()); + } + } + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * A valid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All last names are valid") + public void validateLastName(Person person) { + try { + assertTrue(PersonValidator.validateLastName(person)); + } catch (PersonValidator.ValidationException e) { + fail("Exception not expected: " + e.getLocalizedMessage()); + } + } + + } + + /** + * Nested class, uses ExtendWith + * {@link com.baeldung.param.InvalidPersonParameterResolver InvalidPersonParameterResolver} + * to feed Test methods with "bad" data. + */ + @Nested + @DisplayName("When using Invalid data") + @ExtendWith(InvalidPersonParameterResolver.class) + public class InvalidData { + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * An invalid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All first names are invalid") + public void validateFirstName(Person person) { + assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateFirstName(person)); + } + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * An invalid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All first names are invalid") + public void validateLastName(Person person) { + assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateLastName(person)); + } + + } + +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/runfromjava/FirstUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/runfromjava/FirstUnitTest.java new file mode 100644 index 0000000000..835132240e --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/runfromjava/FirstUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.runfromjava; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +class FirstUnitTest { + + @Test + void whenThis_thenThat() { + assertTrue(true); + } + + @Test + void whenSomething_thenSomething() { + assertTrue(true); + } + + @Test + void whenSomethingElse_thenSomethingElse() { + assertTrue(true); + } + +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/runfromjava/RunJUnit5TestsFromJava.java b/testing-modules/junit-5/src/test/java/com/baeldung/runfromjava/RunJUnit5TestsFromJava.java new file mode 100644 index 0000000000..309c1bc8c9 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/runfromjava/RunJUnit5TestsFromJava.java @@ -0,0 +1,59 @@ +package com.baeldung.runfromjava; + +import org.junit.platform.launcher.Launcher; +import org.junit.platform.launcher.LauncherDiscoveryRequest; +import org.junit.platform.launcher.TestPlan; +import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; +import org.junit.platform.launcher.core.LauncherFactory; +import org.junit.platform.launcher.listeners.SummaryGeneratingListener; +import org.junit.platform.launcher.listeners.TestExecutionSummary; + +import java.io.PrintWriter; + +import static org.junit.platform.engine.discovery.ClassNameFilter.includeClassNamePatterns; +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage; + +public class RunJUnit5TestsFromJava { + SummaryGeneratingListener listener = new SummaryGeneratingListener(); + + public void runOne() { + LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder + .request() + .selectors(selectClass(FirstUnitTest.class)) + .build(); + Launcher launcher = LauncherFactory.create(); + TestPlan testPlan = launcher.discover(request); + + launcher.registerTestExecutionListeners(listener); + launcher.execute(request); + } + + public void runAll() { + LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder + .request() + .selectors(selectPackage("com.baeldung.runfromjava")) + .filters(includeClassNamePatterns(".*Test")) + .build(); + Launcher launcher = LauncherFactory.create(); + + TestPlan testPlan = launcher.discover(request); + + launcher.registerTestExecutionListeners(listener); + + launcher.execute(request); + } + + public static void main(String[] args) { + RunJUnit5TestsFromJava runner = new RunJUnit5TestsFromJava(); + runner.runAll(); + + TestExecutionSummary summary = runner.listener.getSummary(); + summary.printTo(new PrintWriter(System.out)); + + runner.runOne(); + + summary = runner.listener.getSummary(); + summary.printTo(new PrintWriter(System.out)); + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/runfromjava/SecondUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/runfromjava/SecondUnitTest.java new file mode 100644 index 0000000000..b6a387d852 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/runfromjava/SecondUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.runfromjava; + +import org.junit.jupiter.api.RepeatedTest; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SecondUnitTest { + + @RepeatedTest(10) + void whenSomething_thenSomething() { + assertTrue(true); + } + + @RepeatedTest(5) + void whenSomethingElse_thenSomethingElse() { + assertTrue(true); + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/suites/AllTests.java b/testing-modules/junit-5/src/test/java/com/baeldung/suites/AllTests.java deleted file mode 100644 index 29452efc3d..0000000000 --- a/testing-modules/junit-5/src/test/java/com/baeldung/suites/AllTests.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.suites; - -import org.junit.platform.runner.JUnitPlatform; -import org.junit.platform.suite.api.SelectPackages; -import org.junit.runner.RunWith; - -@RunWith(JUnitPlatform.class) -@SelectPackages("com.baeldung") -// @SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class}) -public class AllTests { - -} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/suites/AllUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/suites/AllUnitTest.java new file mode 100644 index 0000000000..30b92ad428 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/suites/AllUnitTest.java @@ -0,0 +1,12 @@ +package com.baeldung.suites; + +import org.junit.platform.runner.JUnitPlatform; +import org.junit.platform.suite.api.SelectPackages; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@SelectPackages("com.baeldung") +// @SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class}) +public class AllUnitTest { + +} diff --git a/testing-modules/junit5-migration/README.md b/testing-modules/junit5-migration/README.md new file mode 100644 index 0000000000..5fe7fc1f16 --- /dev/null +++ b/testing-modules/junit5-migration/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [JUnit4 -> JUnit5 migration guide](http://www.baeldung.com/junit4-junit5-migration-guide) + diff --git a/testing-modules/junit5-migration/pom.xml b/testing-modules/junit5-migration/pom.xml new file mode 100644 index 0000000000..9d9d418774 --- /dev/null +++ b/testing-modules/junit5-migration/pom.xml @@ -0,0 +1,90 @@ + + + + 4.0.0 + + junit5-migration + 1.0-SNAPSHOT + junit5-migration + JUnit 4 -> JUnit 5 migration + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + + org.junit.platform + junit-platform-engine + ${junit.platform.version} + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit.vintage.version} + test + + + org.junit.jupiter + junit-jupiter-migrationsupport + ${junit.vintage.version} + test + + + + + + + src/test/resources + true + + + + + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + + + java + + + + + com.baeldung.TestLauncher + + + + + + + 5.2.0 + 1.2.0 + 5.2.0 + 2.21.0 + 1.6.0 + + + diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/AnnotationTestExampleUnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/AnnotationTestExampleUnitTest.java new file mode 100644 index 0000000000..a5f5c19c65 --- /dev/null +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/AnnotationTestExampleUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.junit4; + +import com.baeldung.junit4.categories.Annotations; +import com.baeldung.junit4.categories.JUnit4UnitTest; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.experimental.categories.Category; + +@Category(value = { Annotations.class, JUnit4UnitTest.class }) +public class AnnotationTestExampleUnitTest { + @Test(expected = Exception.class) + public void shouldRaiseAnException() throws Exception { + throw new Exception("This is my expected exception"); + } + + @Test(timeout = 1) + @Ignore + public void shouldFailBecauseTimeout() throws InterruptedException { + Thread.sleep(10); + } + +} diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/AssertionUnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/AssertionUnitTest.java new file mode 100644 index 0000000000..8979c9ecbc --- /dev/null +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/AssertionUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.junit4; + +import org.junit.Assert; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; + +import static org.hamcrest.CoreMatchers.hasItems; +import static org.junit.Assert.*; +import static org.junit.Assert.assertArrayEquals; + +@DisplayName("Test case for assertions") +public class AssertionUnitTest { + + @Test + @DisplayName("Arrays should be equals") + public void whenAssertingArraysEquality_thenEqual() { + char[] expected = {'J', 'u', 'p', 'i', 't', 'e', 'r'}; + char[] actual = "Jupiter".toCharArray(); + + assertArrayEquals("Arrays should be equal", expected, actual); + } + + @Test + public void givenMultipleAssertion_whenAssertingAll_thenOK() { + assertEquals("4 is 2 times 2", 4, 2 * 2); + assertEquals("java", "JAVA".toLowerCase()); + assertEquals("null is equal to null", null, null); + } + + @Test + public void testAssertThatHasItems() { + assertThat(Arrays.asList("Java", "Kotlin", "Scala"), hasItems("Java", "Kotlin")); + } +} diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/AssumeUnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/AssumeUnitTest.java new file mode 100644 index 0000000000..f7730a3dd8 --- /dev/null +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/AssumeUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.junit4; + + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assume.assumeFalse; +import static org.junit.Assume.assumeTrue; + +public class AssumeUnitTest { + + @Test + public void trueAssumption() { + assumeTrue("5 is greater the 1", 5 > 1); + assertEquals(5 + 2, 7); + } + + @Test + public void falseAssumption() { + assumeFalse("5 is less then 1", 5 < 1); + assertEquals(5 + 2, 7); + } +} diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/ExceptionAssertionUnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/ExceptionAssertionUnitTest.java new file mode 100644 index 0000000000..38e7f640a2 --- /dev/null +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/ExceptionAssertionUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.junit4; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +public class ExceptionAssertionUnitTest { + + @Rule + public ExpectedException exceptionRule = ExpectedException.none(); + + @Test(expected = NullPointerException.class) + public void whenExceptionThrown_thenExpectationSatisfied() { + String test = null; + test.length(); + } + + @Test + public void whenExceptionThrown_thenRuleIsApplied() { + exceptionRule.expect(NumberFormatException.class); + exceptionRule.expectMessage("For input string"); + Integer.parseInt("1a"); + } +} diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/RuleExampleUnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/RuleExampleUnitTest.java new file mode 100644 index 0000000000..35f96b4f6a --- /dev/null +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/RuleExampleUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.junit4; + +import org.junit.Rule; +import org.junit.Test; + +public class RuleExampleUnitTest { + + @Rule + public final TraceUnitTestRule traceRuleTests = new TraceUnitTestRule(); + + @Test + public void whenTracingTests() { + System.out.println("This is my test"); + /*...*/ + } +} diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/TestAnnotationsUnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/TestAnnotationsUnitTest.java new file mode 100644 index 0000000000..89c33cafe6 --- /dev/null +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/TestAnnotationsUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.junit4; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; + +import java.util.logging.Logger; + +public class TestAnnotationsUnitTest { + + private static final Logger log = Logger.getLogger(TestAnnotationsUnitTest.class.getName()); + + @BeforeClass + static void setup() { + log.info("@BeforeAll - executes once before all test methods in this class"); + } + + @Before + void init() { + log.info("@BeforeEach - executes before each test method in this class"); + } + + @After + void tearDown() { + log.info("@AfterEach - executed after each test method."); + } + + @AfterClass + static void done() { + log.info("@AfterAll - executed after all test methods."); + } + +} diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/TraceUnitTestRule.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/TraceUnitTestRule.java new file mode 100644 index 0000000000..9f4811da3d --- /dev/null +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/TraceUnitTestRule.java @@ -0,0 +1,35 @@ +package com.baeldung.junit4; + +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runners.model.MultipleFailureException; +import org.junit.runners.model.Statement; + +import java.util.ArrayList; +import java.util.List; + +public class TraceUnitTestRule implements TestRule { + + @Override + public Statement apply(Statement base, Description description) { + + return new Statement() { + @Override + public void evaluate() throws Throwable { + List errors = new ArrayList(); + + System.out.println("Starting test ... " + description.getMethodName()); + try { + base.evaluate(); + } catch (Throwable e) { + errors.add(e); + } finally { + System.out.println("... test finished. " + description.getMethodName()); + } + + MultipleFailureException.assertEmpty(errors); + } + }; + } + +} diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/categories/Annotations.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/categories/Annotations.java new file mode 100644 index 0000000000..22214d95b6 --- /dev/null +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/categories/Annotations.java @@ -0,0 +1,5 @@ +package com.baeldung.junit4.categories; + +public interface Annotations { + +} diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/categories/JUnit4UnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/categories/JUnit4UnitTest.java new file mode 100644 index 0000000000..a7474d5f24 --- /dev/null +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit4/categories/JUnit4UnitTest.java @@ -0,0 +1,5 @@ +package com.baeldung.junit4.categories; + +public interface JUnit4UnitTest { + +} diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/AnnotationTestExampleUnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/AnnotationTestExampleUnitTest.java new file mode 100644 index 0000000000..16de0be9d8 --- /dev/null +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/AnnotationTestExampleUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.junit5; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +import java.time.Duration; + +@Tag("annotations") +@Tag("junit5") +@RunWith(JUnitPlatform.class) +public class AnnotationTestExampleUnitTest { + @Test + public void shouldRaiseAnException() throws Exception { + Assertions.assertThrows(Exception.class, () -> { + throw new Exception("This is my expected exception"); + }); + } + + @Test + @Disabled + public void shouldFailBecauseTimeout() throws InterruptedException { + Assertions.assertTimeout(Duration.ofMillis(1), () -> Thread.sleep(10)); + } +} diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/AssertionUnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/AssertionUnitTest.java new file mode 100644 index 0000000000..d1d08c6e62 --- /dev/null +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/AssertionUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.junit5; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@DisplayName("Test case for assertions") +public class AssertionUnitTest { + + @Test + @DisplayName("Arrays should be equals") + public void whenAssertingArraysEquality_thenEqual() { + char[] expected = {'J', 'u', 'p', 'i', 't', 'e', 'r'}; + char[] actual = "Jupiter".toCharArray(); + + assertArrayEquals(expected, actual, "Arrays should be equal"); + } + + @Test + @DisplayName("The area of two polygons should be equal") + public void whenAssertingEquality_thenEqual() { + float square = 2 * 2; + float rectangle = 2 * 2; + + assertEquals(square, rectangle); + } + + @Test + public void givenMultipleAssertion_whenAssertingAll_thenOK() { + assertAll( + "heading", + () -> assertEquals(4, 2 * 2, "4 is 2 times 2"), + () -> assertEquals("java", "JAVA".toLowerCase()), + () -> assertEquals(null, null, "null is equal to null") + ); + } +} diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/AssumptionUnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/AssumptionUnitTest.java new file mode 100644 index 0000000000..4f3d827403 --- /dev/null +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/AssumptionUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.junit5; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.*; + +public class AssumptionUnitTest { + + @Test + public void trueAssumption() { + assumeTrue(5 > 1, () -> "5 is greater the 1"); + assertEquals(5 + 2, 7); + } + + @Test + public void falseAssumption() { + assumeFalse(5 < 1, () -> "5 is less then 1"); + assertEquals(5 + 2, 7); + } + + @Test + public void assumptionThat() { + String someString = "Just a string"; + assumingThat(someString.equals("Just a string"), () -> assertEquals(2 + 2, 4)); + } +} diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/ConditionalExecutionUnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/ConditionalExecutionUnitTest.java new file mode 100644 index 0000000000..7f76e237f1 --- /dev/null +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/ConditionalExecutionUnitTest.java @@ -0,0 +1,69 @@ +package com.baeldung.junit5; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.*; + +import static org.junit.jupiter.api.Assertions.*; + +public class ConditionalExecutionUnitTest { + + @Test + @EnabledOnOs({OS.MAC}) + void whenOperatingSystemIsMac_thenTestIsEnabled() { + assertEquals(5 + 2, 7); + } + + @Test + @DisabledOnOs({OS.WINDOWS}) + void whenOperatingSystemIsWindows_thenTestIsDisabled() { + assertEquals(5 + 2, 7); + } + + @Test + @EnabledOnJre({JRE.JAVA_8}) + void whenRunningTestsOnJRE8_thenTestIsEnabled() { + assertTrue(5 > 4, "5 is greater the 4"); + assertTrue(null == null, "null is equal to null"); + } + + @Test + @DisabledOnJre({JRE.JAVA_10}) + void whenRunningTestsOnJRE10_thenTestIsDisabled() { + assertTrue(5 > 4, "5 is greater the 4"); + assertTrue(null == null, "null is equal to null"); + } + + @Test + @EnabledIfSystemProperty(named = "os.arch", matches = ".*64.*") + public void whenRunningTestsOn64BitArchitectures_thenTestIsDisabled() { + Integer value = 5; // result of an algorithm + + assertNotEquals(0, value, "The result cannot be 0"); + } + + @Test + @DisabledIfSystemProperty(named = "ci-server", matches = "true") + public void whenRunningTestsOnCIServer_thenTestIsDisabled() { + Integer value = 5; // result of an algorithm + + assertNotEquals(0, value, "The result cannot be 0"); + } + + @Test + @EnabledIfEnvironmentVariable(named = "ENV", matches = "staging-server") + public void whenRunningTestsStagingServer_thenTestIsEnabled() { + char[] expected = {'J', 'u', 'p', 'i', 't', 'e', 'r'}; + char[] actual = "Jupiter".toCharArray(); + + assertArrayEquals(expected, actual, "Arrays should be equal"); + } + + @Test + @DisabledIfEnvironmentVariable(named = "ENV", matches = ".*development.*") + public void whenRunningTestsDevelopmentEnvironment_thenTestIsDisabled() { + char[] expected = {'J', 'u', 'p', 'i', 't', 'e', 'r'}; + char[] actual = "Jupiter".toCharArray(); + + assertArrayEquals(expected, actual, "Arrays should be equal"); + } +} diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/NestedUnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/NestedUnitTest.java new file mode 100644 index 0000000000..9eeff471ba --- /dev/null +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/NestedUnitTest.java @@ -0,0 +1,77 @@ +package com.baeldung.junit5; + +import org.junit.jupiter.api.*; + +import java.util.EmptyStackException; +import java.util.Stack; + +public class NestedUnitTest { + + Stack stack; + + @Test + @DisplayName("is instantiated with new Stack()") + void isInstantiatedWithNew() { + new Stack<>(); + } + + @Nested + @DisplayName("when new") + class WhenNew { + + @BeforeEach + void init() { + stack = new Stack<>(); + } + + @Test + @DisplayName("is empty") + void isEmpty() { + Assertions.assertTrue(stack.isEmpty()); + } + + @Test + @DisplayName("throws EmptyStackException when popped") + void throwsExceptionWhenPopped() { + Assertions.assertThrows(EmptyStackException.class, () -> stack.pop()); + } + + @Test + @DisplayName("throws EmptyStackException when peeked") + void throwsExceptionWhenPeeked() { + Assertions.assertThrows(EmptyStackException.class, () -> stack.peek()); + } + + @Nested + @DisplayName("after pushing an element") + class AfterPushing { + + String anElement = "an element"; + + @BeforeEach + void init() { + stack.push(anElement); + } + + @Test + @DisplayName("it is no longer empty") + void isEmpty() { + Assertions.assertFalse(stack.isEmpty()); + } + + @Test + @DisplayName("returns the element when popped and is empty") + void returnElementWhenPopped() { + Assertions.assertEquals(anElement, stack.pop()); + Assertions.assertTrue(stack.isEmpty()); + } + + @Test + @DisplayName("returns the element when peeked but remains not empty") + void returnElementWhenPeeked() { + Assertions.assertEquals(anElement, stack.peek()); + Assertions.assertFalse(stack.isEmpty()); + } + } + } +} diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/RuleExampleUnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/RuleExampleUnitTest.java new file mode 100644 index 0000000000..297d0f1730 --- /dev/null +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/RuleExampleUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.junit5; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@ExtendWith(TraceUnitExtension.class) +public class RuleExampleUnitTest { + + @Test + public void whenTracingTests() { + System.out.println("This is my test"); + /*...*/ + } +} diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/RuleMigrationSupportUnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/RuleMigrationSupportUnitTest.java new file mode 100644 index 0000000000..bbaa42ec7b --- /dev/null +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/RuleMigrationSupportUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.junit5; + +import org.junit.Rule; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; +import org.junit.rules.ExpectedException; + +@EnableRuleMigrationSupport +public class RuleMigrationSupportUnitTest { + + @Rule + public ExpectedException exceptionRule = ExpectedException.none(); + + @Test + public void whenExceptionThrown_thenExpectationSatisfied() { + exceptionRule.expect(NullPointerException.class); + String test = null; + test.length(); + } + + @Test + public void whenExceptionThrown_thenRuleIsApplied() { + exceptionRule.expect(NumberFormatException.class); + exceptionRule.expectMessage("For input string"); + Integer.parseInt("1a"); + } +} diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/TestAnnotationsUnitTest.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/TestAnnotationsUnitTest.java new file mode 100644 index 0000000000..8daf952747 --- /dev/null +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/TestAnnotationsUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.junit5; + +import org.junit.jupiter.api.*; + +import java.util.logging.Logger; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class TestAnnotationsUnitTest { + + private static final Logger log = Logger.getLogger(TestAnnotationsUnitTest.class.getName()); + + @BeforeAll + static void setup() { + log.info("@BeforeAll - executes once before all test methods in this class"); + } + + @BeforeEach + void init() { + log.info("@BeforeEach - executes before each test method in this class"); + } + + @Test + @Disabled + void disabledTest() { + assertTrue(false); + } + + @AfterEach + void tearDown() { + log.info("@AfterEach - executed after each test method."); + } + + @AfterAll + static void done() { + log.info("@AfterAll - executed after all test methods."); + } + +} diff --git a/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/TraceUnitExtension.java b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/TraceUnitExtension.java new file mode 100644 index 0000000000..bd5ae47d63 --- /dev/null +++ b/testing-modules/junit5-migration/src/test/java/com/baeldung/junit5/TraceUnitExtension.java @@ -0,0 +1,19 @@ +package com.baeldung.junit5; + +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; + +public class TraceUnitExtension implements AfterEachCallback, BeforeEachCallback { + + @Override + public void beforeEach(ExtensionContext context) throws Exception { + System.out.println("Starting test ... " + context.getDisplayName()); + } + + @Override + public void afterEach(ExtensionContext context) throws Exception { + System.out.println("... test finished. " + context.getDisplayName()); + } + +} diff --git a/testing-modules/mockito-2/pom.xml b/testing-modules/mockito-2/pom.xml index f51919858f..cab4d7977b 100644 --- a/testing-modules/mockito-2/pom.xml +++ b/testing-modules/mockito-2/pom.xml @@ -1,5 +1,5 @@ + 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 mockito-2 @@ -15,9 +15,6 @@ - UTF-8 - - - 2.8.9 + 2.21.0 diff --git a/testing-modules/mockito-2/src/main/resources/logback.xml b/testing-modules/mockito-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/testing-modules/mockito-2/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/LazyVerificationTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/LazyVerificationTest.java deleted file mode 100644 index 43b39d6859..0000000000 --- a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/LazyVerificationTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.mockito.java8; - -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import java.util.List; - -import org.junit.Test; -import org.mockito.exceptions.base.MockitoAssertionError; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.VerificationCollector; - -public class LazyVerificationTest { - - @Test - public void whenLazilyVerified_thenReportsMultipleFailures() { - VerificationCollector collector = MockitoJUnit.collector() - .assertLazily(); - - List mockList = mock(List.class); - verify(mockList).add("one"); - verify(mockList).clear(); - - try { - collector.collectAndReport(); - } catch (MockitoAssertionError error) { - assertTrue(error.getMessage() - .contains("1. Wanted but not invoked:")); - assertTrue(error.getMessage() - .contains("2. Wanted but not invoked:")); - } - } -} diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/LazyVerificationUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/LazyVerificationUnitTest.java new file mode 100644 index 0000000000..0e6921c7a1 --- /dev/null +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/LazyVerificationUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.mockito.java8; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import java.util.List; + +import org.junit.Test; +import org.mockito.exceptions.base.MockitoAssertionError; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.VerificationCollector; + +public class LazyVerificationUnitTest { + + @Test + public void whenLazilyVerified_thenReportsMultipleFailures() { + VerificationCollector collector = MockitoJUnit.collector() + .assertLazily(); + + List mockList = mock(List.class); + verify(mockList).add("one"); + verify(mockList).clear(); + + try { + collector.collectAndReport(); + } catch (MockitoAssertionError error) { + assertTrue(error.getMessage() + .contains("1. Wanted but not invoked:")); + assertTrue(error.getMessage() + .contains("2. Wanted but not invoked:")); + } + } +} diff --git a/testing-modules/mockito/README.md b/testing-modules/mockito/README.md index 5a8d2289a4..e1b9c27523 100644 --- a/testing-modules/mockito/README.md +++ b/testing-modules/mockito/README.md @@ -17,3 +17,5 @@ - [Hamcrest Text Matchers](http://www.baeldung.com/hamcrest-text-matchers) - [Hamcrest File Matchers](http://www.baeldung.com/hamcrest-file-matchers) - [Hamcrest Custom Matchers](http://www.baeldung.com/hamcrest-custom-matchers) +- [Hamcrest Common Core Matchers](http://www.baeldung.com/hamcrest-core-matchers) +- [Testing Callbacks with Mockito](http://www.baeldung.com/mockito-callbacks) diff --git a/testing-modules/mockito/pom.xml b/testing-modules/mockito/pom.xml index 45ce288fa9..acdd7eb2ac 100644 --- a/testing-modules/mockito/pom.xml +++ b/testing-modules/mockito/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung mockito @@ -9,11 +9,32 @@ com.baeldung parent-java - 0.0.1-SNAPSHOT - ../../parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + org.springframework + spring-core + ${spring-framework.version} + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework.data + spring-data-jpa + ${spring-data.version} + + + org.eclipse.persistence + javax.persistence + 2.1.1 + @@ -23,8 +44,6 @@ ${commons-lang3.version} - - @@ -39,7 +58,6 @@ ${powermock.version} test - org.hamcrest java-hamcrest @@ -49,35 +67,15 @@ org.springframework.boot spring-boot-starter - LATEST + ${spring-boot.version} test org.springframework.boot spring-boot-starter-test - LATEST + ${spring-boot.version} test - - org.springframework - spring-core - LATEST - - - org.springframework - spring-context - LATEST - - - org.eclipse.persistence - javax.persistence - 2.1.1 - - - org.springframework.data - spring-data-jpa - LATEST - @@ -88,10 +86,12 @@ true - + 2.0.4.RELEASE + 5.0.8.RELEASE + 2.0.9.RELEASE 19.0 3.5 diff --git a/testing-modules/mockito/src/main/java/org/baeldung/mockito/service/ActionHandler.java b/testing-modules/mockito/src/main/java/org/baeldung/mockito/service/ActionHandler.java new file mode 100644 index 0000000000..289dcff399 --- /dev/null +++ b/testing-modules/mockito/src/main/java/org/baeldung/mockito/service/ActionHandler.java @@ -0,0 +1,26 @@ +package org.baeldung.mockito.service; + +public class ActionHandler { + + private Service service; + + public ActionHandler(Service service) { + this.service = service; + } + + public void doAction() { + service.doAction("our-request", new Callback() { + @Override + public void reply(Response response) { + handleResponse(response); + } + }); + } + + private void handleResponse(Response response) { + if (response.isValid()) { + response.setData(new Data("Successful data response")); + } + } + +} diff --git a/testing-modules/mockito/src/main/java/org/baeldung/mockito/service/Callback.java b/testing-modules/mockito/src/main/java/org/baeldung/mockito/service/Callback.java new file mode 100644 index 0000000000..fb8d01ce2e --- /dev/null +++ b/testing-modules/mockito/src/main/java/org/baeldung/mockito/service/Callback.java @@ -0,0 +1,6 @@ +package org.baeldung.mockito.service; + +public interface Callback { + + void reply(T response); +} diff --git a/testing-modules/mockito/src/main/java/org/baeldung/mockito/service/Data.java b/testing-modules/mockito/src/main/java/org/baeldung/mockito/service/Data.java new file mode 100644 index 0000000000..665c05382c --- /dev/null +++ b/testing-modules/mockito/src/main/java/org/baeldung/mockito/service/Data.java @@ -0,0 +1,15 @@ +package org.baeldung.mockito.service; + +public class Data { + + private String message; + + public Data(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } + +} diff --git a/testing-modules/mockito/src/main/java/org/baeldung/mockito/service/Response.java b/testing-modules/mockito/src/main/java/org/baeldung/mockito/service/Response.java new file mode 100644 index 0000000000..22474a5ba7 --- /dev/null +++ b/testing-modules/mockito/src/main/java/org/baeldung/mockito/service/Response.java @@ -0,0 +1,24 @@ +package org.baeldung.mockito.service; + +public class Response { + + private Data data; + private boolean isValid = true; + + public boolean isValid() { + return isValid; + } + + public void setIsValid(boolean isValid) { + this.isValid = isValid; + } + + public void setData(Data data) { + this.data = data; + } + + public Data getData() { + return data; + } + +} diff --git a/testing-modules/mockito/src/main/java/org/baeldung/mockito/service/Service.java b/testing-modules/mockito/src/main/java/org/baeldung/mockito/service/Service.java new file mode 100644 index 0000000000..63434e53fb --- /dev/null +++ b/testing-modules/mockito/src/main/java/org/baeldung/mockito/service/Service.java @@ -0,0 +1,7 @@ +package org.baeldung.mockito.service; + +public interface Service { + + void doAction(String request, Callback callback); + +} diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorIntegrationTest.java b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorIntegrationTest.java new file mode 100644 index 0000000000..5e311c60f2 --- /dev/null +++ b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorIntegrationTest.java @@ -0,0 +1,51 @@ +package com.baeldung.powermockito.introduction; + +import static org.junit.Assert.assertEquals; +import static org.powermock.api.mockito.PowerMockito.doReturn; +import static org.powermock.api.mockito.PowerMockito.spy; +import static org.powermock.api.mockito.PowerMockito.verifyPrivate; +import static org.powermock.api.mockito.PowerMockito.when; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(fullyQualifiedNames = "com.baeldung.powermockito.introduction.LuckyNumberGenerator") +public class LuckyNumberGeneratorIntegrationTest { + + @Test + public final void givenPrivateMethodWithReturn_whenUsingPowerMockito_thenCorrect() throws Exception { + LuckyNumberGenerator mock = spy(new LuckyNumberGenerator()); + + when(mock, "getDefaultLuckyNumber").thenReturn(300); + + int result = mock.getLuckyNumber(null); + + assertEquals(300, result); + } + + @Test + public final void givenPrivateMethodWithArgumentAndReturn_whenUsingPowerMockito_thenCorrect() throws Exception { + LuckyNumberGenerator mock = spy(new LuckyNumberGenerator()); + + doReturn(1).when(mock, "getComputedLuckyNumber", ArgumentMatchers.anyInt()); + + int result = mock.getLuckyNumber("Jack"); + + assertEquals(1, result); + } + + @Test + public final void givenPrivateMethodWithNoArgumentAndReturn_whenUsingPowerMockito_thenCorrect() throws Exception { + LuckyNumberGenerator mock = spy(new LuckyNumberGenerator()); + + int result = mock.getLuckyNumber("Tyranosorous"); + + verifyPrivate(mock).invoke("saveIntoDatabase", ArgumentMatchers.anyString()); + assertEquals(10000, result); + } + +} diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorTest.java b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorTest.java deleted file mode 100644 index 2836bcd317..0000000000 --- a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.powermockito.introduction; - -import static org.junit.Assert.assertEquals; -import static org.powermock.api.mockito.PowerMockito.doReturn; -import static org.powermock.api.mockito.PowerMockito.spy; -import static org.powermock.api.mockito.PowerMockito.verifyPrivate; -import static org.powermock.api.mockito.PowerMockito.when; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -@RunWith(PowerMockRunner.class) -@PrepareForTest(fullyQualifiedNames = "com.baeldung.powermockito.introduction.LuckyNumberGenerator") -public class LuckyNumberGeneratorTest { - - @Test - public final void givenPrivateMethodWithReturn_whenUsingPowerMockito_thenCorrect() throws Exception { - LuckyNumberGenerator mock = spy(new LuckyNumberGenerator()); - - when(mock, "getDefaultLuckyNumber").thenReturn(300); - - int result = mock.getLuckyNumber(null); - - assertEquals(300, result); - } - - @Test - public final void givenPrivateMethodWithArgumentAndReturn_whenUsingPowerMockito_thenCorrect() throws Exception { - LuckyNumberGenerator mock = spy(new LuckyNumberGenerator()); - - doReturn(1).when(mock, "getComputedLuckyNumber", ArgumentMatchers.anyInt()); - - int result = mock.getLuckyNumber("Jack"); - - assertEquals(1, result); - } - - @Test - public final void givenPrivateMethodWithNoArgumentAndReturn_whenUsingPowerMockito_thenCorrect() throws Exception { - LuckyNumberGenerator mock = spy(new LuckyNumberGenerator()); - - int result = mock.getLuckyNumber("Tyranosorous"); - - verifyPrivate(mock).invoke("saveIntoDatabase", ArgumentMatchers.anyString()); - assertEquals(10000, result); - } - -} diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java index 4a98bbcb87..1b6431f0c2 100644 --- a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java +++ b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java @@ -7,6 +7,8 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.*; @RunWith(PowerMockRunner.class) @@ -23,7 +25,7 @@ public class PowerMockitoIntegrationTest { when(collaborator.helloMethod()).thenReturn("Hello Baeldung!"); String welcome = collaborator.helloMethod(); - Mockito.verify(collaborator).helloMethod(); + verify(collaborator).helloMethod(); assertEquals("Hello Baeldung!", welcome); } @@ -42,7 +44,7 @@ public class PowerMockitoIntegrationTest { assertEquals("Hello Baeldung!", firstWelcome); assertEquals("Hello Baeldung!", secondWelcome); - verifyStatic(Mockito.times(2)); + verifyStatic(times(2)); CollaboratorWithStaticMethods.firstMethod(Mockito.anyString()); verifyStatic(Mockito.never()); @@ -67,7 +69,7 @@ public class PowerMockitoIntegrationTest { when(mock.finalMethod()).thenReturn("I am a final mock method."); returnValue = mock.finalMethod(); - Mockito.verify(mock).finalMethod(); + verify(mock,times(3)).finalMethod(); assertEquals("I am a final mock method.", returnValue); when(mock, "privateMethod").thenReturn("I am a private mock method."); diff --git a/testing-modules/mockito/src/test/java/org/baeldung/bddmockito/BDDMockitoIntegrationTest.java b/testing-modules/mockito/src/test/java/org/baeldung/bddmockito/BDDMockitoIntegrationTest.java new file mode 100644 index 0000000000..e772b5e049 --- /dev/null +++ b/testing-modules/mockito/src/test/java/org/baeldung/bddmockito/BDDMockitoIntegrationTest.java @@ -0,0 +1,104 @@ +package org.baeldung.bddmockito; + +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.*; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; + + +public class BDDMockitoIntegrationTest { + + PhoneBookService phoneBookService; + PhoneBookRepository phoneBookRepository; + + String momContactName = "Mom"; + String momPhoneNumber = "01234"; + String xContactName = "x"; + String tooLongPhoneNumber = "01111111111111"; + + @Before + public void init() { + phoneBookRepository = Mockito.mock(PhoneBookRepository.class); + phoneBookService = new PhoneBookService(phoneBookRepository); + } + + @Test + public void givenValidContactName_whenSearchInPhoneBook_thenRetunPhoneNumber() { + given(phoneBookRepository.contains(momContactName)).willReturn(true); + given(phoneBookRepository.getPhoneNumberByContactName(momContactName)) + .will((InvocationOnMock invocation) -> { + if(invocation.getArgument(0).equals(momContactName)) { + return momPhoneNumber; + } else { + return null; + } + }); + + String phoneNumber = phoneBookService.search(momContactName); + + then(phoneBookRepository).should().contains(momContactName); + then(phoneBookRepository).should().getPhoneNumberByContactName(momContactName); + Assert.assertEquals(phoneNumber, momPhoneNumber); + } + + @Test + public void givenInvalidContactName_whenSearch_thenRetunNull() { + given(phoneBookRepository.contains(xContactName)).willReturn(false); + + String phoneNumber = phoneBookService.search(xContactName); + + then(phoneBookRepository).should().contains(xContactName); + then(phoneBookRepository).should(never()).getPhoneNumberByContactName(xContactName); + Assert.assertEquals(phoneNumber, null); + } + + @Test + public void givenValidContactNameAndPhoneNumber_whenRegister_thenSucceed() { + given(phoneBookRepository.contains(momContactName)).willReturn(false); + + phoneBookService.register(momContactName, momPhoneNumber); + + verify(phoneBookRepository).insert(momContactName, momPhoneNumber); + } + + @Test + public void givenEmptyPhoneNumber_whenRegister_thenFail() { + given(phoneBookRepository.contains(momContactName)).willReturn(false); + + phoneBookService.register(xContactName, ""); + + then(phoneBookRepository).should(never()).insert(momContactName, momPhoneNumber); + } + + @Test + public void givenLongPhoneNumber_whenRegister_thenFail() { + given(phoneBookRepository.contains(xContactName)).willReturn(false); + willThrow(new RuntimeException()) + .given(phoneBookRepository).insert(any(String.class), eq(tooLongPhoneNumber)); + + try { + phoneBookService.register(xContactName, tooLongPhoneNumber); + fail("Should throw exception"); + } catch (RuntimeException ex) { } + + then(phoneBookRepository).should(never()).insert(momContactName, tooLongPhoneNumber); + } + + @Test + public void givenExistentContactName_whenRegister_thenFail() { + given(phoneBookRepository.contains(momContactName)) + .willThrow(new RuntimeException("Name already exist")); + + try { + phoneBookService.register(momContactName, momPhoneNumber); + fail("Should throw exception"); + } catch(Exception ex) { } + + then(phoneBookRepository).should(never()).insert(momContactName, momPhoneNumber); + } + +} diff --git a/testing-modules/mockito/src/test/java/org/baeldung/bddmockito/BDDMockitoTest.java b/testing-modules/mockito/src/test/java/org/baeldung/bddmockito/BDDMockitoTest.java deleted file mode 100644 index 9cc586fb84..0000000000 --- a/testing-modules/mockito/src/test/java/org/baeldung/bddmockito/BDDMockitoTest.java +++ /dev/null @@ -1,104 +0,0 @@ -package org.baeldung.bddmockito; - -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.*; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; - - -public class BDDMockitoTest { - - PhoneBookService phoneBookService; - PhoneBookRepository phoneBookRepository; - - String momContactName = "Mom"; - String momPhoneNumber = "01234"; - String xContactName = "x"; - String tooLongPhoneNumber = "01111111111111"; - - @Before - public void init() { - phoneBookRepository = Mockito.mock(PhoneBookRepository.class); - phoneBookService = new PhoneBookService(phoneBookRepository); - } - - @Test - public void givenValidContactName_whenSearchInPhoneBook_thenRetunPhoneNumber() { - given(phoneBookRepository.contains(momContactName)).willReturn(true); - given(phoneBookRepository.getPhoneNumberByContactName(momContactName)) - .will((InvocationOnMock invocation) -> { - if(invocation.getArgument(0).equals(momContactName)) { - return momPhoneNumber; - } else { - return null; - } - }); - - String phoneNumber = phoneBookService.search(momContactName); - - then(phoneBookRepository).should().contains(momContactName); - then(phoneBookRepository).should().getPhoneNumberByContactName(momContactName); - Assert.assertEquals(phoneNumber, momPhoneNumber); - } - - @Test - public void givenInvalidContactName_whenSearch_thenRetunNull() { - given(phoneBookRepository.contains(xContactName)).willReturn(false); - - String phoneNumber = phoneBookService.search(xContactName); - - then(phoneBookRepository).should().contains(xContactName); - then(phoneBookRepository).should(never()).getPhoneNumberByContactName(xContactName); - Assert.assertEquals(phoneNumber, null); - } - - @Test - public void givenValidContactNameAndPhoneNumber_whenRegister_thenSucceed() { - given(phoneBookRepository.contains(momContactName)).willReturn(false); - - phoneBookService.register(momContactName, momPhoneNumber); - - verify(phoneBookRepository).insert(momContactName, momPhoneNumber); - } - - @Test - public void givenEmptyPhoneNumber_whenRegister_thenFail() { - given(phoneBookRepository.contains(momContactName)).willReturn(false); - - phoneBookService.register(xContactName, ""); - - then(phoneBookRepository).should(never()).insert(momContactName, momPhoneNumber); - } - - @Test - public void givenLongPhoneNumber_whenRegister_thenFail() { - given(phoneBookRepository.contains(xContactName)).willReturn(false); - willThrow(new RuntimeException()) - .given(phoneBookRepository).insert(any(String.class), eq(tooLongPhoneNumber)); - - try { - phoneBookService.register(xContactName, tooLongPhoneNumber); - fail("Should throw exception"); - } catch (RuntimeException ex) { } - - then(phoneBookRepository).should(never()).insert(momContactName, tooLongPhoneNumber); - } - - @Test - public void givenExistentContactName_whenRegister_thenFail() { - given(phoneBookRepository.contains(momContactName)) - .willThrow(new RuntimeException("Name already exist")); - - try { - phoneBookService.register(momContactName, momPhoneNumber); - fail("Should throw exception"); - } catch(Exception ex) { } - - then(phoneBookRepository).should(never()).insert(momContactName, momPhoneNumber); - } - -} diff --git a/testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestCoreMatchersTest.java b/testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestCoreMatchersTest.java deleted file mode 100644 index 8f3e96c956..0000000000 --- a/testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestCoreMatchersTest.java +++ /dev/null @@ -1,259 +0,0 @@ -package org.baeldung.hamcrest; - - -import com.google.common.collect.Lists; -import org.junit.Test; - -import java.util.List; - -import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.StringEndsWith.endsWith; -import static org.hamcrest.core.StringStartsWith.startsWith; - -public class HamcrestCoreMatchersTest { - - @Test - public void givenTestInput_WhenUsingIsForMatch() { - - // GIVEN - String testString = "hamcrest core"; - - // ASSERT - assertThat(testString, is("hamcrest core")); - assertThat(testString, is(equalTo("hamcrest core"))); - } - - @Test - public void givenDifferentStaticTypeTestInput_WhenUsingEqualToObject_ThenCorrect() { - - // GIVEN - Object original = 100; - - // ASSERT - assertThat(original, equalToObject(100)); - } - - @Test - public void givenTestInput_WhenUsingInstanceOfForClassTypeCheck() { - - assertThat("hamcrest", is(instanceOf(String.class))); - } - - @Test - public void givenTestInput_WhenUsingIsA_ThenAssertType() { - - assertThat("hamcrest core", isA(String.class)); - } - - @Test - public void givenTestInput_WhenUsingEqualToMatcherForEquality() { - - // GIVEN - String actualString = "Hamcrest Core"; - List actualList = Lists.newArrayList("hamcrest", "core"); - - // ASSERT - assertThat(actualString, is(equalTo("Hamcrest Core"))); - assertThat(actualList, is(equalTo(Lists.newArrayList("hamcrest", "core")))); - } - - @Test - public void givenTestInput_WhenUsingNotForMatch() { - - // GIVEN - String testString = "hamcrest"; - - // ASSERT - assertThat(testString, not("hamcrest core")); - assertThat(testString, is(not(equalTo("hamcrest core")))); - assertThat(testString, is(not(instanceOf(Integer.class)))); - } - - @Test - public void givenTestInput_WhenUsingNullValueForNullCheck() { - - // GIVEN - Integer nullObject = null; - - // ASSERT - assertThat(nullObject, is(nullValue())); - assertThat(nullObject, is(nullValue(Integer.class))); - } - - @Test - public void givenTestInput_WhenUsingNotNullValueForNotNullCheck() { - - // GIVEN - Integer testNumber = 123; - - // ASSERT - assertThat(testNumber, is(notNullValue())); - assertThat(testNumber, is(notNullValue(Integer.class))); - } - - @Test - public void givenString_WhenStartsWith_ThenCorrect() { - - // GIVEN - String testString = "hamcrest core"; - - // ASSERT - assertThat(testString, startsWith("hamcrest")); - } - - @Test - public void giveString_WhenStartsWithIgnoringCase_ThenCorrect() { - - // GIVEN - String testString = "hamcrest core"; - - // ASSERT - assertThat(testString, startsWithIgnoringCase("HAMCREST")); - } - - @Test - public void givenString_WhenEndsWith_ThenCorrect() { - - // GIVEN - String testString = "hamcrest core"; - - // ASSERT - assertThat(testString, endsWith("core")); - } - - @Test - public void givenString_WhenEndsWithIgnoringCase_ThenCorrect() { - - // GIVEN - String testString = "hamcrest core"; - - // ASSERT - assertThat(testString, endsWithIgnoringCase("CORE")); - } - - @Test - public void givenString_WhenContainsString_ThenCorrect() { - - // GIVEN - String testString = "hamcrest core"; - - // ASSERT - assertThat(testString, containsString("co")); - } - - @Test - public void givenString_WhenContainsStringIgnoringCase_ThenCorrect() { - - - // GIVEN - String testString = "hamcrest core"; - - // ASSERT - assertThat(testString, containsStringIgnoringCase("CO")); - } - - @Test - public void givenTestInput_WhenUsingHasItemInCollection() { - - // GIVEN - List list = Lists.newArrayList("java", "spring", "baeldung"); - - // ASSERT - assertThat(list, hasItem("java")); - assertThat(list, hasItem(isA(String.class))); - } - - - @Test - public void givenTestInput_WhenUsingHasItemsInCollection() { - - // GIVEN - List list = Lists.newArrayList("java", "spring", "baeldung"); - - // ASSERT - assertThat(list, hasItems("java", "baeldung")); - assertThat(list, hasItems(isA(String.class), endsWith("ing"))); - } - - @Test - public void givenTestInput_WhenUsingAnyForClassType() { - - assertThat("hamcrest", is(any(String.class))); - assertThat("hamcrest", is(any(Object.class))); - } - - @Test - public void givenTestInput_WhenUsingAllOfForAllMatchers() { - - // GIVEN - String testString = "Hamcrest Core"; - - // ASSERT - assertThat(testString, allOf(startsWith("Ham"), endsWith("ore"), containsString("Core"))); - } - - @Test - public void givenTestInput_WhenUsingAnyOfForAnyMatcher() { - - // GIVEN - String testString = "Hamcrest Core"; - - // ASSERT - assertThat(testString, anyOf(startsWith("Ham"), containsString("baeldung"))); - } - - @Test - public void givenTestInput_WhenUsingBothForMatcher() { - - // GIVEN - String testString = "Hamcrest Core Matchers"; - - // ASSERT - assertThat(testString, both(startsWith("Ham")).and(containsString("Core"))); - } - - @Test - public void givenTestInput_WhenUsingEitherForMatcher() { - - // GIVEN - String testString = "Hamcrest Core Matchers"; - - // ASSERT - assertThat(testString, either(startsWith("Bael")).or(containsString("Core"))); - } - - - @Test - public void givenTestInput_WhenUsingEveryItemForMatchInCollection() { - - // GIVEN - List testItems = Lists.newArrayList("Common", "Core", "Combinable"); - - // ASSERT - assertThat(testItems, everyItem(startsWith("Co"))); - } - - @Test - public void givenTwoTestInputs_WhenUsingSameInstanceForMatch() { - - // GIVEN - String string1 = "hamcrest"; - String string2 = string1; - - // ASSERT - assertThat(string1, is(sameInstance(string2))); - } - - @Test - public void givenTwoTestInputs_WhenUsingTheInstanceForMatch() { - // GIVEN - String string1 = "hamcrest"; - String string2 = string1; - - // ASSERT - assertThat(string1, is(theInstance(string2))); - } - -} - diff --git a/testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestCoreMatchersUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestCoreMatchersUnitTest.java new file mode 100644 index 0000000000..d66ed98e8d --- /dev/null +++ b/testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestCoreMatchersUnitTest.java @@ -0,0 +1,259 @@ +package org.baeldung.hamcrest; + + +import com.google.common.collect.Lists; +import org.junit.Test; + +import java.util.List; + +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.StringEndsWith.endsWith; +import static org.hamcrest.core.StringStartsWith.startsWith; + +public class HamcrestCoreMatchersUnitTest { + + @Test + public void givenTestInput_WhenUsingIsForMatch() { + + // GIVEN + String testString = "hamcrest core"; + + // ASSERT + assertThat(testString, is("hamcrest core")); + assertThat(testString, is(equalTo("hamcrest core"))); + } + + @Test + public void givenDifferentStaticTypeTestInput_WhenUsingEqualToObject_ThenCorrect() { + + // GIVEN + Object original = 100; + + // ASSERT + assertThat(original, equalToObject(100)); + } + + @Test + public void givenTestInput_WhenUsingInstanceOfForClassTypeCheck() { + + assertThat("hamcrest", is(instanceOf(String.class))); + } + + @Test + public void givenTestInput_WhenUsingIsA_ThenAssertType() { + + assertThat("hamcrest core", isA(String.class)); + } + + @Test + public void givenTestInput_WhenUsingEqualToMatcherForEquality() { + + // GIVEN + String actualString = "Hamcrest Core"; + List actualList = Lists.newArrayList("hamcrest", "core"); + + // ASSERT + assertThat(actualString, is(equalTo("Hamcrest Core"))); + assertThat(actualList, is(equalTo(Lists.newArrayList("hamcrest", "core")))); + } + + @Test + public void givenTestInput_WhenUsingNotForMatch() { + + // GIVEN + String testString = "hamcrest"; + + // ASSERT + assertThat(testString, not("hamcrest core")); + assertThat(testString, is(not(equalTo("hamcrest core")))); + assertThat(testString, is(not(instanceOf(Integer.class)))); + } + + @Test + public void givenTestInput_WhenUsingNullValueForNullCheck() { + + // GIVEN + Integer nullObject = null; + + // ASSERT + assertThat(nullObject, is(nullValue())); + assertThat(nullObject, is(nullValue(Integer.class))); + } + + @Test + public void givenTestInput_WhenUsingNotNullValueForNotNullCheck() { + + // GIVEN + Integer testNumber = 123; + + // ASSERT + assertThat(testNumber, is(notNullValue())); + assertThat(testNumber, is(notNullValue(Integer.class))); + } + + @Test + public void givenString_WhenStartsWith_ThenCorrect() { + + // GIVEN + String testString = "hamcrest core"; + + // ASSERT + assertThat(testString, startsWith("hamcrest")); + } + + @Test + public void giveString_WhenStartsWithIgnoringCase_ThenCorrect() { + + // GIVEN + String testString = "hamcrest core"; + + // ASSERT + assertThat(testString, startsWithIgnoringCase("HAMCREST")); + } + + @Test + public void givenString_WhenEndsWith_ThenCorrect() { + + // GIVEN + String testString = "hamcrest core"; + + // ASSERT + assertThat(testString, endsWith("core")); + } + + @Test + public void givenString_WhenEndsWithIgnoringCase_ThenCorrect() { + + // GIVEN + String testString = "hamcrest core"; + + // ASSERT + assertThat(testString, endsWithIgnoringCase("CORE")); + } + + @Test + public void givenString_WhenContainsString_ThenCorrect() { + + // GIVEN + String testString = "hamcrest core"; + + // ASSERT + assertThat(testString, containsString("co")); + } + + @Test + public void givenString_WhenContainsStringIgnoringCase_ThenCorrect() { + + + // GIVEN + String testString = "hamcrest core"; + + // ASSERT + assertThat(testString, containsStringIgnoringCase("CO")); + } + + @Test + public void givenTestInput_WhenUsingHasItemInCollection() { + + // GIVEN + List list = Lists.newArrayList("java", "spring", "baeldung"); + + // ASSERT + assertThat(list, hasItem("java")); + assertThat(list, hasItem(isA(String.class))); + } + + + @Test + public void givenTestInput_WhenUsingHasItemsInCollection() { + + // GIVEN + List list = Lists.newArrayList("java", "spring", "baeldung"); + + // ASSERT + assertThat(list, hasItems("java", "baeldung")); + assertThat(list, hasItems(isA(String.class), endsWith("ing"))); + } + + @Test + public void givenTestInput_WhenUsingAnyForClassType() { + + assertThat("hamcrest", is(any(String.class))); + assertThat("hamcrest", is(any(Object.class))); + } + + @Test + public void givenTestInput_WhenUsingAllOfForAllMatchers() { + + // GIVEN + String testString = "Hamcrest Core"; + + // ASSERT + assertThat(testString, allOf(startsWith("Ham"), endsWith("ore"), containsString("Core"))); + } + + @Test + public void givenTestInput_WhenUsingAnyOfForAnyMatcher() { + + // GIVEN + String testString = "Hamcrest Core"; + + // ASSERT + assertThat(testString, anyOf(startsWith("Ham"), containsString("baeldung"))); + } + + @Test + public void givenTestInput_WhenUsingBothForMatcher() { + + // GIVEN + String testString = "Hamcrest Core Matchers"; + + // ASSERT + assertThat(testString, both(startsWith("Ham")).and(containsString("Core"))); + } + + @Test + public void givenTestInput_WhenUsingEitherForMatcher() { + + // GIVEN + String testString = "Hamcrest Core Matchers"; + + // ASSERT + assertThat(testString, either(startsWith("Bael")).or(containsString("Core"))); + } + + + @Test + public void givenTestInput_WhenUsingEveryItemForMatchInCollection() { + + // GIVEN + List testItems = Lists.newArrayList("Common", "Core", "Combinable"); + + // ASSERT + assertThat(testItems, everyItem(startsWith("Co"))); + } + + @Test + public void givenTwoTestInputs_WhenUsingSameInstanceForMatch() { + + // GIVEN + String string1 = "hamcrest"; + String string2 = string1; + + // ASSERT + assertThat(string1, is(sameInstance(string2))); + } + + @Test + public void givenTwoTestInputs_WhenUsingTheInstanceForMatch() { + // GIVEN + String string1 = "hamcrest"; + String string2 = string1; + + // ASSERT + assertThat(string1, is(theInstance(string2))); + } + +} + diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java index f846907fd7..6ec3b34db5 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java @@ -24,7 +24,7 @@ public class MockitoMockIntegrationTest { } @Rule - private ExpectedException thrown = ExpectedException.none(); + public ExpectedException thrown = ExpectedException.none(); @Test public void whenUsingSimpleMock_thenCorrect() { diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsTest.java deleted file mode 100644 index 4de9a88dcc..0000000000 --- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.baeldung.mockito; - -import org.junit.Test; -import org.junit.runner.RunWith; -import static org.junit.Assert.assertEquals; - -import static org.mockito.Mockito.*; -import org.mockito.ArgumentCaptor; -import static org.mockito.Matchers.any; -import org.mockito.stubbing.Answer; -import org.mockito.runners.MockitoJUnitRunner; - -@RunWith(MockitoJUnitRunner.class) -public class MockitoVoidMethodsTest { - - @Test - public void whenAddCalledVerified() { - MyList mockVoid = mock(MyList.class); - mockVoid.add(0, ""); - verify(mockVoid, times(1)).add(0, ""); - } - - @Test(expected = Exception.class) - public void givenNull_addThrows() { - MyList mockVoid = mock(MyList.class); - doThrow().when(mockVoid).add(isA(Integer.class), isNull()); - mockVoid.add(0, null); - } - - @Test - public void whenAddCalledValueCaptured() { - MyList mockVoid = mock(MyList.class); - ArgumentCaptor valueCapture = ArgumentCaptor.forClass(String.class); - doNothing().when(mockVoid).add(any(Integer.class), valueCapture.capture()); - mockVoid.add(0, "captured"); - assertEquals("captured", valueCapture.getValue()); - } - - @Test - public void whenAddCalledAnswered() { - MyList mockVoid = mock(MyList.class); - doAnswer((Answer) invocation -> { - Object arg0 = invocation.getArgument(0); - Object arg1 = invocation.getArgument(1); - - //do something with the arguments here - assertEquals(3, arg0); - assertEquals("answer me", arg1); - - return null; - }).when(mockVoid).add(any(Integer.class), any(String.class)); - mockVoid.add(3, "answer me"); - } - - @Test - public void whenAddCalledRealMethodCalled() { - MyList mockVoid = mock(MyList.class); - doCallRealMethod().when(mockVoid).add(any(Integer.class), any(String.class)); - mockVoid.add(1, "real"); - verify(mockVoid, times(1)).add(1, "real"); - } -} diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsUnitTest.java new file mode 100644 index 0000000000..49360f8d6c --- /dev/null +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsUnitTest.java @@ -0,0 +1,62 @@ +package org.baeldung.mockito; + +import org.junit.Test; +import org.junit.runner.RunWith; +import static org.junit.Assert.assertEquals; + +import static org.mockito.Mockito.*; +import org.mockito.ArgumentCaptor; +import static org.mockito.Matchers.any; +import org.mockito.stubbing.Answer; +import org.mockito.runners.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class MockitoVoidMethodsUnitTest { + + @Test + public void whenAddCalledVerified() { + MyList mockVoid = mock(MyList.class); + mockVoid.add(0, ""); + verify(mockVoid, times(1)).add(0, ""); + } + + @Test(expected = Exception.class) + public void givenNull_addThrows() { + MyList mockVoid = mock(MyList.class); + doThrow().when(mockVoid).add(isA(Integer.class), isNull()); + mockVoid.add(0, null); + } + + @Test + public void whenAddCalledValueCaptured() { + MyList mockVoid = mock(MyList.class); + ArgumentCaptor valueCapture = ArgumentCaptor.forClass(String.class); + doNothing().when(mockVoid).add(any(Integer.class), valueCapture.capture()); + mockVoid.add(0, "captured"); + assertEquals("captured", valueCapture.getValue()); + } + + @Test + public void whenAddCalledAnswered() { + MyList mockVoid = mock(MyList.class); + doAnswer((Answer) invocation -> { + Object arg0 = invocation.getArgument(0); + Object arg1 = invocation.getArgument(1); + + //do something with the arguments here + assertEquals(3, arg0); + assertEquals("answer me", arg1); + + return null; + }).when(mockVoid).add(any(Integer.class), any(String.class)); + mockVoid.add(3, "answer me"); + } + + @Test + public void whenAddCalledRealMethodCalled() { + MyList mockVoid = mock(MyList.class); + doCallRealMethod().when(mockVoid).add(any(Integer.class), any(String.class)); + mockVoid.add(1, "real"); + verify(mockVoid, times(1)).add(1, "real"); + } +} diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/service/ActionHandlerUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/service/ActionHandlerUnitTest.java new file mode 100644 index 0000000000..c34a9a4a09 --- /dev/null +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/service/ActionHandlerUnitTest.java @@ -0,0 +1,65 @@ +package org.baeldung.mockito.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.verify; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.stubbing.Answer; + +public class ActionHandlerUnitTest { + + @Mock + private Service service; + + @Captor + private ArgumentCaptor> callbackCaptor; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void givenServiceWithValidResponse_whenCallbackReceived_thenProcessed() { + ActionHandler handler = new ActionHandler(service); + handler.doAction(); + + verify(service).doAction(anyString(), callbackCaptor.capture()); + + Callback callback = callbackCaptor.getValue(); + Response response = new Response(); + callback.reply(response); + + String expectedMessage = "Successful data response"; + Data data = response.getData(); + assertEquals("Should receive a successful message: ", expectedMessage, data.getMessage()); + } + + @Test + public void givenServiceWithInvalidResponse_whenCallbackReceived_thenNotProcessed() { + Response response = new Response(); + response.setIsValid(false); + + doAnswer((Answer) invocation -> { + Callback callback = invocation.getArgument(1); + callback.reply(response); + + Data data = response.getData(); + assertNull("No data in invalid response: ", data); + return null; + }).when(service) + .doAction(anyString(), any(Callback.class)); + + ActionHandler handler = new ActionHandler(service); + handler.doAction(); + } +} diff --git a/testing-modules/mocks/README.md b/testing-modules/mocks/README.md index fe8e197061..2b24ed8536 100644 --- a/testing-modules/mocks/README.md +++ b/testing-modules/mocks/README.md @@ -5,4 +5,4 @@ - [JMockit 101](http://www.baeldung.com/jmockit-101) - [Mockito vs EasyMock vs JMockit](http://www.baeldung.com/mockito-vs-easymock-vs-jmockit) - [EasyMock Argument Matchers](http://www.baeldung.com/easymock-argument-matchers) - +- [Mock Static Method using JMockit](https://www.baeldung.com/jmockit-static-method) diff --git a/testing-modules/mocks/jmockit/pom.xml b/testing-modules/mocks/jmockit/pom.xml index 0ce0818ca3..12bbe6b60d 100644 --- a/testing-modules/mocks/jmockit/pom.xml +++ b/testing-modules/mocks/jmockit/pom.xml @@ -1,6 +1,8 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + jmockit + jmockit com.baeldung @@ -9,13 +11,6 @@ ../ - jmockit - jmockit - - - 1.24 - - org.jmockit @@ -35,4 +30,8 @@ + + 1.24 + + \ No newline at end of file diff --git a/testing-modules/mocks/jmockit/src/main/java/com/baeldung/mocks/jmockit/AppManager.java b/testing-modules/mocks/jmockit/src/main/java/com/baeldung/mocks/jmockit/AppManager.java new file mode 100644 index 0000000000..615650ea6d --- /dev/null +++ b/testing-modules/mocks/jmockit/src/main/java/com/baeldung/mocks/jmockit/AppManager.java @@ -0,0 +1,26 @@ +package com.baeldung.mocks.jmockit; + +import java.util.Random; + +public class AppManager { + + public boolean managerResponse(String question) { + return AppManager.isResponsePositive(question); + } + + public static boolean isResponsePositive(String value) { + if (value == null) + return false; + int orgLength = value.length(); + int randomNumber = randomNumber(); + return orgLength == randomNumber ? true : false; + } + + private static int randomNumber() { + return new Random().nextInt(7); + } + + private static Integer stringToInteger(String num) { + return Integer.parseInt(num); + } +} diff --git a/testing-modules/mocks/jmockit/src/main/resources/logback.xml b/testing-modules/mocks/jmockit/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/testing-modules/mocks/jmockit/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/testing-modules/mocks/jmockit/src/test/java/com/baeldung/mocks/jmockit/AppManagerUnitTest.java b/testing-modules/mocks/jmockit/src/test/java/com/baeldung/mocks/jmockit/AppManagerUnitTest.java new file mode 100644 index 0000000000..2c5aa2a3ed --- /dev/null +++ b/testing-modules/mocks/jmockit/src/test/java/com/baeldung/mocks/jmockit/AppManagerUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.mocks.jmockit; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import mockit.Deencapsulation; +import mockit.Mock; +import mockit.MockUp; + +public class AppManagerUnitTest { + + private AppManager appManager; + + @BeforeEach + public void setUp() { + appManager = new AppManager(); + } + + @Test + public void givenAppManager_whenStaticMethodCalled_thenValidateExpectedResponse() { + new MockUp() { + @Mock + public boolean isResponsePositive(String value) { + return false; + } + }; + + Assertions.assertFalse(appManager.managerResponse("Why are you coming late?")); + } + + @Test + public void givenAppManager_whenPrivateStaticMethod_thenValidateExpectedResponse() { + final int response = Deencapsulation.invoke(AppManager.class, "stringToInteger", "110"); + Assertions.assertEquals(110, response); + } + + @Test + public void givenAppManager_whenPrivateStaticMethod_thenExpectException() { + Assertions.assertThrows(IllegalArgumentException.class, () -> { + Deencapsulation.invoke(AppManager.class, "stringToInteger", "11r"); + }); + } +} diff --git a/testing-modules/mocks/mock-comparisons/pom.xml b/testing-modules/mocks/mock-comparisons/pom.xml index 9328639ad8..ae36280300 100644 --- a/testing-modules/mocks/mock-comparisons/pom.xml +++ b/testing-modules/mocks/mock-comparisons/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 mock-comparisons mock-comparisons @@ -46,10 +46,10 @@ - 2.9.0 + 2.21.0 3.5.1 - 1.34 - UTF-8 + 1.41 + - \ No newline at end of file + diff --git a/testing-modules/mocks/mock-comparisons/src/main/resources/logback.xml b/testing-modules/mocks/mock-comparisons/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/testing-modules/mocks/mock-comparisons/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedTest.java deleted file mode 100755 index af2ef3e6da..0000000000 --- a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.easymock; - -import org.easymock.EasyMockRunner; -import org.easymock.Mock; -import org.easymock.TestSubject; -import org.junit.*; -import org.junit.runner.RunWith; - -import java.util.NoSuchElementException; - -import static org.easymock.EasyMock.*; - -@RunWith(EasyMockRunner.class) -public class BaeldungReaderAnnotatedTest { - - @Mock ArticleReader mockArticleReader; - - @Mock IArticleWriter mockArticleWriter; - - @TestSubject BaeldungReader baeldungReader = new BaeldungReader(); - - @Test - public void givenBaeldungReader_whenReadNext_thenNextArticleRead() { - expect(mockArticleReader.next()).andReturn(null); - replay(mockArticleReader); - baeldungReader.readNext(); - verify(mockArticleReader); - } - - @Mock BaeldungReader mockBaeldungReader; - - @Test - public void givenBaeldungReader_whenWrite_thenWriterCalled() { - expect(mockArticleWriter.write("title", "content")).andReturn(null); - replay(mockArticleWriter); - baeldungReader.write("title", "content"); - verify(mockArticleWriter); - } - - @Test - public void givenArticlesInReader_whenReadTillEnd_thenThrowException() { - expect(mockArticleReader.next()) - .andReturn(null) - .times(2) - .andThrow(new NoSuchElementException()); - replay(mockArticleReader); - try { - for (int i = 0; i < 3; i++) { - baeldungReader.readNext(); - } - } catch (Exception ignored) { - } - verify(mockArticleReader); - } - -} - diff --git a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedUnitTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedUnitTest.java new file mode 100755 index 0000000000..afacd8d8ad --- /dev/null +++ b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedUnitTest.java @@ -0,0 +1,57 @@ +package com.baeldung.easymock; + +import org.easymock.EasyMockRunner; +import org.easymock.Mock; +import org.easymock.TestSubject; +import org.junit.*; +import org.junit.runner.RunWith; + +import java.util.NoSuchElementException; + +import static org.easymock.EasyMock.*; + +@RunWith(EasyMockRunner.class) +public class BaeldungReaderAnnotatedUnitTest { + + @Mock ArticleReader mockArticleReader; + + @Mock IArticleWriter mockArticleWriter; + + @TestSubject BaeldungReader baeldungReader = new BaeldungReader(); + + @Test + public void givenBaeldungReader_whenReadNext_thenNextArticleRead() { + expect(mockArticleReader.next()).andReturn(null); + replay(mockArticleReader); + baeldungReader.readNext(); + verify(mockArticleReader); + } + + @Mock BaeldungReader mockBaeldungReader; + + @Test + public void givenBaeldungReader_whenWrite_thenWriterCalled() { + expect(mockArticleWriter.write("title", "content")).andReturn(null); + replay(mockArticleWriter); + baeldungReader.write("title", "content"); + verify(mockArticleWriter); + } + + @Test + public void givenArticlesInReader_whenReadTillEnd_thenThrowException() { + expect(mockArticleReader.next()) + .andReturn(null) + .times(2) + .andThrow(new NoSuchElementException()); + replay(mockArticleReader); + try { + for (int i = 0; i < 3; i++) { + baeldungReader.readNext(); + } + } catch (Exception ignored) { + } + verify(mockArticleReader); + } + +} + diff --git a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedWithRuleTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedWithRuleTest.java deleted file mode 100755 index 28ed1484fc..0000000000 --- a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedWithRuleTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.easymock; - -import org.easymock.EasyMockRule; -import org.easymock.Mock; -import org.easymock.TestSubject; -import org.junit.*; - -import java.util.NoSuchElementException; - -import static org.easymock.EasyMock.*; - -public class BaeldungReaderAnnotatedWithRuleTest { - - @Rule public EasyMockRule mockRule = new EasyMockRule(this); - - @Mock ArticleReader mockArticleReader; - - @Mock IArticleWriter mockArticleWriter; - - @TestSubject BaeldungReader baeldungReader = new BaeldungReader(); - - @Test - public void givenBaeldungReader_whenReadNext_thenNextArticleRead() { - expect(mockArticleReader.next()).andReturn(null); - replay(mockArticleReader); - baeldungReader.readNext(); - verify(mockArticleReader); - } - - @Mock BaeldungReader mockBaeldungReader; - - @Test - public void givenBaeldungReader_whenWrite_thenWriterCalled() { - expect(mockArticleWriter.write("title", "content")).andReturn(null); - replay(mockArticleWriter); - baeldungReader.write("title", "content"); - verify(mockArticleWriter); - } - - @Test - public void givenArticlesInReader_whenReadTillEnd_thenThrowException() { - expect(mockArticleReader.next()) - .andReturn(null) - .times(2) - .andThrow(new NoSuchElementException()); - replay(mockArticleReader); - try { - for (int i = 0; i < 3; i++) { - baeldungReader.readNext(); - } - } catch (Exception ignored) { - } - verify(mockArticleReader); - } - -} - diff --git a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedWithRuleUnitTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedWithRuleUnitTest.java new file mode 100755 index 0000000000..086ed88888 --- /dev/null +++ b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedWithRuleUnitTest.java @@ -0,0 +1,57 @@ +package com.baeldung.easymock; + +import org.easymock.EasyMockRule; +import org.easymock.Mock; +import org.easymock.TestSubject; +import org.junit.*; + +import java.util.NoSuchElementException; + +import static org.easymock.EasyMock.*; + +public class BaeldungReaderAnnotatedWithRuleUnitTest { + + @Rule public EasyMockRule mockRule = new EasyMockRule(this); + + @Mock ArticleReader mockArticleReader; + + @Mock IArticleWriter mockArticleWriter; + + @TestSubject BaeldungReader baeldungReader = new BaeldungReader(); + + @Test + public void givenBaeldungReader_whenReadNext_thenNextArticleRead() { + expect(mockArticleReader.next()).andReturn(null); + replay(mockArticleReader); + baeldungReader.readNext(); + verify(mockArticleReader); + } + + @Mock BaeldungReader mockBaeldungReader; + + @Test + public void givenBaeldungReader_whenWrite_thenWriterCalled() { + expect(mockArticleWriter.write("title", "content")).andReturn(null); + replay(mockArticleWriter); + baeldungReader.write("title", "content"); + verify(mockArticleWriter); + } + + @Test + public void givenArticlesInReader_whenReadTillEnd_thenThrowException() { + expect(mockArticleReader.next()) + .andReturn(null) + .times(2) + .andThrow(new NoSuchElementException()); + replay(mockArticleReader); + try { + for (int i = 0; i < 3; i++) { + baeldungReader.readNext(); + } + } catch (Exception ignored) { + } + verify(mockArticleReader); + } + +} + diff --git a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockDelegationTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockDelegationTest.java deleted file mode 100755 index 3ff0d6416e..0000000000 --- a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockDelegationTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.easymock; - -import org.easymock.*; -import org.junit.*; - -import static org.easymock.EasyMock.*; - -public class BaeldungReaderMockDelegationTest { - - EasyMockSupport easyMockSupport = new EasyMockSupport(); - - @Test - public void givenBaeldungReader_whenReadAndWriteSequencially_thenWorks() { - ArticleReader mockArticleReader = easyMockSupport.createMock(ArticleReader.class); - IArticleWriter mockArticleWriter = easyMockSupport.createMock(IArticleWriter.class); - BaeldungReader baeldungReader = new BaeldungReader(mockArticleReader, mockArticleWriter); - - expect(mockArticleReader.next()).andReturn(null); - expect(mockArticleWriter.write("title", "content")).andReturn(""); - easyMockSupport.replayAll(); - - baeldungReader.readNext(); - baeldungReader.write("title", "content"); - easyMockSupport.verifyAll(); - } - -} \ No newline at end of file diff --git a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockDelegationUnitTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockDelegationUnitTest.java new file mode 100755 index 0000000000..89d3a2baee --- /dev/null +++ b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockDelegationUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.easymock; + +import org.easymock.*; +import org.junit.*; + +import static org.easymock.EasyMock.*; + +public class BaeldungReaderMockDelegationUnitTest { + + EasyMockSupport easyMockSupport = new EasyMockSupport(); + + @Test + public void givenBaeldungReader_whenReadAndWriteSequencially_thenWorks() { + ArticleReader mockArticleReader = easyMockSupport.createMock(ArticleReader.class); + IArticleWriter mockArticleWriter = easyMockSupport.createMock(IArticleWriter.class); + BaeldungReader baeldungReader = new BaeldungReader(mockArticleReader, mockArticleWriter); + + expect(mockArticleReader.next()).andReturn(null); + expect(mockArticleWriter.write("title", "content")).andReturn(""); + easyMockSupport.replayAll(); + + baeldungReader.readNext(); + baeldungReader.write("title", "content"); + easyMockSupport.verifyAll(); + } + +} \ No newline at end of file diff --git a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockSupportTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockSupportTest.java deleted file mode 100755 index 3bed89927f..0000000000 --- a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockSupportTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.easymock; - -import org.easymock.*; -import org.junit.*; -import org.junit.runner.RunWith; - -import java.util.NoSuchElementException; - -import static org.easymock.EasyMock.*; -import static org.junit.Assert.assertEquals; - -@RunWith(EasyMockRunner.class) -public class BaeldungReaderMockSupportTest extends EasyMockSupport { - - @TestSubject BaeldungReader baeldungReader = new BaeldungReader(); - @Mock ArticleReader mockArticleReader; - @Mock IArticleWriter mockArticleWriter; - - @Test - public void givenBaeldungReader_whenReadAndWriteSequencially_thenWorks() { - expect(mockArticleReader.next()) - .andReturn(null) - .times(2) - .andThrow(new NoSuchElementException()); - expect(mockArticleWriter.write("title", "content")).andReturn("BAEL-201801"); - replayAll(); - - Exception expectedException = null; - try { - for (int i = 0; i < 3; i++) { - baeldungReader.readNext(); - } - } catch (Exception exception) { - expectedException = exception; - } - String articleId = baeldungReader.write("title", "content"); - verifyAll(); - assertEquals(NoSuchElementException.class, expectedException.getClass()); - assertEquals("BAEL-201801", articleId); - } - -} \ No newline at end of file diff --git a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockSupportUnitTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockSupportUnitTest.java new file mode 100755 index 0000000000..cd0c906949 --- /dev/null +++ b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockSupportUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.easymock; + +import org.easymock.*; +import org.junit.*; +import org.junit.runner.RunWith; + +import java.util.NoSuchElementException; + +import static org.easymock.EasyMock.*; +import static org.junit.Assert.assertEquals; + +@RunWith(EasyMockRunner.class) +public class BaeldungReaderMockSupportUnitTest extends EasyMockSupport { + + @TestSubject BaeldungReader baeldungReader = new BaeldungReader(); + @Mock ArticleReader mockArticleReader; + @Mock IArticleWriter mockArticleWriter; + + @Test + public void givenBaeldungReader_whenReadAndWriteSequencially_thenWorks() { + expect(mockArticleReader.next()) + .andReturn(null) + .times(2) + .andThrow(new NoSuchElementException()); + expect(mockArticleWriter.write("title", "content")).andReturn("BAEL-201801"); + replayAll(); + + Exception expectedException = null; + try { + for (int i = 0; i < 3; i++) { + baeldungReader.readNext(); + } + } catch (Exception exception) { + expectedException = exception; + } + String articleId = baeldungReader.write("title", "content"); + verifyAll(); + assertEquals(NoSuchElementException.class, expectedException.getClass()); + assertEquals("BAEL-201801", articleId); + } + +} \ No newline at end of file diff --git a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderTest.java deleted file mode 100755 index 5b485357fd..0000000000 --- a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderTest.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.baeldung.easymock; - -import org.junit.*; - -import java.util.NoSuchElementException; - -import static org.easymock.EasyMock.*; -import static org.junit.Assert.assertEquals; - -public class BaeldungReaderTest { - - private BaeldungReader baeldungReader; - - private ArticleReader mockArticleReader; - - private IArticleWriter mockArticleWriter; - - @Test - public void givenBaeldungReader_whenReadNext_thenNextArticleRead() { - mockArticleReader = mock(ArticleReader.class); - baeldungReader = new BaeldungReader(mockArticleReader); - - expect(mockArticleReader.next()).andReturn(null); - replay(mockArticleReader); - - BaeldungArticle article = baeldungReader.readNext(); - verify(mockArticleReader); - assertEquals(null, article); - } - - @Test - public void givenBaeldungReader_whenReadNextAndSkimTopics_thenAllAllowed() { - mockArticleReader = strictMock(ArticleReader.class); - baeldungReader = new BaeldungReader(mockArticleReader); - - expect(mockArticleReader.next()).andReturn(null); - expect(mockArticleReader.ofTopic("easymock")).andReturn(null); - replay(mockArticleReader); - - baeldungReader.readNext(); - baeldungReader.readTopic("easymock"); - verify(mockArticleReader); - } - - @Test - public void givenBaeldungReader_whenReadNextAndOthers_thenAllowed() { - mockArticleReader = niceMock(ArticleReader.class); - baeldungReader = new BaeldungReader(mockArticleReader); - - expect(mockArticleReader.next()).andReturn(null); - replay(mockArticleReader); - - baeldungReader.readNext(); - baeldungReader.readTopic("easymock"); - verify(mockArticleReader); - } - - @Test - public void givenBaeldungReader_whenWriteMaliciousContent_thenArgumentIllegal() { - mockArticleWriter = mock(IArticleWriter.class); - baeldungReader = new BaeldungReader(mockArticleWriter); - expect(mockArticleWriter.write("easymock", "")).andThrow(new IllegalArgumentException()); - replay(mockArticleWriter); - - Exception expectedException = null; - try { - baeldungReader.write("easymock", ""); - } catch (Exception exception) { - expectedException = exception; - } - - verify(mockArticleWriter); - assertEquals(IllegalArgumentException.class, expectedException.getClass()); - } - - @Test - public void givenBaeldungReader_whenWrite_thenWriterCalled() { - mockArticleWriter = mock(IArticleWriter.class); - baeldungReader = new BaeldungReader(mockArticleWriter); - expect(mockArticleWriter.write("title", "content")).andReturn(null); - replay(mockArticleWriter); - String articleId = baeldungReader.write("title", "content"); - verify(mockArticleWriter); - assertEquals(null, articleId); - } - - @Test - public void givenArticlesInReader_whenReadTillEnd_thenThrowException() { - ArticleReader mockArticleReader = mock(ArticleReader.class); - baeldungReader = new BaeldungReader(mockArticleReader); - expect(mockArticleReader.next()) - .andReturn(null) - .times(2) - .andThrow(new NoSuchElementException()); - replay(mockArticleReader); - try { - for (int i = 0; i < 3; i++) { - baeldungReader.readNext(); - } - } catch (Exception ignored) { - } - verify(mockArticleReader); - } - -} \ No newline at end of file diff --git a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderUnitTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderUnitTest.java new file mode 100755 index 0000000000..31f6af116c --- /dev/null +++ b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderUnitTest.java @@ -0,0 +1,105 @@ +package com.baeldung.easymock; + +import org.junit.*; + +import java.util.NoSuchElementException; + +import static org.easymock.EasyMock.*; +import static org.junit.Assert.assertEquals; + +public class BaeldungReaderUnitTest { + + private BaeldungReader baeldungReader; + + private ArticleReader mockArticleReader; + + private IArticleWriter mockArticleWriter; + + @Test + public void givenBaeldungReader_whenReadNext_thenNextArticleRead() { + mockArticleReader = mock(ArticleReader.class); + baeldungReader = new BaeldungReader(mockArticleReader); + + expect(mockArticleReader.next()).andReturn(null); + replay(mockArticleReader); + + BaeldungArticle article = baeldungReader.readNext(); + verify(mockArticleReader); + assertEquals(null, article); + } + + @Test + public void givenBaeldungReader_whenReadNextAndSkimTopics_thenAllAllowed() { + mockArticleReader = strictMock(ArticleReader.class); + baeldungReader = new BaeldungReader(mockArticleReader); + + expect(mockArticleReader.next()).andReturn(null); + expect(mockArticleReader.ofTopic("easymock")).andReturn(null); + replay(mockArticleReader); + + baeldungReader.readNext(); + baeldungReader.readTopic("easymock"); + verify(mockArticleReader); + } + + @Test + public void givenBaeldungReader_whenReadNextAndOthers_thenAllowed() { + mockArticleReader = niceMock(ArticleReader.class); + baeldungReader = new BaeldungReader(mockArticleReader); + + expect(mockArticleReader.next()).andReturn(null); + replay(mockArticleReader); + + baeldungReader.readNext(); + baeldungReader.readTopic("easymock"); + verify(mockArticleReader); + } + + @Test + public void givenBaeldungReader_whenWriteMaliciousContent_thenArgumentIllegal() { + mockArticleWriter = mock(IArticleWriter.class); + baeldungReader = new BaeldungReader(mockArticleWriter); + expect(mockArticleWriter.write("easymock", "")).andThrow(new IllegalArgumentException()); + replay(mockArticleWriter); + + Exception expectedException = null; + try { + baeldungReader.write("easymock", ""); + } catch (Exception exception) { + expectedException = exception; + } + + verify(mockArticleWriter); + assertEquals(IllegalArgumentException.class, expectedException.getClass()); + } + + @Test + public void givenBaeldungReader_whenWrite_thenWriterCalled() { + mockArticleWriter = mock(IArticleWriter.class); + baeldungReader = new BaeldungReader(mockArticleWriter); + expect(mockArticleWriter.write("title", "content")).andReturn(null); + replay(mockArticleWriter); + String articleId = baeldungReader.write("title", "content"); + verify(mockArticleWriter); + assertEquals(null, articleId); + } + + @Test + public void givenArticlesInReader_whenReadTillEnd_thenThrowException() { + ArticleReader mockArticleReader = mock(ArticleReader.class); + baeldungReader = new BaeldungReader(mockArticleReader); + expect(mockArticleReader.next()) + .andReturn(null) + .times(2) + .andThrow(new NoSuchElementException()); + replay(mockArticleReader); + try { + for (int i = 0; i < 3; i++) { + baeldungReader.readNext(); + } + } catch (Exception ignored) { + } + verify(mockArticleReader); + } + +} \ No newline at end of file diff --git a/testing-modules/mocks/pom.xml b/testing-modules/mocks/pom.xml index b005164413..6473f07c13 100644 --- a/testing-modules/mocks/pom.xml +++ b/testing-modules/mocks/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 diff --git a/testing-modules/mockserver/pom.xml b/testing-modules/mockserver/pom.xml index 96c86a23d7..c2fa2870e2 100644 --- a/testing-modules/mockserver/pom.xml +++ b/testing-modules/mockserver/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.baeldung mockserver @@ -20,13 +19,11 @@ mockserver-netty ${mock-sever-netty-version} - org.mock-server mockserver-client-java ${mock-sever-netty-version} - org.apache.httpcomponents httpclient diff --git a/testing-modules/mockserver/src/main/resources/logback.xml b/testing-modules/mockserver/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/testing-modules/mockserver/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/testing-modules/parallel-tests-junit/math-test-functions/pom.xml b/testing-modules/parallel-tests-junit/math-test-functions/pom.xml new file mode 100644 index 0000000000..18d2b562f3 --- /dev/null +++ b/testing-modules/parallel-tests-junit/math-test-functions/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + + com.baeldung + parallel-tests-junit + 0.0.1-SNAPSHOT + + math-test-functions + math-test-functions + http://maven.apache.org + + UTF-8 + + + + junit + junit + 4.12 + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.0 + + all + 10 + 2 + 2 + 6 + 3.5 + 5 + true + + FunctionTestSuite.class + + + + + + diff --git a/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ArithmeticFunctionTest.java b/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ArithmeticFunctionTest.java new file mode 100644 index 0000000000..df0aa695fc --- /dev/null +++ b/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ArithmeticFunctionTest.java @@ -0,0 +1,28 @@ +package com.baeldung; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class ArithmeticFunctionTest { + + @Test + public void test_addingIntegers_returnsSum() { + assertEquals(22, Math.addExact(10, 12)); + } + + @Test + public void test_multiplyingIntegers_returnsProduct() { + assertEquals(120, Math.multiplyExact(10, 12)); + } + + @Test + public void test_subtractingIntegers_returnsDifference() { + assertEquals(2, Math.subtractExact(12, 10)); + } + + @Test + public void test_minimumInteger() { + assertEquals(10, Math.min(10, 12)); + } +} diff --git a/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ComparisonFunctionTest.java b/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ComparisonFunctionTest.java new file mode 100644 index 0000000000..4f72c87279 --- /dev/null +++ b/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ComparisonFunctionTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class ComparisonFunctionTest { + + @Test + public void test_findMax() { + assertEquals(20, Math.max(10, 20)); + } + + @Test + public void test_findMin() { + assertEquals(10, Math.min(10, 20)); + } + +} diff --git a/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/FunctionTestSuite.java b/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/FunctionTestSuite.java new file mode 100644 index 0000000000..4fe551b365 --- /dev/null +++ b/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/FunctionTestSuite.java @@ -0,0 +1,11 @@ +package com.baeldung; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ ComparisonFunctionTest.class, ArithmeticFunctionTest.class }) +public class FunctionTestSuite { + +} diff --git a/testing-modules/parallel-tests-junit/pom.xml b/testing-modules/parallel-tests-junit/pom.xml new file mode 100644 index 0000000000..3fd4e695e5 --- /dev/null +++ b/testing-modules/parallel-tests-junit/pom.xml @@ -0,0 +1,12 @@ + + + 4.0.0 + com.baeldung + parallel-tests-junit + 0.0.1-SNAPSHOT + pom + + math-test-functions + string-test-functions + + diff --git a/testing-modules/parallel-tests-junit/string-test-functions/pom.xml b/testing-modules/parallel-tests-junit/string-test-functions/pom.xml new file mode 100644 index 0000000000..af61cfce8e --- /dev/null +++ b/testing-modules/parallel-tests-junit/string-test-functions/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + + com.baeldung + parallel-tests-junit + 0.0.1-SNAPSHOT + + string-test-functions + string-test-functions + http://maven.apache.org + + UTF-8 + + + + + junit + junit + 4.12 + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.0 + + all + true + 2 + + + + + diff --git a/testing-modules/parallel-tests-junit/string-test-functions/src/test/java/com/baeldung/StringFunctionTest.java b/testing-modules/parallel-tests-junit/string-test-functions/src/test/java/com/baeldung/StringFunctionTest.java new file mode 100644 index 0000000000..7f2bc5e5e7 --- /dev/null +++ b/testing-modules/parallel-tests-junit/string-test-functions/src/test/java/com/baeldung/StringFunctionTest.java @@ -0,0 +1,18 @@ +package com.baeldung; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class StringFunctionTest { + + @Test + public void test_upperCase() { + assertEquals("TESTCASE", "testCase".toUpperCase()); + } + + @Test + public void test_indexOf() { + assertEquals(1, "testCase".indexOf("e")); + } +} diff --git a/testing-modules/rest-assured/pom.xml b/testing-modules/rest-assured/pom.xml index 3452cdae22..ed7e5e3577 100644 --- a/testing-modules/rest-assured/pom.xml +++ b/testing-modules/rest-assured/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung rest-assured @@ -9,8 +9,8 @@ com.baeldung parent-java - 0.0.1-SNAPSHOT - ../../parent-java + 0.0.1-SNAPSHOT + ../../parent-java @@ -168,7 +168,6 @@ commons-collections ${commons-collections.version} - @@ -181,7 +180,6 @@ 1.4.7 9.4.0.v20161208 - 3.5 3.2.2 diff --git a/testing-modules/rest-testing/pom.xml b/testing-modules/rest-testing/pom.xml index 8ebe86b9bb..0e54980683 100644 --- a/testing-modules/rest-testing/pom.xml +++ b/testing-modules/rest-testing/pom.xml @@ -1,17 +1,17 @@ + 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 rest-testing 0.1-SNAPSHOT - rest-testing com.baeldung parent-java - 0.0.1-SNAPSHOT - ../../parent-java + 0.0.1-SNAPSHOT + ../../parent-java @@ -116,7 +116,6 @@ 19.0 3.5 - 2.5 2.9.0 @@ -131,7 +130,6 @@ 2.6 - \ No newline at end of file diff --git a/testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java index aa0c6696a4..834d266cc6 100644 --- a/testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java +++ b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java @@ -1,19 +1,5 @@ package com.baeldung.rest.wiremock.introduction; -import com.github.tomakehurst.wiremock.junit.WireMockRule; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.junit.Rule; -import org.junit.Test; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Scanner; - import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; @@ -29,16 +15,46 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.junit.Assert.assertEquals; +import java.io.IOException; +import java.io.InputStream; +import java.net.ServerSocket; +import java.util.Scanner; + +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.junit.Rule; +import org.junit.Test; +import com.github.tomakehurst.wiremock.junit.WireMockRule; + public class JUnitManagedIntegrationTest { private static final String BAELDUNG_WIREMOCK_PATH = "/baeldung/wiremock"; private static final String APPLICATION_JSON = "application/json"; - + static int port; + + static { + + try { + // Get a free port + ServerSocket s = new ServerSocket(0); + port = s.getLocalPort(); + s.close(); + + } catch (IOException e) { + // No OPS + } + } + @Rule - public WireMockRule wireMockRule = new WireMockRule(); + public WireMockRule wireMockRule = new WireMockRule(port); @Test public void givenJUnitManagedServer_whenMatchingURL_thenCorrect() throws IOException { + stubFor(get(urlPathMatching("/baeldung/.*")) .willReturn(aResponse() .withStatus(200) @@ -46,7 +62,7 @@ public class JUnitManagedIntegrationTest { .withBody("\"testing-library\": \"WireMock\""))); CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet request = new HttpGet("http://localhost:8080/baeldung/wiremock"); + HttpGet request = new HttpGet(String.format("http://localhost:%s/baeldung/wiremock", port)); HttpResponse httpResponse = httpClient.execute(request); String stringResponse = convertHttpResponseToString(httpResponse); @@ -66,7 +82,7 @@ public class JUnitManagedIntegrationTest { .withBody("!!! Service Unavailable !!!"))); CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet request = new HttpGet("http://localhost:8080/baeldung/wiremock"); + HttpGet request = new HttpGet(String.format("http://localhost:%s/baeldung/wiremock", port)); request.addHeader("Accept", "text/html"); HttpResponse httpResponse = httpClient.execute(request); String stringResponse = convertHttpResponseToString(httpResponse); @@ -91,7 +107,7 @@ public class JUnitManagedIntegrationTest { StringEntity entity = new StringEntity(jsonString); CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpPost request = new HttpPost("http://localhost:8080/baeldung/wiremock"); + HttpPost request = new HttpPost(String.format("http://localhost:%s/baeldung/wiremock", port)); request.addHeader("Content-Type", APPLICATION_JSON); request.setEntity(entity); HttpResponse response = httpClient.execute(request); @@ -137,7 +153,7 @@ public class JUnitManagedIntegrationTest { private HttpResponse generateClientAndReceiveResponseForPriorityTests() throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet request = new HttpGet("http://localhost:8080/baeldung/wiremock"); + HttpGet request = new HttpGet(String.format("http://localhost:%s/baeldung/wiremock", port)); request.addHeader("Accept", "text/xml"); return httpClient.execute(request); } diff --git a/testing-modules/runjunitfromjava/src/main/resources/logback.xml b/testing-modules/runjunitfromjava/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/testing-modules/runjunitfromjava/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/testing-modules/runjunitfromjava/src/test/java/com/baeldung/junit4/runfromjava/FirstUnitTest.java b/testing-modules/runjunitfromjava/src/test/java/com/baeldung/junit4/runfromjava/FirstUnitTest.java new file mode 100644 index 0000000000..588a1e5d66 --- /dev/null +++ b/testing-modules/runjunitfromjava/src/test/java/com/baeldung/junit4/runfromjava/FirstUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.junit4.runfromjava; + +import org.junit.Test; + +import static org.junit.Assert.assertTrue; + + +public class FirstUnitTest { + + @Test + public void whenThis_thenThat() { + assertTrue(true); + } + + @Test + public void whenSomething_thenSomething() { + assertTrue(true); + } + + @Test + public void whenSomethingElse_thenSomethingElse() { + assertTrue(true); + } + +} diff --git a/testing-modules/runjunitfromjava/src/test/java/com/baeldung/junit4/runfromjava/SecondUnitTest.java b/testing-modules/runjunitfromjava/src/test/java/com/baeldung/junit4/runfromjava/SecondUnitTest.java new file mode 100644 index 0000000000..e2d75021cf --- /dev/null +++ b/testing-modules/runjunitfromjava/src/test/java/com/baeldung/junit4/runfromjava/SecondUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.junit4.runfromjava; + +import org.junit.Test; + +import static org.junit.Assert.assertTrue; + +public class SecondUnitTest { + + @Test + public void whenSomething_thenSomething() { + assertTrue(true); + } + + @Test + public void whensomethingElse_thenSomethingElse() { + assertTrue(true); + } +} diff --git a/testing-modules/runjunitfromjava/src/test/java/com/baeldung/junit5/runfromjava/FirstUnitTest.java b/testing-modules/runjunitfromjava/src/test/java/com/baeldung/junit5/runfromjava/FirstUnitTest.java new file mode 100644 index 0000000000..57c505781d --- /dev/null +++ b/testing-modules/runjunitfromjava/src/test/java/com/baeldung/junit5/runfromjava/FirstUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.junit5.runfromjava; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +class FirstUnitTest { + + @Test + void whenThis_thenThat() { + assertTrue(true); + } + + @Test + void whenSomething_thenSomething() { + assertTrue(true); + } + + @Test + void whenSomethingElse_thenSomethingElse() { + assertTrue(true); + } + +} diff --git a/testing-modules/runjunitfromjava/src/test/java/com/baeldung/junit5/runfromjava/SecondUnitTest.java b/testing-modules/runjunitfromjava/src/test/java/com/baeldung/junit5/runfromjava/SecondUnitTest.java new file mode 100644 index 0000000000..fbfb68898b --- /dev/null +++ b/testing-modules/runjunitfromjava/src/test/java/com/baeldung/junit5/runfromjava/SecondUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.junit5.runfromjava; + +import org.junit.jupiter.api.RepeatedTest; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SecondUnitTest { + + @RepeatedTest(10) + void whenSomething_thenSomething() { + assertTrue(true); + } + + @RepeatedTest(5) + void whenSomethingElse_thenSomethingElse() { + assertTrue(true); + } +} diff --git a/testing-modules/selenium-junit-testng/pom.xml b/testing-modules/selenium-junit-testng/pom.xml index 194871b58e..e22f7421cf 100644 --- a/testing-modules/selenium-junit-testng/pom.xml +++ b/testing-modules/selenium-junit-testng/pom.xml @@ -1,5 +1,5 @@ + 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 selenium-junit-testng @@ -12,29 +12,6 @@ ../../ - - src - - - - live - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - **/*LiveTest.java - - - - - - - - org.seleniumhq.selenium @@ -60,10 +37,34 @@ org.hamcrest hamcrest-all - 1.3 + ${org.hamcrest.version} + + src + + + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*LiveTest.java + + + + + + + + 6.10 3.4.0 diff --git a/testing-modules/selenium-junit-testng/src/main/resources/logback.xml b/testing-modules/selenium-junit-testng/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/testing-modules/selenium-junit-testng/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/testing-modules/spring-testing/README.md b/testing-modules/spring-testing/README.md index a96ddccabb..aed330d260 100644 --- a/testing-modules/spring-testing/README.md +++ b/testing-modules/spring-testing/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: +* [Mockito.mock() vs @Mock vs @MockBean](http://www.baeldung.com/java-spring-mockito-mock-mockbean) diff --git a/testing-modules/spring-testing/src/main/resources/logback.xml b/testing-modules/spring-testing/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/testing-modules/spring-testing/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/testing-modules/test-containers/README.md b/testing-modules/test-containers/README.md new file mode 100644 index 0000000000..f4f424194f --- /dev/null +++ b/testing-modules/test-containers/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Docker Test Containers in Java Tests](http://www.baeldung.com/docker-test-containers) diff --git a/testing-modules/test-containers/pom.xml b/testing-modules/test-containers/pom.xml new file mode 100644 index 0000000000..1f4c483988 --- /dev/null +++ b/testing-modules/test-containers/pom.xml @@ -0,0 +1,115 @@ + + + 4.0.0 + + + test-containers + 1.0-SNAPSHOT + test-containers + Intro to Java Test Containers + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit.vintage.version} + test + + + org.apache.logging.log4j + log4j-core + ${log4j2.version} + + + org.testcontainers + testcontainers + ${testcontainers.version} + + + org.testcontainers + postgresql + ${testcontainers.version} + + + org.testcontainers + selenium + ${testcontainers.version} + + + org.postgresql + postgresql + ${postgresql.version} + + + org.seleniumhq.selenium + selenium-remote-driver + ${selenium-remote-driver.version} + + + + + + + src/test/resources + true + + + + + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + + + java + + + + + com.baeldung.TestLauncher + + + + + + + 5.1.0 + 1.0.1 + 4.12.1 + 2.8.2 + 1.4.196 + 2.21.0 + 5.0.1.RELEASE + 1.7.2 + 42.2.2 + 3.12.0 + 2.21.0 + + + diff --git a/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/DockerComposeContainerLiveTest.java b/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/DockerComposeContainerLiveTest.java new file mode 100644 index 0000000000..438c4dee23 --- /dev/null +++ b/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/DockerComposeContainerLiveTest.java @@ -0,0 +1,47 @@ +package com.baeldung.testconainers; + +import static org.junit.Assert.assertEquals; + +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; + +import org.junit.ClassRule; +import org.junit.Test; +import org.testcontainers.containers.DockerComposeContainer; + +public class DockerComposeContainerLiveTest { + @ClassRule + public static DockerComposeContainer compose = + new DockerComposeContainer( + new File("src/test/resources/test-compose.yml")) + .withExposedService("simpleWebServer_1", 80); + + @Test + public void givenSimpleWebServerContainer_whenGetReuqest_thenReturnsResponse() + throws Exception { + String address = "http://" + compose.getServiceHost("simpleWebServer_1", 80) + + ":" + compose.getServicePort("simpleWebServer_1", 80); + String response = simpleGetRequest(address); + + assertEquals(response, "Hello World!"); + } + + private String simpleGetRequest(String address) throws Exception { + URL url = new URL(address); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + StringBuffer content = new StringBuffer(); + while ((inputLine = in.readLine()) != null) { + content.append(inputLine); + } + in.close(); + + return content.toString(); + } +} diff --git a/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/GenericContainerLiveTest.java b/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/GenericContainerLiveTest.java new file mode 100644 index 0000000000..90b9d3a6c3 --- /dev/null +++ b/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/GenericContainerLiveTest.java @@ -0,0 +1,51 @@ +package com.baeldung.testconainers; + +import static org.junit.Assert.assertEquals; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; + +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.platform.commons.annotation.Testable; +import org.testcontainers.containers.GenericContainer; + +@Testable +public class GenericContainerLiveTest { + @ClassRule + public static GenericContainer simpleWebServer = + new GenericContainer("alpine:3.2") + .withExposedPorts(80) + .withCommand("/bin/sh", "-c", "while true; do echo " + + "\"HTTP/1.1 200 OK\n\nHello World!\" | nc -l -p 80; done"); + + @Test + public void givenSimpleWebServerContainer_whenGetReuqest_thenReturnsResponse() + throws Exception { + String address = "http://" + + simpleWebServer.getContainerIpAddress() + + ":" + simpleWebServer.getMappedPort(80); + String response = simpleGetRequest(address); + + assertEquals(response, "Hello World!"); + } + + private String simpleGetRequest(String address) throws Exception { + URL url = new URL(address); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + + BufferedReader in = new BufferedReader( + new InputStreamReader(con.getInputStream())); + String inputLine; + StringBuffer content = new StringBuffer(); + while ((inputLine = in.readLine()) != null) { + content.append(inputLine); + } + in.close(); + + return content.toString(); + } +} diff --git a/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/PostgreSqlContainerLiveTest.java b/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/PostgreSqlContainerLiveTest.java new file mode 100644 index 0000000000..ca53f7da13 --- /dev/null +++ b/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/PostgreSqlContainerLiveTest.java @@ -0,0 +1,36 @@ +package com.baeldung.testconainers; + +import static org.junit.Assert.assertEquals; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.platform.commons.annotation.Testable; +import org.testcontainers.containers.PostgreSQLContainer; + +@Testable +public class PostgreSqlContainerLiveTest { + @Rule + public PostgreSQLContainer postgresContainer = new PostgreSQLContainer(); + + @Test + public void whenSelectQueryExecuted_thenResulstsReturned() throws Exception { + ResultSet resultSet = performQuery(postgresContainer, "SELECT 1"); + resultSet.next(); + int result = resultSet.getInt(1); + assertEquals(1, result); + } + + private ResultSet performQuery(PostgreSQLContainer postgres, String query) throws SQLException { + String jdbcUrl = postgres.getJdbcUrl(); + String username = postgres.getUsername(); + String password = postgres.getPassword(); + Connection conn = DriverManager.getConnection(jdbcUrl, username, password); + return conn.createStatement() + .executeQuery(query); + } +} diff --git a/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/WebDriverContainerLiveTest.java b/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/WebDriverContainerLiveTest.java new file mode 100644 index 0000000000..0e52c4e9f7 --- /dev/null +++ b/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/WebDriverContainerLiveTest.java @@ -0,0 +1,30 @@ +package com.baeldung.testconainers; + +import static org.junit.Assert.assertEquals; + +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; +import org.openqa.selenium.By; +import org.openqa.selenium.remote.DesiredCapabilities; +import org.openqa.selenium.remote.RemoteWebDriver; +import org.testcontainers.DockerClientFactory; +import org.testcontainers.containers.BrowserWebDriverContainer; +import org.testcontainers.containers.GenericContainer; + +public class WebDriverContainerLiveTest { + @Rule + public BrowserWebDriverContainer chrome + = new BrowserWebDriverContainer() + .withDesiredCapabilities(DesiredCapabilities.chrome()); + + @Test + public void whenNavigatedToPage_thenHeadingIsInThePage() { + RemoteWebDriver driver = chrome.getWebDriver(); + driver.get("https://saucelabs.com/test/guinea-pig"); + String heading = driver.findElement(By.xpath("/html/body/h1")) + .getText(); + assertEquals("This page is a Selenium sandbox", heading); + } + +} diff --git a/testing-modules/test-containers/src/test/resources/test-compose.yml b/testing-modules/test-containers/src/test/resources/test-compose.yml new file mode 100644 index 0000000000..3810c1c589 --- /dev/null +++ b/testing-modules/test-containers/src/test/resources/test-compose.yml @@ -0,0 +1,3 @@ +simpleWebServer: + image: alpine:3.2 + command: ["/bin/sh", "-c", "while true; do echo 'HTTP/1.1 200 OK\n\nHello World!' | nc -l -p 80; done"] diff --git a/testing-modules/testing/README.md b/testing-modules/testing/README.md index c9c656dde9..849b578a55 100644 --- a/testing-modules/testing/README.md +++ b/testing-modules/testing/README.md @@ -19,3 +19,5 @@ - [Guide to JSpec](http://www.baeldung.com/jspec) - [Custom Assertions with AssertJ](http://www.baeldung.com/assertj-custom-assertion) - [Using Conditions with AssertJ](http://www.baeldung.com/assertj-conditions) +- [Guide to JavaFaker](https://www.baeldung.com/java-faker) +- [Running JUnit Tests Programmatically, from a Java Application](https://www.baeldung.com/junit-tests-run-programmatically-from-java) diff --git a/testing-modules/testing/pom.xml b/testing-modules/testing/pom.xml index 6cf7ee223f..2e783b2116 100644 --- a/testing-modules/testing/pom.xml +++ b/testing-modules/testing/pom.xml @@ -1,5 +1,5 @@ + 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 testing @@ -9,57 +9,51 @@ com.baeldung parent-java - 0.0.1-SNAPSHOT - ../../parent-java + 0.0.1-SNAPSHOT + ../../parent-java com.insightfullogic lambda-behave - 0.4 + ${lambda-behave.version} org.assertj assertj-guava - 3.0.0 + ${assertj-guava.version} - org.assertj assertj-core ${assertj-core.version} test - info.cukes cucumber-junit ${cucumber.version} test - info.cukes cucumber-java ${cucumber.version} test - info.cukes cucumber-java8 ${cucumber.version} test - org.pitest pitest-parent ${pitest.version} pom - com.google.truth truth @@ -86,7 +80,7 @@ org.jukito jukito - 1.5 + ${jukito.version} test @@ -94,7 +88,13 @@ javalite-common ${javalite.version} + + com.github.javafaker + javafaker + 0.15 + + @@ -174,5 +174,9 @@ 1.1.0 0.12 1.4.13 + 0.4 + 3.0.0 + 1.5 + diff --git a/testing-modules/testing/src/main/resources/logback.xml b/testing-modules/testing/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/testing-modules/testing/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/testing-modules/testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java b/testing-modules/testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java deleted file mode 100644 index 313e1d2938..0000000000 --- a/testing-modules/testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java +++ /dev/null @@ -1,62 +0,0 @@ -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/testing-modules/testing/src/test/java/com/baeldung/introductionjukito/CalculatorUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/introductionjukito/CalculatorUnitTest.java new file mode 100644 index 0000000000..193a4b9cd8 --- /dev/null +++ b/testing-modules/testing/src/test/java/com/baeldung/introductionjukito/CalculatorUnitTest.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 CalculatorUnitTest { + + 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/testing-modules/testing/src/test/java/com/baeldung/javafaker/JavaFakerUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/javafaker/JavaFakerUnitTest.java new file mode 100644 index 0000000000..7a3b9771fb --- /dev/null +++ b/testing-modules/testing/src/test/java/com/baeldung/javafaker/JavaFakerUnitTest.java @@ -0,0 +1,121 @@ +package com.baeldung.javafaker; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Locale; +import java.util.Random; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.Before; +import org.junit.Test; + +import com.github.javafaker.Faker; +import com.github.javafaker.service.FakeValuesService; +import com.github.javafaker.service.LocaleDoesNotExistException; +import com.github.javafaker.service.RandomService; + +public class JavaFakerUnitTest { + + private Faker faker; + + @Before + public void setUp() throws Exception { + faker = new Faker(); + } + + @Test + public void givenJavaFaker_whenAddressObjectCalled_checkValidAddressInfoGiven() throws Exception { + + Faker faker = new Faker(); + + String streetName = faker.address() + .streetName(); + String number = faker.address() + .buildingNumber(); + String city = faker.address() + .city(); + String country = faker.address() + .country(); + + System.out.println(String.format("%s\n%s\n%s\n%s", number, streetName, city, country)); + + } + + @Test + public void givenJavaFakersWithSameSeed_whenNameCalled_CheckSameName() throws Exception { + + Faker faker1 = new Faker(new Random(24)); + Faker faker2 = new Faker(new Random(24)); + + assertEquals(faker1.name() + .firstName(), + faker2.name() + .firstName()); + } + + @Test + public void givenJavaFakersWithDifferentLocals_checkZipCodesMatchRegex() throws Exception { + + Faker ukFaker = new Faker(new Locale("en-GB")); + Faker usFaker = new Faker(new Locale("en-US")); + + System.out.println(String.format("American zipcode: %s", usFaker.address() + .zipCode())); + System.out.println(String.format("British postcode: %s", ukFaker.address() + .zipCode())); + + Pattern ukPattern = Pattern.compile("([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\\s?[0-9][A-Za-z]{2})"); + Matcher ukMatcher = ukPattern.matcher(ukFaker.address() + .zipCode()); + + assertTrue(ukMatcher.find()); + + Matcher usMatcher = Pattern.compile("^\\d{5}(?:[-\\s]\\d{4})?$") + .matcher(usFaker.address() + .zipCode()); + + assertTrue(usMatcher.find()); + + } + + @Test + public void givenJavaFakerService_testFakersCreated() throws Exception { + + RandomService randomService = new RandomService(); + + System.out.println(randomService.nextBoolean()); + System.out.println(randomService.nextDouble()); + + Faker faker = new Faker(new Random(randomService.nextLong())); + + System.out.println(faker.address() + .city()); + + } + + @Test + public void testFakeValuesService() throws Exception { + + FakeValuesService fakeValuesService = new FakeValuesService(new Locale("en-GB"), new RandomService()); + + String email = fakeValuesService.bothify("????##@gmail.com"); + Matcher emailMatcher = Pattern.compile("\\w{4}\\d{2}@gmail.com") + .matcher(email); + assertTrue(emailMatcher.find()); + + String alphaNumericString = fakeValuesService.regexify("[a-z1-9]{10}"); + Matcher alphaNumericMatcher = Pattern.compile("[a-z1-9]{10}") + .matcher(alphaNumericString); + assertTrue(alphaNumericMatcher.find()); + + } + + @Test(expected = LocaleDoesNotExistException.class) + public void givenWrongLocale_whenFakerIsInitialised_testLocaleDoesNotExistExceptionIsThrown() throws Exception { + + Faker wrongLocaleFaker = new Faker(new Locale("en-seaWorld")); + + } +} \ No newline at end of file diff --git a/testing-modules/testing/src/test/java/com/baeldung/junit/AdditionTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/AdditionTest.java deleted file mode 100644 index 0d492f8058..0000000000 --- a/testing-modules/testing/src/test/java/com/baeldung/junit/AdditionTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.junit; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class AdditionTest { - Calculator calculator = new Calculator(); - - @Test - public void testAddition() { - assertEquals("addition", 8, calculator.add(5, 3)); - } -} diff --git a/testing-modules/testing/src/test/java/com/baeldung/junit/AdditionUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/AdditionUnitTest.java new file mode 100644 index 0000000000..ae6fa355fa --- /dev/null +++ b/testing-modules/testing/src/test/java/com/baeldung/junit/AdditionUnitTest.java @@ -0,0 +1,14 @@ +package com.baeldung.junit; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class AdditionUnitTest { + Calculator calculator = new Calculator(); + + @Test + public void testAddition() { + assertEquals("addition", 8, calculator.add(5, 3)); + } +} diff --git a/testing-modules/testing/src/test/java/com/baeldung/junit/CalculatorTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/CalculatorTest.java deleted file mode 100644 index d1b35d1442..0000000000 --- a/testing-modules/testing/src/test/java/com/baeldung/junit/CalculatorTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.junit; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import static org.junit.Assert.assertEquals; - -@RunWith(JUnit4.class) -public class CalculatorTest { - Calculator calculator = new Calculator(); - - @Test - public void testAddition() { - assertEquals("addition", 8, calculator.add(5, 3)); - } -} diff --git a/testing-modules/testing/src/test/java/com/baeldung/junit/CalculatorUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/CalculatorUnitTest.java new file mode 100644 index 0000000000..d5ca847106 --- /dev/null +++ b/testing-modules/testing/src/test/java/com/baeldung/junit/CalculatorUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.junit; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import static org.junit.Assert.assertEquals; + +@RunWith(JUnit4.class) +public class CalculatorUnitTest { + Calculator calculator = new Calculator(); + + @Test + public void testAddition() { + assertEquals("addition", 8, calculator.add(5, 3)); + } +} diff --git a/testing-modules/testing/src/test/java/com/baeldung/junit/SubstractionTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/SubstractionTest.java deleted file mode 100644 index 9650d83afe..0000000000 --- a/testing-modules/testing/src/test/java/com/baeldung/junit/SubstractionTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.junit; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class SubstractionTest { - Calculator calculator = new Calculator(); - - @Test - public void substraction() { - assertEquals("substraction", 2, calculator.sub(5, 3)); - } -} diff --git a/testing-modules/testing/src/test/java/com/baeldung/junit/SubstractionUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/SubstractionUnitTest.java new file mode 100644 index 0000000000..fd98395ebc --- /dev/null +++ b/testing-modules/testing/src/test/java/com/baeldung/junit/SubstractionUnitTest.java @@ -0,0 +1,14 @@ +package com.baeldung.junit; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class SubstractionUnitTest { + Calculator calculator = new Calculator(); + + @Test + public void substraction() { + assertEquals("substraction", 2, calculator.sub(5, 3)); + } +} diff --git a/testing-modules/testing/src/test/java/com/baeldung/junit/SuiteTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/SuiteTest.java deleted file mode 100644 index 428319e72e..0000000000 --- a/testing-modules/testing/src/test/java/com/baeldung/junit/SuiteTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.junit; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -@RunWith(Suite.class) -@SuiteClasses({ - AdditionTest.class, - SubstractionTest.class}) -public class SuiteTest { -} diff --git a/testing-modules/testing/src/test/java/com/baeldung/junit/SuiteUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/SuiteUnitTest.java new file mode 100644 index 0000000000..76d19f84b2 --- /dev/null +++ b/testing-modules/testing/src/test/java/com/baeldung/junit/SuiteUnitTest.java @@ -0,0 +1,12 @@ +package com.baeldung.junit; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + AdditionUnitTest.class, + SubstractionUnitTest.class}) +public class SuiteUnitTest { +} diff --git a/testing-modules/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java b/testing-modules/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java deleted file mode 100644 index f1659437ec..0000000000 --- a/testing-modules/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.junitparams; - -import junitparams.FileParameters; -import junitparams.JUnitParamsRunner; -import junitparams.Parameters; -import org.junit.Test; -import org.junit.runner.RunWith; - -import static org.junit.Assert.assertEquals; - -@RunWith(JUnitParamsRunner.class) -public class SafeAdditionUtilTest { - - private SafeAdditionUtil serviceUnderTest = new SafeAdditionUtil(); - - @Test - @Parameters({"1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15"}) - public void whenWithAnnotationProvidedParams_thenSafeAdd(int a, int b, int expectedValue) { - assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); - } - - @Test - @Parameters(method = "parametersToTestAdd") - public void whenWithNamedMethod_thendSafeAdd(int a, int b, int expectedValue) { - assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); - } - - private Object[] parametersToTestAdd() { - return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}}; - } - - @Test - @Parameters - public void whenWithnoParam_thenLoadByNameSafeAdd(int a, int b, int expectedValue) { - assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); - } - - private Object[] parametersForWhenWithnoParam_thenLoadByNameSafeAdd() { - return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}}; - } - - @Test - @Parameters(source = TestDataProvider.class) - public void whenWithNamedClass_thenSafeAdd(int a, int b, int expectedValue) { - assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); - } - - @Test - @FileParameters("src/test/resources/JunitParamsTestParameters.csv") - public void whenWithCsvFile_thenSafeAdd(int a, int b, int expectedValue) { - assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); - } - -} diff --git a/testing-modules/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilUnitTest.java new file mode 100644 index 0000000000..6c98454da0 --- /dev/null +++ b/testing-modules/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.junitparams; + +import junitparams.FileParameters; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.assertEquals; + +@RunWith(JUnitParamsRunner.class) +public class SafeAdditionUtilUnitTest { + + private SafeAdditionUtil serviceUnderTest = new SafeAdditionUtil(); + + @Test + @Parameters({"1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15"}) + public void whenWithAnnotationProvidedParams_thenSafeAdd(int a, int b, int expectedValue) { + assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); + } + + @Test + @Parameters(method = "parametersToTestAdd") + public void whenWithNamedMethod_thendSafeAdd(int a, int b, int expectedValue) { + assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); + } + + private Object[] parametersToTestAdd() { + return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}}; + } + + @Test + @Parameters + public void whenWithnoParam_thenLoadByNameSafeAdd(int a, int b, int expectedValue) { + assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); + } + + private Object[] parametersForWhenWithnoParam_thenLoadByNameSafeAdd() { + return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}}; + } + + @Test + @Parameters(source = TestDataProvider.class) + public void whenWithNamedClass_thenSafeAdd(int a, int b, int expectedValue) { + assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); + } + + @Test + @FileParameters("src/test/resources/JunitParamsTestParameters.csv") + public void whenWithCsvFile_thenSafeAdd(int a, int b, int expectedValue) { + assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); + } + +} diff --git a/testing-modules/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java b/testing-modules/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java deleted file mode 100644 index d179c6eb0e..0000000000 --- a/testing-modules/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.lambdabehave; - -import com.insightfullogic.lambdabehave.JunitSuiteRunner; -import com.insightfullogic.lambdabehave.Suite; -import com.insightfullogic.lambdabehave.generators.Generator; -import com.insightfullogic.lambdabehave.generators.SourceGenerator; -import org.junit.runner.RunWith; - -@RunWith(JunitSuiteRunner.class) -public class CalculatorTest { - - private Calculator calculator; - - { - Suite.describe("Lambda behave example tests", it -> { - - it.isSetupWith(() -> { - calculator = new Calculator(1, 2); - }); - it.should("Add the given numbers", expect -> { - expect.that(calculator.add()).is(3); - }); - it.should("Throw an exception if divide by 0", expect -> { - expect.exception(ArithmeticException.class, () -> { - calculator.divide(1, 0); - }); - }); - it.uses(2, 3, 5) - .and(23, 10, 33) - .toShow("%d + %d = %d", (expect, a, b, c) -> { - expect.that(calculator.add(a, b)).is(c); - }); - it.requires(2) - .example(Generator.asciiStrings()) - .toShow("Reversing a String twice returns the original String", (expect, str) -> { - String same = new StringBuilder(str).reverse() - .reverse() - .toString(); - expect.that(same) - .isEqualTo(str); - }); - it.requires(2) - .withSource(SourceGenerator.deterministicNumbers(5626689007407L)) - .example(Generator.asciiStrings()) - .toShow("Reversing a String twice returns the original String", (expect, str) -> { - String same = new StringBuilder(str).reverse() - .reverse() - .toString(); - expect.that(same) - .isEqualTo(str); - }); - }); - } -} diff --git a/testing-modules/testing/src/test/java/com/baeldung/lambdabehave/CalculatorUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/lambdabehave/CalculatorUnitTest.java new file mode 100644 index 0000000000..5b6cd73332 --- /dev/null +++ b/testing-modules/testing/src/test/java/com/baeldung/lambdabehave/CalculatorUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.lambdabehave; + +import com.insightfullogic.lambdabehave.JunitSuiteRunner; +import com.insightfullogic.lambdabehave.Suite; +import com.insightfullogic.lambdabehave.generators.Generator; +import com.insightfullogic.lambdabehave.generators.SourceGenerator; +import org.junit.runner.RunWith; + +@RunWith(JunitSuiteRunner.class) +public class CalculatorUnitTest { + + private Calculator calculator; + + { + Suite.describe("Lambda behave example tests", it -> { + + it.isSetupWith(() -> { + calculator = new Calculator(1, 2); + }); + it.should("Add the given numbers", expect -> { + expect.that(calculator.add()).is(3); + }); + it.should("Throw an exception if divide by 0", expect -> { + expect.exception(ArithmeticException.class, () -> { + calculator.divide(1, 0); + }); + }); + it.uses(2, 3, 5) + .and(23, 10, 33) + .toShow("%d + %d = %d", (expect, a, b, c) -> { + expect.that(calculator.add(a, b)).is(c); + }); + it.requires(2) + .example(Generator.asciiStrings()) + .toShow("Reversing a String twice returns the original String", (expect, str) -> { + String same = new StringBuilder(str).reverse() + .reverse() + .toString(); + expect.that(same) + .isEqualTo(str); + }); + it.requires(2) + .withSource(SourceGenerator.deterministicNumbers(5626689007407L)) + .example(Generator.asciiStrings()) + .toShow("Reversing a String twice returns the original String", (expect, str) -> { + String same = new StringBuilder(str).reverse() + .reverse() + .toString(); + expect.that(same) + .isEqualTo(str); + }); + }); + } +} diff --git a/testing-modules/testing/src/test/java/com/baeldung/runfromjava/FirstUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/runfromjava/FirstUnitTest.java new file mode 100644 index 0000000000..0e08c43021 --- /dev/null +++ b/testing-modules/testing/src/test/java/com/baeldung/runfromjava/FirstUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.runfromjava; + +import org.junit.Test; + +import static org.junit.Assert.assertTrue; + +public class FirstUnitTest { + + @Test + public void whenThis_thenThat() { + assertTrue(true); + } + + @Test + public void whenSomething_thenSomething() { + assertTrue(true); + } + + @Test + public void whenSomethingElse_thenSomethingElse() { + assertTrue(true); + } + +} diff --git a/testing-modules/testing/src/test/java/com/baeldung/runfromjava/MyTestSuite.java b/testing-modules/testing/src/test/java/com/baeldung/runfromjava/MyTestSuite.java new file mode 100644 index 0000000000..2413fb1ddf --- /dev/null +++ b/testing-modules/testing/src/test/java/com/baeldung/runfromjava/MyTestSuite.java @@ -0,0 +1,10 @@ +package com.baeldung.runfromjava; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +@RunWith(Suite.class) +@Suite.SuiteClasses({ FirstUnitTest.class, SecondUnitTest.class }) +public class MyTestSuite { + +} diff --git a/testing-modules/testing/src/test/java/com/baeldung/runfromjava/RunJUnit4TestsFromJava.java b/testing-modules/testing/src/test/java/com/baeldung/runfromjava/RunJUnit4TestsFromJava.java new file mode 100644 index 0000000000..b44b66440a --- /dev/null +++ b/testing-modules/testing/src/test/java/com/baeldung/runfromjava/RunJUnit4TestsFromJava.java @@ -0,0 +1,93 @@ +package com.baeldung.runfromjava; + +import junit.extensions.ActiveTestSuite; +import junit.extensions.RepeatedTest; +import junit.framework.JUnit4TestAdapter; +import junit.framework.Test; +import junit.framework.TestSuite; +import org.junit.internal.TextListener; +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; + +public class RunJUnit4TestsFromJava { + + public static void runOne() { + JUnitCore junit = new JUnitCore(); + junit.addListener(new TextListener(System.out)); + junit.run(FirstUnitTest.class); + } + + public static void runAllClasses() { + JUnitCore junit = new JUnitCore(); + junit.addListener(new TextListener(System.out)); + + Result result = junit.run(FirstUnitTest.class, SecondUnitTest.class); + + for (Failure failure : result.getFailures()) { + System.out.println(failure.toString()); + } + + resultReport(result); + } + + public static void runSuiteOfClasses() { + JUnitCore junit = new JUnitCore(); + junit.addListener(new TextListener(System.out)); + Result result = junit.run(MyTestSuite.class); + + for (Failure failure : result.getFailures()) { + System.out.println(failure.toString()); + } + + resultReport(result); + } + + public static void runRepeated() { + Test test = new JUnit4TestAdapter(SecondUnitTest.class); + RepeatedTest repeatedTest = new RepeatedTest(test, 5); + + JUnitCore junit = new JUnitCore(); + junit.addListener(new TextListener(System.out)); + + junit.run(repeatedTest); + } + + public static void runRepeatedSuite() { + TestSuite mySuite = new ActiveTestSuite(); + + JUnitCore junit = new JUnitCore(); + junit.addListener(new TextListener(System.out)); + + mySuite.addTest(new RepeatedTest(new JUnit4TestAdapter(FirstUnitTest.class), 5)); + mySuite.addTest(new RepeatedTest(new JUnit4TestAdapter(SecondUnitTest.class), 3)); + + junit.run(mySuite); + } + + public static void resultReport(Result result) { + System.out.println("Finished. Result: Failures: " + + result.getFailureCount() + ". Ignored: " + + result.getIgnoreCount() + ". Tests run: " + + result.getRunCount() + ". Time: " + + result.getRunTime() + "ms."); + } + + public static void main(String[] args) { + System.out.println("\nRunning one test class:"); + runOne(); + + System.out.println("\nRunning all test classes:"); + runAllClasses(); + + System.out.println("\nRunning a suite of test classes:"); + runSuiteOfClasses(); + + System.out.println("\nRunning repeated tests:"); + runRepeated(); + + System.out.println("\nRunning repeated suite tests:"); + runRepeatedSuite(); + } + +} \ No newline at end of file diff --git a/testing-modules/testing/src/test/java/com/baeldung/runfromjava/SecondUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/runfromjava/SecondUnitTest.java new file mode 100644 index 0000000000..aa5883562e --- /dev/null +++ b/testing-modules/testing/src/test/java/com/baeldung/runfromjava/SecondUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.runfromjava; + +import org.junit.Test; + +import static org.junit.Assert.assertTrue; + +public class SecondUnitTest { + + @Test + public void whenSomething_thenSomething() { + assertTrue(true); + } + + @Test + public void whensomethingElse_thenSomethingElse() { + assertTrue(true); + } +} diff --git a/testing-modules/testng/pom.xml b/testing-modules/testng/pom.xml index e50f3bb563..a9f680aafb 100644 --- a/testing-modules/testng/pom.xml +++ b/testing-modules/testng/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 testng 0.1.0-SNAPSHOT @@ -15,16 +15,13 @@ - - org.testng testng ${testng.version} test - @@ -41,26 +38,6 @@ true - - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - prepare-package - - copy-dependencies - - - ${project.build.directory}/libs - - - - - - @@ -68,5 +45,4 @@ 6.10 - \ No newline at end of file diff --git a/twilio/README.md b/twilio/README.md new file mode 100644 index 0000000000..9d230610c7 --- /dev/null +++ b/twilio/README.md @@ -0,0 +1,5 @@ + + +### Relevant Articles: + +- [Sending SMS in Java with Twilio](http://www.baeldung.com/java-sms-twilio) diff --git a/twilio/pom.xml b/twilio/pom.xml index 89b40ccdac..8683192b5c 100644 --- a/twilio/pom.xml +++ b/twilio/pom.xml @@ -1,18 +1,12 @@ - + 4.0.0 com.baeldung twilio 1.0-SNAPSHOT - - 1.8 - 1.8 - - com.twilio.sdk @@ -21,4 +15,9 @@ + + 1.8 + 1.8 + + diff --git a/twilio/src/main/resources/logback.xml b/twilio/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/twilio/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/undertow/dependency-reduced-pom.xml b/undertow/dependency-reduced-pom.xml deleted file mode 100644 index a4a17f94d6..0000000000 --- a/undertow/dependency-reduced-pom.xml +++ /dev/null @@ -1,90 +0,0 @@ - - - - parent-modules - com.baeldung - 1.0.0-SNAPSHOT - - 4.0.0 - com.baeldung.undertow - undertow - undertow - 1.0-SNAPSHOT - http://maven.apache.org - - ${project.artifactId} - - - maven-shade-plugin - - - package - - shade - - - - - - maven-jar-plugin - - - - com.baeldung.undertow.SimpleServer - - - - - - - - - junit - junit - 4.12 - test - - - org.hamcrest - hamcrest-core - 1.3 - test - - - org.hamcrest - hamcrest-library - 1.3 - test - - - org.hamcrest - hamcrest-all - 1.3 - test - - - org.mockito - mockito-core - 2.8.9 - test - - - byte-buddy - net.bytebuddy - - - byte-buddy-agent - net.bytebuddy - - - objenesis - org.objenesis - - - - - - 1.8 - 1.8 - - diff --git a/undertow/pom.xml b/undertow/pom.xml index 35ea2b3348..d000956aee 100644 --- a/undertow/pom.xml +++ b/undertow/pom.xml @@ -1,27 +1,25 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 + com.baeldung.undertow undertow jar 1.0-SNAPSHOT undertow http://maven.apache.org + com.baeldung parent-modules 1.0.0-SNAPSHOT - - 1.8 - 1.8 - io.undertow undertow-servlet - 1.4.18.Final + ${undertow-servlet.version} @@ -31,6 +29,7 @@ org.apache.maven.plugins maven-shade-plugin + ${maven-shade-plugin.version} package @@ -43,6 +42,7 @@ org.apache.maven.plugins maven-jar-plugin + ${maven-jar-plugin.version} @@ -54,4 +54,10 @@ + + 1.4.18.Final + 2.4.3 + 3.0.2 + + \ No newline at end of file diff --git a/undertow/src/main/resources/logback.xml b/undertow/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/undertow/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/vaadin-spring/README.md b/vaadin-spring/README.md new file mode 100644 index 0000000000..347c92d7b5 --- /dev/null +++ b/vaadin-spring/README.md @@ -0,0 +1,3 @@ +### Relevant articles + +- [Sample Application with Spring Boot and Vaadin](https://www.baeldung.com/spring-boot-vaadin) diff --git a/vaadin/README.md b/vaadin/README.md index 0dfeea8996..43d2cc8961 100644 --- a/vaadin/README.md +++ b/vaadin/README.md @@ -1,3 +1,4 @@ ## Relevant articles: - [Introduction to Vaadin](http://www.baeldung.com/vaadin) +- [Sample Application with Spring Boot and Vaadin](https://www.baeldung.com/spring-boot-vaadin) diff --git a/vaadin/pom.xml b/vaadin/pom.xml index 6fdf033c22..c34ffa3636 100644 --- a/vaadin/pom.xml +++ b/vaadin/pom.xml @@ -1,40 +1,21 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.test - vaadin-app + vaadin war 1.0-SNAPSHOT - vaadin-app + Vaadin - - 3 - + parent-boot-2 com.baeldung - parent-modules - 1.0.0-SNAPSHOT + 0.0.1-SNAPSHOT + ../parent-boot-2 - - 7.7.10 - 8.0.6 - 9.3.9.v20160517 - UTF-8 - 1.8 - 1.8 - local - mytheme - - - - - vaadin-addons - http://maven.vaadin.com/vaadin-addons - - - + @@ -46,12 +27,11 @@ - + javax.servlet javax.servlet-api - 3.0.1 provided @@ -70,6 +50,25 @@ com.vaadin vaadin-themes + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.vaadin + vaadin-spring-boot-starter + ${vaadin-spring-boot-starter.version} + + + com.h2database + h2 + + + org.springframework.boot + spring-boot-starter-test + test + @@ -77,7 +76,7 @@ org.apache.maven.plugins maven-war-plugin - 3.0.0 + ${maven-war-plugin.version} false @@ -103,7 +102,7 @@ org.apache.maven.plugins maven-clean-plugin - 3.0.0 + ${maven-clean-plugin.version} @@ -117,9 +116,7 @@ - - + org.eclipse.jetty jetty-maven-plugin @@ -128,9 +125,20 @@ 2 + + org.springframework.boot + spring-boot-maven-plugin + + + + vaadin-addons + http://maven.vaadin.com/vaadin-addons + + + @@ -174,4 +182,19 @@ + + 3.0.1 + 7.7.10 + 8.0.6 + 10.0.1 + 9.3.9.v20160517 + UTF-8 + 1.8 + 1.8 + local + mytheme + 3.0.0 + 3.0.0 + + diff --git a/vaadin/src/main/java/com/baeldung/Application.java b/vaadin/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..1d3084723a --- /dev/null +++ b/vaadin/src/main/java/com/baeldung/Application.java @@ -0,0 +1,29 @@ +package com.baeldung; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +public class Application { + + private static final Logger log = LoggerFactory.getLogger(Application.class); + + public static void main(String[] args) { + SpringApplication.run(Application.class); + } + + @Bean + public CommandLineRunner loadData(EmployeeRepository repository) { + return (args) -> { + repository.save(new Employee("Bill", "Gates")); + repository.save(new Employee("Mark", "Zuckerberg")); + repository.save(new Employee("Sundar", "Pichai")); + repository.save(new Employee("Jeff", "Bezos")); + }; + } +} diff --git a/vaadin/src/main/java/com/baeldung/Employee.java b/vaadin/src/main/java/com/baeldung/Employee.java new file mode 100644 index 0000000000..726f0838b6 --- /dev/null +++ b/vaadin/src/main/java/com/baeldung/Employee.java @@ -0,0 +1,51 @@ +package com.baeldung; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Employee { + + @Id + @GeneratedValue + private Long id; + + private String firstName; + + private String lastName; + + protected Employee() { + } + + public Employee(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public Long getId() { + return id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + @Override + public String toString() { + return String.format("Employee[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); + } + +} diff --git a/vaadin/src/main/java/com/baeldung/EmployeeEditor.java b/vaadin/src/main/java/com/baeldung/EmployeeEditor.java new file mode 100644 index 0000000000..ee312786d1 --- /dev/null +++ b/vaadin/src/main/java/com/baeldung/EmployeeEditor.java @@ -0,0 +1,90 @@ +package com.baeldung; + +import com.vaadin.flow.component.Key; +import com.vaadin.flow.component.KeyNotifier; +import com.vaadin.flow.component.button.Button; +import com.vaadin.flow.component.icon.VaadinIcon; +import com.vaadin.flow.component.orderedlayout.HorizontalLayout; +import com.vaadin.flow.component.orderedlayout.VerticalLayout; +import com.vaadin.flow.component.textfield.TextField; +import com.vaadin.flow.data.binder.Binder; +import com.vaadin.flow.spring.annotation.SpringComponent; +import com.vaadin.flow.spring.annotation.UIScope; +import org.springframework.beans.factory.annotation.Autowired; + +@SpringComponent +@UIScope +public class EmployeeEditor extends VerticalLayout implements KeyNotifier { + + private final EmployeeRepository repository; + + private Employee employee; + + TextField firstName = new TextField("First name"); + TextField lastName = new TextField("Last name"); + + Button save = new Button("Save", VaadinIcon.CHECK.create()); + Button cancel = new Button("Cancel"); + Button delete = new Button("Delete", VaadinIcon.TRASH.create()); + HorizontalLayout actions = new HorizontalLayout(save, cancel, delete); + + Binder binder = new Binder<>(Employee.class); + private ChangeHandler changeHandler; + + @Autowired + public EmployeeEditor(EmployeeRepository repository) { + this.repository = repository; + + add(firstName, lastName, actions); + + binder.bindInstanceFields(this); + + setSpacing(true); + + save.getElement().getThemeList().add("primary"); + delete.getElement().getThemeList().add("error"); + + addKeyPressListener(Key.ENTER, e -> save()); + + save.addClickListener(e -> save()); + delete.addClickListener(e -> delete()); + cancel.addClickListener(e -> editEmployee(employee)); + setVisible(false); + } + + void delete() { + repository.delete(employee); + changeHandler.onChange(); + } + + void save() { + repository.save(employee); + changeHandler.onChange(); + } + + public interface ChangeHandler { + void onChange(); + } + + public final void editEmployee(Employee c) { + if (c == null) { + setVisible(false); + return; + } + final boolean persisted = c.getId() != null; + if (persisted) { + employee = repository.findById(c.getId()).get(); + } else { + employee = c; + } + + cancel.setVisible(persisted); + binder.setBean(employee); + setVisible(true); + firstName.focus(); + } + + public void setChangeHandler(ChangeHandler h) { + changeHandler = h; + } +} diff --git a/vaadin/src/main/java/com/baeldung/EmployeeRepository.java b/vaadin/src/main/java/com/baeldung/EmployeeRepository.java new file mode 100644 index 0000000000..044160da78 --- /dev/null +++ b/vaadin/src/main/java/com/baeldung/EmployeeRepository.java @@ -0,0 +1,10 @@ +package com.baeldung; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface EmployeeRepository extends JpaRepository { + + List findByLastNameStartsWithIgnoreCase(String lastName); +} diff --git a/vaadin/src/main/java/com/baeldung/MainView.java b/vaadin/src/main/java/com/baeldung/MainView.java new file mode 100644 index 0000000000..6d4c0aaa88 --- /dev/null +++ b/vaadin/src/main/java/com/baeldung/MainView.java @@ -0,0 +1,67 @@ +package com.baeldung; + +import org.springframework.util.StringUtils; + +import com.vaadin.flow.component.button.Button; +import com.vaadin.flow.component.grid.Grid; +import com.vaadin.flow.component.icon.VaadinIcon; +import com.vaadin.flow.component.orderedlayout.HorizontalLayout; +import com.vaadin.flow.component.orderedlayout.VerticalLayout; +import com.vaadin.flow.component.textfield.TextField; +import com.vaadin.flow.data.value.ValueChangeMode; +import com.vaadin.flow.router.Route; + +@Route +public class MainView extends VerticalLayout { + + private final EmployeeRepository employeeRepository; + + private final EmployeeEditor editor; + + final Grid grid; + + final TextField filter; + + private final Button addNewBtn; + + public MainView(EmployeeRepository repo, EmployeeEditor editor) { + this.employeeRepository = repo; + this.editor = editor; + this.grid = new Grid<>(Employee.class); + this.filter = new TextField(); + this.addNewBtn = new Button("New employee", VaadinIcon.PLUS.create()); + + HorizontalLayout actions = new HorizontalLayout(filter, addNewBtn); + add(actions, grid, editor); + + grid.setHeight("200px"); + grid.setColumns("id", "firstName", "lastName"); + grid.getColumnByKey("id").setWidth("50px").setFlexGrow(0); + + filter.setPlaceholder("Filter by last name"); + + filter.setValueChangeMode(ValueChangeMode.EAGER); + filter.addValueChangeListener(e -> listEmployees(e.getValue())); + + grid.asSingleSelect().addValueChangeListener(e -> { + editor.editEmployee(e.getValue()); + }); + + addNewBtn.addClickListener(e -> editor.editEmployee(new Employee("", ""))); + + editor.setChangeHandler(() -> { + editor.setVisible(false); + listEmployees(filter.getValue()); + }); + + listEmployees(null); + } + + void listEmployees(String filterText) { + if (StringUtils.isEmpty(filterText)) { + grid.setItems(employeeRepository.findAll()); + } else { + grid.setItems(employeeRepository.findByLastNameStartsWithIgnoreCase(filterText)); + } + } +} diff --git a/vaadin/src/main/resources/logback.xml b/vaadin/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/vaadin/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/vavr/README.md b/vavr/README.md index c8570db04c..b7ba72229b 100644 --- a/vavr/README.md +++ b/vavr/README.md @@ -11,3 +11,4 @@ - [Introduction to Future in Vavr](http://www.baeldung.com/vavr-future) - [Introduction to VRaptor in Java](http://www.baeldung.com/vraptor) - [Introduction to Vavr’s Either](http://www.baeldung.com/vavr-either) +- [Interoperability Between Java and Vavr](http://www.baeldung.com/java-vavr) diff --git a/vavr/pom.xml b/vavr/pom.xml index 3bf91adcd3..ae495e9830 100644 --- a/vavr/pom.xml +++ b/vavr/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 com.baeldung vavr @@ -18,23 +19,19 @@ vavr-test ${vavr.version} - org.springframework.boot spring-boot-starter-data-jpa - com.h2database h2 - org.springframework.boot spring-boot-starter-test test - org.awaitility awaitility @@ -46,7 +43,6 @@ 1.8 0.9.1 - 4.12 3.0.0 diff --git a/vavr/src/main/resources/logback.xml b/vavr/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/vavr/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/vavr/src/test/java/com/baeldung/vavr/future/FutureTest.java b/vavr/src/test/java/com/baeldung/vavr/future/FutureTest.java deleted file mode 100644 index d5345cad55..0000000000 --- a/vavr/src/test/java/com/baeldung/vavr/future/FutureTest.java +++ /dev/null @@ -1,189 +0,0 @@ -package com.baeldung.vavr.future; - -import io.vavr.Tuple; -import io.vavr.concurrent.Future; -import io.vavr.control.Option; -import io.vavr.control.Try; -import org.junit.Test; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; - -import static java.util.concurrent.Executors.newSingleThreadExecutor; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class FutureTest { - - private static final String error = "Failed to get underlying value."; - private static final String HELLO = "Welcome to Baeldung!"; - - @Test - public void whenChangeExecutorService_thenCorrect() { - String result = Future.of(newSingleThreadExecutor(), () -> HELLO) - .getOrElse(error); - - assertThat(result) - .isEqualTo(HELLO); - } - - @Test - public void whenAppendData_thenCorrect1() { - String result = Future.of(() -> HELLO) - .getOrElse(error); - - assertThat(result) - .isEqualTo(HELLO); - } - - @Test - public void whenAppendData_thenCorrect2() { - Future resultFuture = Future.of(() -> HELLO) - .await(); - - Option> futureOption = resultFuture.getValue(); - String result = futureOption.get().getOrElse(error); - - assertThat(result) - .isEqualTo(HELLO); - } - - @Test - public void whenAppendData_thenSuccess() { - String result = Future.of(() -> HELLO) - .onSuccess(finalResult -> System.out.println("Successfully Completed - Result: " + finalResult)) - .onFailure(finalResult -> System.out.println("Failed - Result: " + finalResult)) - .getOrElse(error); - - assertThat(result) - .isEqualTo(HELLO); - } - - @Test - public void whenTransform_thenCorrect() { - Future future = Future.of(() -> 5) - .transformValue(result -> Try.of(() -> HELLO + result.get())); - - assertThat(future.get()).isEqualTo(HELLO + 5); - } - - @Test - public void whenChainingCallbacks_thenCorrect() { - Future.of(() -> HELLO) - .andThen(r -> System.out.println("Completed - 1: " + r)) - .andThen(r -> System.out.println("Completed - 2: " + r)); - } - - @Test - public void whenCallAwait_thenCorrect() { - Future resultFuture = Future.of(() -> HELLO) - .await(); - String result = resultFuture.getValue().get().getOrElse(error); - - assertThat(result) - .isEqualTo(HELLO); - } - - @Test - public void whenDivideByZero_thenGetThrowable1() { - Future resultFuture = Future.of(() -> 10 / 0); - - assertThatThrownBy(resultFuture::get) - .isInstanceOf(ArithmeticException.class); - } - - @Test - public void whenDivideByZero_thenGetThrowable2() { - Future resultFuture = Future.of(() -> 10 / 0) - .await(); - - assertThat(resultFuture.getCause().get().getMessage()) - .isEqualTo("/ by zero"); - } - - @Test - public void whenDivideByZero_thenCorrect() { - Future resultFuture = Future.of(() -> 10 / 0) - .await(); - - assertThat(resultFuture.isCompleted()).isTrue(); - assertThat(resultFuture.isSuccess()).isFalse(); - assertThat(resultFuture.isFailure()).isTrue(); - } - - @Test - public void whenAppendData_thenFutureNotEmpty() { - Future resultFuture = Future.of(() -> HELLO) - .await(); - - assertThat(resultFuture.isEmpty()) - .isFalse(); - } - - @Test - public void whenCallZip_thenCorrect() { - Future f1 = Future.of(() -> "hello1"); - Future f2 = Future.of(() -> "hello2"); - - assertThat(f1.zip(f2).get()) - .isEqualTo(Tuple.of("hello1", "hello2")); - } - - @Test - public void whenConvertToCompletableFuture_thenCorrect() throws InterruptedException, ExecutionException { - CompletableFuture convertedFuture = Future.of(() -> HELLO) - .toCompletableFuture(); - - assertThat(convertedFuture.get()) - .isEqualTo(HELLO); - } - - @Test - public void whenCallMap_thenCorrect() { - Future futureResult = Future.of(() -> "from Baeldung") - .map(a -> "Hello " + a) - .await(); - - assertThat(futureResult.get()) - .isEqualTo("Hello from Baeldung"); - } - - @Test - public void whenCallFlatMap_thenCorrect() { - Future futureMap = Future.of(() -> 1) - .flatMap((i) -> Future.of(() -> "Hello: " + i)); - - assertThat(futureMap.get()).isEqualTo("Hello: 1"); - } - - @Test - public void whenFutureFails_thenGetErrorMessage() { - Future future = Future.of(() -> "Hello".substring(-1)) - .recover(x -> "fallback value"); - - assertThat(future.get()) - .isEqualTo("fallback value"); - } - - @Test - public void whenFutureFails_thenGetAnotherFuture() { - Future future = Future.of(() -> "Hello".substring(-1)) - .recoverWith(x -> Future.of(() -> "fallback value")); - - assertThat(future.get()) - .isEqualTo("fallback value"); - } - - @Test - public void whenBothFuturesFail_thenGetErrorMessage() { - Future f1 = Future.of(() -> "Hello".substring(-1)); - Future f2 = Future.of(() -> "Hello".substring(-2)); - - Future errorMessageFuture = f1.fallbackTo(f2); - Future errorMessage = errorMessageFuture.failed(); - - assertThat( - errorMessage.get().getMessage()) - .isEqualTo("String index out of range: -1"); - } -} diff --git a/vavr/src/test/java/com/baeldung/vavr/future/FutureUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/future/FutureUnitTest.java new file mode 100644 index 0000000000..c398cc4095 --- /dev/null +++ b/vavr/src/test/java/com/baeldung/vavr/future/FutureUnitTest.java @@ -0,0 +1,189 @@ +package com.baeldung.vavr.future; + +import io.vavr.Tuple; +import io.vavr.concurrent.Future; +import io.vavr.control.Option; +import io.vavr.control.Try; +import org.junit.Test; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +import static java.util.concurrent.Executors.newSingleThreadExecutor; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +public class FutureUnitTest { + + private static final String error = "Failed to get underlying value."; + private static final String HELLO = "Welcome to Baeldung!"; + + @Test + public void whenChangeExecutorService_thenCorrect() { + String result = Future.of(newSingleThreadExecutor(), () -> HELLO) + .getOrElse(error); + + assertThat(result) + .isEqualTo(HELLO); + } + + @Test + public void whenAppendData_thenCorrect1() { + String result = Future.of(() -> HELLO) + .getOrElse(error); + + assertThat(result) + .isEqualTo(HELLO); + } + + @Test + public void whenAppendData_thenCorrect2() { + Future resultFuture = Future.of(() -> HELLO) + .await(); + + Option> futureOption = resultFuture.getValue(); + String result = futureOption.get().getOrElse(error); + + assertThat(result) + .isEqualTo(HELLO); + } + + @Test + public void whenAppendData_thenSuccess() { + String result = Future.of(() -> HELLO) + .onSuccess(finalResult -> System.out.println("Successfully Completed - Result: " + finalResult)) + .onFailure(finalResult -> System.out.println("Failed - Result: " + finalResult)) + .getOrElse(error); + + assertThat(result) + .isEqualTo(HELLO); + } + + @Test + public void whenTransform_thenCorrect() { + Future future = Future.of(() -> 5) + .transformValue(result -> Try.of(() -> HELLO + result.get())); + + assertThat(future.get()).isEqualTo(HELLO + 5); + } + + @Test + public void whenChainingCallbacks_thenCorrect() { + Future.of(() -> HELLO) + .andThen(r -> System.out.println("Completed - 1: " + r)) + .andThen(r -> System.out.println("Completed - 2: " + r)); + } + + @Test + public void whenCallAwait_thenCorrect() { + Future resultFuture = Future.of(() -> HELLO) + .await(); + String result = resultFuture.getValue().get().getOrElse(error); + + assertThat(result) + .isEqualTo(HELLO); + } + + @Test + public void whenDivideByZero_thenGetThrowable1() { + Future resultFuture = Future.of(() -> 10 / 0); + + assertThatThrownBy(resultFuture::get) + .isInstanceOf(ArithmeticException.class); + } + + @Test + public void whenDivideByZero_thenGetThrowable2() { + Future resultFuture = Future.of(() -> 10 / 0) + .await(); + + assertThat(resultFuture.getCause().get().getMessage()) + .isEqualTo("/ by zero"); + } + + @Test + public void whenDivideByZero_thenCorrect() { + Future resultFuture = Future.of(() -> 10 / 0) + .await(); + + assertThat(resultFuture.isCompleted()).isTrue(); + assertThat(resultFuture.isSuccess()).isFalse(); + assertThat(resultFuture.isFailure()).isTrue(); + } + + @Test + public void whenAppendData_thenFutureNotEmpty() { + Future resultFuture = Future.of(() -> HELLO) + .await(); + + assertThat(resultFuture.isEmpty()) + .isFalse(); + } + + @Test + public void whenCallZip_thenCorrect() { + Future f1 = Future.of(() -> "hello1"); + Future f2 = Future.of(() -> "hello2"); + + assertThat(f1.zip(f2).get()) + .isEqualTo(Tuple.of("hello1", "hello2")); + } + + @Test + public void whenConvertToCompletableFuture_thenCorrect() throws InterruptedException, ExecutionException { + CompletableFuture convertedFuture = Future.of(() -> HELLO) + .toCompletableFuture(); + + assertThat(convertedFuture.get()) + .isEqualTo(HELLO); + } + + @Test + public void whenCallMap_thenCorrect() { + Future futureResult = Future.of(() -> "from Baeldung") + .map(a -> "Hello " + a) + .await(); + + assertThat(futureResult.get()) + .isEqualTo("Hello from Baeldung"); + } + + @Test + public void whenCallFlatMap_thenCorrect() { + Future futureMap = Future.of(() -> 1) + .flatMap((i) -> Future.of(() -> "Hello: " + i)); + + assertThat(futureMap.get()).isEqualTo("Hello: 1"); + } + + @Test + public void whenFutureFails_thenGetErrorMessage() { + Future future = Future.of(() -> "Hello".substring(-1)) + .recover(x -> "fallback value"); + + assertThat(future.get()) + .isEqualTo("fallback value"); + } + + @Test + public void whenFutureFails_thenGetAnotherFuture() { + Future future = Future.of(() -> "Hello".substring(-1)) + .recoverWith(x -> Future.of(() -> "fallback value")); + + assertThat(future.get()) + .isEqualTo("fallback value"); + } + + @Test + public void whenBothFuturesFail_thenGetErrorMessage() { + Future f1 = Future.of(() -> "Hello".substring(-1)); + Future f2 = Future.of(() -> "Hello".substring(-2)); + + Future errorMessageFuture = f1.fallbackTo(f2); + Future errorMessage = errorMessageFuture.failed(); + + assertThat( + errorMessage.get().getMessage()) + .isEqualTo("String index out of range: -1"); + } +} diff --git a/vertx-and-rxjava/pom.xml b/vertx-and-rxjava/pom.xml index b0668c34a6..cbc94dd8f1 100644 --- a/vertx-and-rxjava/pom.xml +++ b/vertx-and-rxjava/pom.xml @@ -1,7 +1,8 @@ - + + 4.0.0 + vertx-and-rxjava com.baeldung @@ -9,63 +10,42 @@ 1.0.0-SNAPSHOT - 4.0.0 - vertx-and-rxjava + + + io.vertx + vertx-rx-java2 + ${vertx.version} + + + io.vertx + vertx-core + ${vertx.version} + + + io.vertx + vertx-unit + ${vertx.version} + test + + org.apache.maven.plugins maven-compiler-plugin - 3.7.0 + ${maven-compiler-plugin.version} - 1.8 - 1.8 + ${java.version} + ${java.version} - - - - 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 - - - + + 3.5.0.Beta1 + 1.2.3 + \ 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 index 71e05a4e24..8b6abffc76 100644 --- a/vertx-and-rxjava/src/test/resources/logback-test.xml +++ b/vertx-and-rxjava/src/test/resources/logback-test.xml @@ -1,7 +1,7 @@ - [%thread{32}] %-5level %msg - %logger%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/vertx/pom.xml b/vertx/pom.xml index b5ca43b1f4..7e494c5914 100644 --- a/vertx/pom.xml +++ b/vertx/pom.xml @@ -1,36 +1,35 @@ - + 4.0.0 - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + com.baeldung vertx 1.0-SNAPSHOT vertx http://maven.apache.org - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + io.vertx vertx-core - 3.0.0 + ${vertx.version} - io.vertx vertx-web - 3.0.0 + ${vertx.version} - io.vertx vertx-unit - 3.0.0 + ${vertx.version} test @@ -40,7 +39,7 @@ org.apache.maven.plugins maven-shade-plugin - 2.3 + ${maven-shade-plugin.version} package @@ -49,15 +48,14 @@ - + io.vertx.core.Starter com.baeldung.SimpleServerVerticle - + ${project.build.directory}/${project.artifactId}-${project.version}-app.jar @@ -67,10 +65,9 @@ - - + 3.0.0 6.10 - + 2.3 diff --git a/vertx/src/main/resources/logback.xml b/vertx/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/vertx/src/main/resources/logback.xml +++ b/vertx/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/video-tutorials/jackson-annotations/pom.xml b/video-tutorials/jackson-annotations/pom.xml index c315efa713..748721b83c 100644 --- a/video-tutorials/jackson-annotations/pom.xml +++ b/video-tutorials/jackson-annotations/pom.xml @@ -1,6 +1,7 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + com.baeldung jackson-annotations 1.0.0-SNAPSHOT @@ -84,7 +85,7 @@ io.rest-assured rest-assured - 3.0.1 + ${rest-assured.version} test @@ -98,7 +99,7 @@ io.rest-assured json-schema-validator - 3.0.0 + ${rest-assured-json-schema-validator.version} test @@ -137,35 +138,25 @@ - - 4.3.11.Final - 5.1.38 - 2.8.5 - 5.1.3.Final 2.9.6 2.8.0 4.1 - 20.0 3.5 2.5 - 2.8.9 - 4.4.1 - 4.5 - 2.9.0 + 3.0.1 + 3.0.0 3.6.1 2.2.6 3.0.1 - - - + \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/src/main/resources/logback.xml b/video-tutorials/jackson-annotations/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/video-tutorials/jackson-annotations/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/video-tutorials/pom.xml b/video-tutorials/pom.xml index cbaf5e3680..ca3b39904f 100644 --- a/video-tutorials/pom.xml +++ b/video-tutorials/pom.xml @@ -1,24 +1,23 @@ + 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 video-tutorials 1.0.0-SNAPSHOT - pom video-tutorials com.baeldung parent-java - 0.0.1-SNAPSHOT - ../parent-java + 0.0.1-SNAPSHOT + ../parent-java jackson-annotations - diff --git a/vraptor/pom.xml b/vraptor/pom.xml index c5978173ab..ae43d8e083 100644 --- a/vraptor/pom.xml +++ b/vraptor/pom.xml @@ -1,33 +1,30 @@ - + 4.0.0 com.baeldung vraptor 1.0.0 war - A demo project to start using VRaptor 4 + com.baeldung parent-modules 1.0.0-SNAPSHOT - - UTF-8 - 2.1.2.Final - br.com.caelum vraptor - 4.2.0.Final + ${vraptor.version} org.jboss.weld.servlet weld-servlet-core - 2.1.2.Final + ${weld.version} org.jboss.spec.javax.el @@ -39,7 +36,7 @@ org.jboss.weld weld-core-impl - 2.1.2.Final + ${weld.version} org.jboss.spec.javax.el @@ -51,63 +48,63 @@ javax.el el-api - 2.2 + ${el.version} provided org.hibernate hibernate-validator-cdi - 5.1.1.Final + ${hibernate-validator.version} javax.servlet jstl - 1.2 + ${jstl.version} javax.servlet javax.servlet-api - 3.1.0 + ${servlet.version} provided org.slf4j slf4j-log4j12 - 1.7.5 + ${slf4j-log4j12.version} br.com.caelum.vraptor vraptor-freemarker - 4.1.0-RC3 + ${vraptor-freemarker.version} br.com.caelum.vraptor vraptor-hibernate - 4.0.4 + ${vraptor-hibernate.version} mysql mysql-connector-java - 8.0.8-dmr + ${mysql-connector.version} org.mindrot jbcrypt - 0.4 + ${jbcrypt.version} org.freemarker freemarker - 2.3.27-incubating + ${freemarker.version} @@ -119,11 +116,28 @@ org.apache.tomcat.maven tomcat7-maven-plugin - 2.1 + ${tomcat7-maven-plugin.version} / - + + + 4.2.0.Final + 2.1.2.Final + 2.2 + 5.1.1.Final + 1.2 + 3.1.0 + 1.7.5 + 4.1.0-RC3 + 4.0.4 + 8.0.8-dmr + 0.4 + 2.3.27-incubating + 2.1 + + + \ No newline at end of file diff --git a/wicket/pom.xml b/wicket/pom.xml index d3cb319902..99be467167 100644 --- a/wicket/pom.xml +++ b/wicket/pom.xml @@ -1,8 +1,8 @@ - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 + com.baeldung.wicket.examples wicket war @@ -15,12 +15,6 @@ 1.0.0-SNAPSHOT - - 7.5.0 - 9.2.13.v20150730 - 2.6 - UTF-8 - @@ -37,6 +31,7 @@ test + @@ -86,4 +81,11 @@ + + + 7.5.0 + 9.2.13.v20150730 + 2.6 + + diff --git a/wicket/src/main/resources/logback.xml b/wicket/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/wicket/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/xml/README.md b/xml/README.md index 7c3ebccac6..80c6a069f0 100644 --- a/xml/README.md +++ b/xml/README.md @@ -2,3 +2,4 @@ - [Intro to XPath with Java](http://www.baeldung.com/java-xpath) - [Introduction to JiBX](http://www.baeldung.com/jibx) - [XML Libraries Support in Java](http://www.baeldung.com/java-xml-libraries) +- [DOM parsing with Xerces](http://www.baeldung.com/java-xerces-dom-parsing) diff --git a/xml/pom.xml b/xml/pom.xml index c417ceb15d..5490f3a89f 100644 --- a/xml/pom.xml +++ b/xml/pom.xml @@ -1,7 +1,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 xml 0.1-SNAPSHOT xml @@ -12,32 +11,6 @@ 1.0.0-SNAPSHOT - - - jibx.sf.net - JiBX repository - http://jibx.sf.net/maven2 - - never - - - false - - - - - - jibx.sf.net - JiBX repository - http://jibx.sf.net/maven2 - - never - - - false - - - @@ -82,12 +55,12 @@ jibx-run ${jibx-version} + commons-lang commons-lang ${commons-lang.version} - @@ -166,7 +139,6 @@ - @@ -194,23 +166,7 @@ template-binding.xml - true - - - - process-classes - - bind - - - - - - org.jibx - maven-jibx-plugin - 1.3.1 - - src/main/resources + src/main/resources *-binding.xml @@ -218,6 +174,14 @@ + process-classes + process-classes + + bind + + + + process-test-classes process-test-classes test-bind @@ -225,7 +189,6 @@ - org.apache.maven.plugins maven-compiler-plugin @@ -235,8 +198,7 @@ - + maven-assembly-plugin ${project.basedir} @@ -266,9 +228,36 @@ - - + + + + jibx.sf.net + JiBX repository + http://jibx.sf.net/maven2 + + never + + + false + + + + + + + jibx.sf.net + JiBX repository + http://jibx.sf.net/maven2 + + never + + + false + + + + 1.6.1 1.1.6 @@ -282,11 +271,8 @@ 2.4 1.8 - 1.3.1 - - diff --git a/xml/src/main/resources/logback.xml b/xml/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/xml/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/xml/src/test/resources/example_dom4j_new.xml b/xml/src/test/resources/example_dom4j_new.xml deleted file mode 100644 index 020760fdd3..0000000000 --- a/xml/src/test/resources/example_dom4j_new.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - XML with Dom4J - XML handling with Dom4J - 14/06/2016 - Dom4J tech writer - - diff --git a/xml/src/test/resources/example_dom4j_updated.xml b/xml/src/test/resources/example_dom4j_updated.xml deleted file mode 100755 index 962ca0c889..0000000000 --- a/xml/src/test/resources/example_dom4j_updated.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - Guava updated - Introduction to Guava - 04/04/2016 - GuavaAuthor - - - XML updated - Introduction to XPath - 04/05/2016 - XMLAuthor - - - Android updated - Introduction to Android - 04/03/2016 - AndroidAuthor - - - Spring updated - Introduction to Spring - 04/02/2016 - SpringAuthor - -
    Spring Core
    -
    Spring MVC
    -
    Spring Batch
    -
    -
    -
    \ No newline at end of file diff --git a/xml/src/test/resources/example_jaxb_new.xml b/xml/src/test/resources/example_jaxb_new.xml deleted file mode 100644 index 646d938869..0000000000 --- a/xml/src/test/resources/example_jaxb_new.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - Jaxb author - 04/02/2015 - XML Binding with Jaxb - XML with Jaxb - - diff --git a/xmlunit-2/pom.xml b/xmlunit-2/pom.xml index 171f3de03c..806ebb6c0e 100644 --- a/xmlunit-2/pom.xml +++ b/xmlunit-2/pom.xml @@ -1,10 +1,9 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung xmlunit-2 1.0 - XMLUnit-2 com.baeldung @@ -18,7 +17,6 @@ xmlunit-matchers ${xmlunit.version} - org.xmlunit xmlunit-core @@ -28,7 +26,6 @@ - 2.3.0 diff --git a/xmlunit-2/src/main/resources/logback.xml b/xmlunit-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/xmlunit-2/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/xstream/pom.xml b/xstream/pom.xml index b8462ac34d..64c8198082 100644 --- a/xstream/pom.xml +++ b/xstream/pom.xml @@ -1,6 +1,7 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + org.baeldung xstream 0.0.1-SNAPSHOT @@ -19,7 +20,6 @@ xstream ${xstream.version} - org.codehaus.jettison jettison diff --git a/xstream/src/main/resources/logback.xml b/xstream/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/xstream/src/main/resources/logback.xml +++ b/xstream/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n